trtc-sdk-v5 5.11.2-wasm.3 → 5.12.0-beta.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/debug-dialog.js +1 -1
- package/index.d.ts +2 -0
- package/package.json +6 -4
- 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/device-detector.esm.js +17 -15
- package/plugins/device-detector/device-detector.umd.js +2 -2
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-decoder/video-decoder.esm.js +1 -1
- package/plugins/video-decoder/video-decoder.umd.js +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.d.ts +70 -13
- package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.esm.js +1 -1
- package/plugins/video-effect/virtual-background/virtual-background.umd.js +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +44 -64
- package/trtc.js +1 -1
- package/assets/av_processing.wasm +0 -0
- package/assets/worker.js +0 -17
package/trtc.esm.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
-
var aE=Object.create;var An=Object.defineProperty,cE=Object.defineProperties,zp=Object.getOwnPropertyDescriptor,dE=Object.getOwnPropertyDescriptors,uE=Object.getOwnPropertyNames,Jp=Object.getOwnPropertySymbols,Xp=Object.getPrototypeOf,Qp=Object.prototype.hasOwnProperty,lE=Object.prototype.propertyIsEnumerable,mE=Reflect.get;var Gi=Math.pow,zu=(i,t,e)=>t in i?An(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,X=(i,t)=>{for(var e in t||(t={}))Qp.call(t,e)&&zu(i,e,t[e]);if(Jp)for(var e of Jp(t))lE.call(t,e)&&zu(i,e,t[e]);return i},Te=(i,t)=>cE(i,dE(t));var bn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),ei=(i,t)=>{for(var e in t)An(i,e,{get:t[e],enumerable:!0})},pE=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of uE(t))!Qp.call(i,o)&&o!==e&&An(i,o,{get:()=>t[o],enumerable:!(r=zp(t,o))||r.enumerable});return i};var ji=(i,t,e)=>(e=i!=null?aE(Xp(i)):{},pE(t||!i||!i.__esModule?An(e,"default",{value:i,enumerable:!0}):e,i));var Z=(i,t,e,r)=>{for(var o=r>1?void 0:r?zp(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&&An(t,e,o),o};var u=(i,t,e)=>zu(i,typeof t!="symbol"?t+"":t,e);var Bt=(i,t,e)=>mE(Xp(i),e,t);var y=(i,t,e)=>new Promise((r,o)=>{var s=l=>{try{c(e.next(l))}catch(m){o(m)}},n=l=>{try{c(e.throw(l))}catch(m){o(m)}},c=l=>l.done?r(l.value):Promise.resolve(l.value).then(s,n);c((e=e.apply(i,t)).next())});var Zi=bn((Oy,Ml)=>{"use strict";var E_=Object.prototype.hasOwnProperty,Wt="~";function Kn(){}Object.create&&(Kn.prototype=Object.create(null),new Kn().__proto__||(Wt=!1));function __(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function Ch(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new __(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 zc(i,t){--i._eventsCount===0?i._events=new Kn:delete i._events[t]}function Ut(){this._events=new Kn,this._eventsCount=0}Ut.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)E_.call(e,r)&&t.push(Wt?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Ut.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};Ut.prototype.listenerCount=function(t){var e=Wt?Wt+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Ut.prototype.emit=function(t,e,r,o,s,n){var c=Wt?Wt+t:t;if(!this._events[c])return!1;var l=this._events[c],m=arguments.length,f,E;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),m){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,r),!0;case 4:return l.fn.call(l.context,e,r,o),!0;case 5:return l.fn.call(l.context,e,r,o,s),!0;case 6:return l.fn.call(l.context,e,r,o,s,n),!0}for(E=1,f=new Array(m-1);E<m;E++)f[E-1]=arguments[E];l.fn.apply(l.context,f)}else{var _=l.length,v;for(E=0;E<_;E++)switch(l[E].once&&this.removeListener(t,l[E].fn,void 0,!0),m){case 1:l[E].fn.call(l[E].context);break;case 2:l[E].fn.call(l[E].context,e);break;case 3:l[E].fn.call(l[E].context,e,r);break;case 4:l[E].fn.call(l[E].context,e,r,o);break;default:if(!f)for(v=1,f=new Array(m-1);v<m;v++)f[v-1]=arguments[v];l[E].fn.apply(l[E].context,f)}}return!0};Ut.prototype.on=function(t,e,r){return Ch(this,t,e,r,!1)};Ut.prototype.once=function(t,e,r){return Ch(this,t,e,r,!0)};Ut.prototype.removeListener=function(t,e,r,o){var s=Wt?Wt+t:t;if(!this._events[s])return this;if(!e)return zc(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&zc(this,s);else{for(var c=0,l=[],m=n.length;c<m;c++)(n[c].fn!==e||o&&!n[c].once||r&&n[c].context!==r)&&l.push(n[c]);l.length?this._events[s]=l.length===1?l[0]:l:zc(this,s)}return this};Ut.prototype.removeAllListeners=function(t){var e;return t?(e=Wt?Wt+t:t,this._events[e]&&zc(this,e)):(this._events=new Kn,this._eventsCount=0),this};Ut.prototype.off=Ut.prototype.removeListener;Ut.prototype.addListener=Ut.prototype.on;Ut.prefixed=Wt;Ut.EventEmitter=Ut;typeof Ml!="undefined"&&(Ml.exports=Ut)});var td=bn((uA,$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(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(Fh).forEach(function(i){var t=Fh[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Wh=bn(fi=>{"use strict";var Gs=function(i){return String(Number(i))===i?Number(i):i},v_=function(i,t,e,r){if(r&&!e)t[r]=Gs(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Gs(i[o+1]))},C_=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;v_(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},Bh=td(),N_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);fi.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(N_).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var c=0;c<(Bh[s]||[]).length;c+=1){var l=Bh[s][c];if(l.reg.test(n))return C_(l,r,n)}}),t.media=e,t};var Hh=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Gs(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};fi.parseParams=function(i){return i.split(/;\s?/).reduce(Hh,{})};fi.parseFmtpConfig=fi.parseParams;fi.parsePayloads=function(i){return i.toString().split(" ").map(Number)};fi.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Gs),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};fi.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(Hh,{})})};fi.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Gs(e):(r=Gs(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var jh=bn((mA,Gh)=>{"use strict";var ql=td(),D_=/%[sdv%]/g,w_=function(i){var t=1,e=arguments,r=e.length;return i.replace(D_,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""}})},ca=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 w_.apply(null,o)},M_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],O_=["i","c","b","a"];Gh.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||M_,r=t.innerOrder||O_,o=[];return e.forEach(function(s){ql[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(ca(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(c){o.push(ca(s,n,c))})})}),i.media.forEach(function(s){o.push(ca("m",ql.m[0],s)),r.forEach(function(n){ql[n].forEach(function(c){c.name in s&&s[c.name]!=null?o.push(ca(n,c,s)):c.push in s&&s[c.push]!=null&&s[c.push].forEach(function(l){o.push(ca(n,c,l))})})})}),o.join(`\r
|
|
1
|
+
var Yf=Object.create;var hs=Object.defineProperty,Zf=Object.defineProperties,Ah=Object.getOwnPropertyDescriptor,Kf=Object.getOwnPropertyDescriptors,e_=Object.getOwnPropertyNames,Ln=Object.getOwnPropertySymbols,Ch=Object.getPrototypeOf,td=Object.prototype.hasOwnProperty,Rh=Object.prototype.propertyIsEnumerable,t_=Reflect.get;var or=Math.pow,ed=(o,i,e)=>i in o?hs(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,v=(o,i)=>{for(var e in i||(i={}))td.call(i,e)&&ed(o,e,i[e]);if(Ln)for(var e of Ln(i))Rh.call(i,e)&&ed(o,e,i[e]);return o},w=(o,i)=>Zf(o,Kf(i));var yh=(o,i)=>{var e={};for(var t in o)td.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&Ln)for(var t of Ln(o))i.indexOf(t)<0&&Rh.call(o,t)&&(e[t]=o[t]);return e};var Ni=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),vi=(o,i)=>{for(var e in i)hs(o,e,{get:i[e],enumerable:!0})},i_=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of e_(i))!td.call(o,r)&&r!==e&&hs(o,r,{get:()=>i[r],enumerable:!(t=Ah(i,r))||t.enumerable});return o};var Ge=(o,i,e)=>(e=o!=null?Yf(Ch(o)):{},i_(i||!o||!o.__esModule?hs(e,"default",{value:o,enumerable:!0}):e,o));var D=(o,i,e,t)=>{for(var r=t>1?void 0:t?Ah(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&hs(i,e,r),r};var d=(o,i,e)=>ed(o,typeof i!="symbol"?i+"":i,e);var We=(o,i,e)=>t_(Ch(o),e,i);var f=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var tt=Ni((SS,id)=>{"use strict";var r_=Object.prototype.hasOwnProperty,et="~";function ms(){}Object.create&&(ms.prototype=Object.create(null),new ms().__proto__||(et=!1));function o_(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function bh(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new o_(e,t||o,r),n=et?et+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function Pn(o,i){--o._eventsCount===0?o._events=new ms:delete o._events[i]}function je(){this._events=new ms,this._eventsCount=0}je.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)r_.call(e,t)&&i.push(et?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};je.prototype.listeners=function(i){var e=et?et+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};je.prototype.listenerCount=function(i){var e=et?et+i:i,t=this._events[e];return t?t.fn?1:t.length:0};je.prototype.emit=function(i,e,t,r,s,n){var a=et?et+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,h;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c.fn.apply(c.context,u)}else{var m=c.length,_;for(h=0;h<m;h++)switch(c[h].once&&this.removeListener(i,c[h].fn,void 0,!0),l){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,e);break;case 3:c[h].fn.call(c[h].context,e,t);break;case 4:c[h].fn.call(c[h].context,e,t,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];c[h].fn.apply(c[h].context,u)}}return!0};je.prototype.on=function(i,e,t){return bh(this,i,e,t,!1)};je.prototype.once=function(i,e,t){return bh(this,i,e,t,!0)};je.prototype.removeListener=function(i,e,t,r){var s=et?et+i:i;if(!this._events[s])return this;if(!e)return Pn(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&Pn(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:Pn(this,s)}return this};je.prototype.removeAllListeners=function(i){var e;return i?(e=et?et+i:i,this._events[e]&&Pn(this,e)):(this._events=new ms,this._eventsCount=0),this};je.prototype.off=je.prototype.removeListener;je.prototype.addListener=je.prototype.on;je.prefixed=et;je.EventEmitter=je;typeof id!="undefined"&&(id.exports=je)});var Na=Ni((FI,gm)=>{"use strict";var _m=gm.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(_m).forEach(function(o){var i=_m[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Sm=Ni(Gi=>{"use strict";var Uo=function(o){return String(Number(o))===o?Number(o):o},lg=function(o,i,e,t){if(t&&!e)i[t]=Uo(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=Uo(o[r+1]))},ug=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;lg(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},Tm=Na(),hg=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Gi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(hg).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Tm[s]||[]).length;a+=1){var c=Tm[s][a];if(c.reg.test(n))return ug(c,t,n)}}),i.media=e,i};var Em=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=Uo(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Gi.parseParams=function(o){return o.split(/;\s?/).reduce(Em,{})};Gi.parseFmtpConfig=Gi.parseParams;Gi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Gi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(Uo),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Gi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Em,{})})};Gi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Uo(e):(t=Uo(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Am=Ni(($I,Im)=>{"use strict";var pl=Na(),mg=/%[sdv%]/g,pg=function(o){var i=1,e=arguments,t=e.length;return o.replace(mg,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Ws=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return pg.apply(null,r)},fg=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_g=["i","c","b","a"];Im.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||fg,t=i.innerOrder||_g,r=[];return e.forEach(function(s){pl[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(Ws(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(Ws(s,n,a))})})}),o.media.forEach(function(s){r.push(Ws("m",pl.m[0],s)),t.forEach(function(n){pl[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(Ws(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(Ws(n,a,c))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var qh=bn(Wr=>{"use strict";var jo=Wh(),x_=jh(),P_=td();Wr.grammar=P_;Wr.write=x_;Wr.parse=jo.parse;Wr.parseParams=jo.parseParams;Wr.parseFmtpConfig=jo.parseFmtpConfig;Wr.parsePayloads=jo.parsePayloads;Wr.parseRemoteCandidates=jo.parseRemoteCandidates;Wr.parseImageAttributes=jo.parseImageAttributes;Wr.parseSimulcastStreamList=jo.parseSimulcastStreamList});var Yp=(te=>(te[te.INVALID_PARAMETER=4096]="INVALID_PARAMETER",te[te.INVALID_OPERATION=4097]="INVALID_OPERATION",te[te.NOT_SUPPORTED=4098]="NOT_SUPPORTED",te[te.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",te[te.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",te[te.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",te[te.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",te[te.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",te[te.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",te[te.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",te[te.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",te[te.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",te[te.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",te[te.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",te[te.CLIENT_BANNED=16448]="CLIENT_BANNED",te[te.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",te[te.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",te[te.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",te[te.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",te[te.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",te[te.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",te[te.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",te[te.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",te[te.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",te[te.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",te[te.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",te[te.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",te[te.API_CALL_ABORTED=16461]="API_CALL_ABORTED",te[te.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",te[te.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",te[te.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",te[te.UNKNOWN=65535]="UNKNOWN",te))(Yp||{}),q=Yp;var hE=function(i){for(let t in q)if(q[t]===i)return t;return"UNKNOWN"},Xu=class extends Error{constructor({name:e="RtcError",message:r,code:o=q.UNKNOWN,extraCode:s=0,constraint:n}){let c=`<${hE(o)} 0x${o.toString(16)}>`,l=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(c)?"":` ${c}`}`;super(l);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=l,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ue=Xu;var ly=new Date().getTime(),fE=0;var Rn=function(){return new Date().getTime()+fE},hc=function(){let i=new Date;return i.setTime(Rn()),i.toLocaleString()},Ss=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 Vr={};ei(Vr,{bytes2ms:()=>ah,calculateScaleResolutionDownNumber:()=>Nc,convertObjectNumberToInt:()=>Vn,copyProperties:()=>nh,deepClone:()=>Po,deepMerge:()=>ur,delay:()=>Fn,fibonacci:()=>ko,formatedTime:()=>bc,getConstructorName:()=>vs,getContainerFromElement:()=>fh,getEnv:()=>ih,getInternalVersion:()=>ph,getLoggerUrl:()=>si,getMediaStreamTrackInfo:()=>Cc,getMuteStateFromFlag:()=>Ln,getNetworkType:()=>xn,getNumNetworkType:()=>Ac,getReconnectionTimeout:()=>dh,getStringByteLength:()=>gh,getTurnServer:()=>hh,getUint32Version:()=>Rc,getValueType:()=>ct,getViewListFromView:()=>Ds,glog:()=>Pn,ipv4ToUint32:()=>Ns,isArray:()=>ot,isAudioWorkletSupported:()=>mh,isBoolean:()=>st,isConstructor:()=>Lo,isEmpty:()=>Cs,isFunction:()=>We,isLangChinese:()=>Sr,isMediaStreamTrack:()=>uh,isNumber:()=>ke,isObject:()=>er,isOverseaSdkAppId:()=>oi,isPlainObject:()=>Lt,isPortrait:()=>cl,isPromise:()=>Ji,isRemoteTrack:()=>lh,isRotate90Or270:()=>ni,isString:()=>Oe,isUndefined:()=>P,loadImage:()=>ws,ms2bytes:()=>ch,ms2samples:()=>al,normalizeUrl:()=>Uo,performanceNow:()=>Ie,promiseAny:()=>kn,samples2ms:()=>nl,setNetworkType:()=>sh,stringify:()=>dr,stringifyIncludeValue:()=>Un,throttlePromise:()=>vc});var sl={};ei(sl,{AUDIO_MUTE_BIT:()=>Tc,AUDIO_STAT_BIT:()=>bs,AUX_STAT_BIT:()=>Dn,AUX_STREAM_MSID:()=>CE,BACKEND_ENV:()=>_c,BASE_DOC_URL:()=>Lr,BASE_HOST:()=>Zp,CAPABILITIES_KEYS:()=>yc,CLASS_NAME:()=>YE,CLOUD_CONSOLE_URL:()=>TE,CROSS_ROOM_BIT:()=>RE,DATA_FREEZE_TIMING:()=>Sc,DOC_URL:()=>IE,DTLS_STATE_UNKNOWN:()=>UE,ENV_NAME:()=>ti,EXCHANGE_SDP_TIMEOUT:()=>WE,IS_WORKER:()=>ys,IS_WORKLET:()=>vn,KIBANA_EVENT:()=>ri,LOCAL_STREAM_PUBLISH_STATE:()=>eh,LOGGER_CMD_TYPE:()=>qi,LOGGER_DOMAIN:()=>Zu,LOGGER_DOMAIN_OVERSEA:()=>Ku,LOG_LEVEL:()=>Tr,LOG_LEVEL_NAME:()=>KE,MAIN_STREAM_MSID:()=>vE,MAX_RTT:()=>Mn,MICROPHONE_COMMUNICATIONS:()=>ZE,MICROPHONE_DEFAULT:()=>xo,MUTE_ALL_BIT:()=>bE,NAME:()=>D,NETWORK_TYPE:()=>Mo,NOT_SUPPORTED_H264:()=>jE,PAUSED_RETRY_COUNT:()=>Oo,PEERCONNECTION_CONNECTING_TIMEOUT:()=>XE,PEER_CONNECTION_STATE:()=>VE,PEER_LEAVE_REASON:()=>th,RECOVER_CAPTURE_INTERVAL:()=>Rs,REMOTE_STREAM_TYPE_AUX:()=>DE,REMOTE_STREAM_TYPE_MAIN:()=>NE,RENDER_FREEZE_TIMING:()=>qE,SCHEDULE_DOMAIN:()=>ii,SCHEDULE_TIMEOUT:()=>QE,SDP_SEMANTICS_PLAN_B:()=>GE,SDP_SEMANTICS_UNIFIED_PLAN:()=>ol,SECOND_HOST:()=>EE,SIGNAL_PING_PONG_INTERVAL:()=>yE,SIGNAL_PING_TIMEOUT:()=>SE,SIGNAL_RECONNECTION_COUNT:()=>$E,SMALL_STAT_BIT:()=>rl,SPEAKER_DEFAULT:()=>wn,STORAGE_EXPIRES_TIME:()=>fc,STREAM_TYPE_BIG:()=>JE,STREAM_TYPE_SMALL:()=>zE,SUBSCRIBE_SMALL_RETRY_COUNT:()=>e_,SYNC_USER_LIST_INTERVAL:()=>BE,Scene:()=>Ur,THIRD_HOST:()=>_E,TRANSPORT_DIRECTION:()=>AE,TRTC_ERROR_ASSISTANCE:()=>el,TRTC_QUALITY_BAD:()=>PE,TRTC_QUALITY_DISCONNECTED:()=>LE,TRTC_QUALITY_EXCELLENT:()=>ME,TRTC_QUALITY_GOOD:()=>OE,TRTC_QUALITY_POOR:()=>xE,TRTC_QUALITY_UNKNOWN:()=>wE,TRTC_QUALITY_VERY_BAD:()=>kE,UPDATE_OFFER_TIMEOUT:()=>HE,VIDEO_MUTE_BIT:()=>Ic,VIDEO_STAT_BIT:()=>As,audioProfileMap:()=>gc,defaultBigVideoProfile:()=>Nn,defaultSmallVideoProfile:()=>tl,getRetryCount:()=>FE,getScriptDir:()=>gE,innerVersion:()=>Qu,loggerProxy:()=>Cn,screenProfileMap:()=>Ec,setLoggerProxy:()=>wo,setRetryCount:()=>il,setVersion:()=>Yu,version:()=>at,videoProfileMap:()=>Ir});var Qu="4.15.00.1600",at="5.0.0";function Yu(i){at=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Qu=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var ys=typeof importScripts!="undefined",vn=typeof registerProcessor!="undefined",gE=()=>{let i=ys?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},Cn="",wo=i=>Cn=i,Zp="web.sdk.qcloud.com",EE="web.sdk.tencent.cn",_E="web.sdk.cloud.tencent.cn",TE="https://console.cloud.tencent.com/trtc",Lr=`https://${Zp}/trtc/webrtc/v5/doc`,IE=`${Lr}/zh-cn/`,Zu="https://yun.tim.qq.com",Ku="https://apisgp.my-imcloud.com",el="trtc_error_assistance",qi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ti={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Tr=(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))(Tr||{}),SE=18e3,yE=2e3,Mo={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},fc=7*24*3600*1e3,gc={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}},Ir={"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}},Nn=Ir["480p_2"],tl=Ir["120p_2"],Ec={"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}},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"},AE={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},_c={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ur=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ur||{}),As=1,rl=2,Dn=4,bs=8,Tc=64,Ic=16,bE=112,RE=128,vE="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",CE="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",NE=D.MAIN,DE=D.AUXILIARY,wE=0,ME=1,OE=2,xE=3,PE=4,kE=5,LE=6,UE="unknown",VE={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Kp=1/0;function il(i){Kp=i}function FE(){return Kp}var $E=30,ri={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"},BE=1e4,HE=1e4,WE=1e4,ol="unified-plan",GE="plan-b",jE=1028,eh=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(eh||{}),Sc=500,qE=1e3,JE=D.BIG,zE=D.SMALL,XE=10*1e3,ii={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"},QE=2e3,YE={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Oo=5,xo="default",wn=xo,ZE="communications",KE=Object.keys(Tr),th=["normal leave","timeout leave","kick","role change"],e_=10,Rs=2e3,yc=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Mn=10*1e3;var ih=function(){return new URLSearchParams(location.search).get("trtc_env")||""},oi=i=>Number(i)<14e8,si=function(i,t){let e;Cn?e=Cn:e=oi(i)?Ku:Zu;let r=Math.floor(Math.random()*Gi(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},On="unknown";function xn(){if(On!=="unknown")return On;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&&(On=oh(r,o)),On}function oh(i,t){if(Mo[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function sh(i){On=oh(i)}function Ac(){return Mo[xn()]}function nh(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 ah(i,t=48e3){return nl(i/4,t)}function nl(i,t=48e3){return i*1e3/t}function ch(i,t=48e3){return al(i,t)*4}function al(i,t=48e3){return i*t/1e3}var Pn=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Sr=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Lt=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 ko(i,t=1,e=1){return i<=1?e:ko(i-1,e,t+e)}function dh(i){return i>8?30*1e3:ko(i)*1e3}function ct(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var We=i=>typeof i=="function",P=i=>typeof i=="undefined",Oe=i=>typeof i=="string",ke=i=>typeof i=="number",st=i=>typeof i=="boolean",er=i=>ct(i)==="object",ot=i=>ct(i)==="array",uh=i=>ct(i)==="MediaStreamTrack".toLowerCase(),lh=i=>i.isRemote,Ji=i=>ct(i)==="promise",Lo=i=>We(i)&&i.prototype.constructor===i,vs=i=>Lo(i)?i.prototype.constructor.name:"",mh=typeof AudioWorkletNode!="undefined";function kn(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 Ie(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var rh=i=>+i<10?`0${i}`:i,ph=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=rh(e[1])+rh(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},t_=Object.prototype.hasOwnProperty,{toString:gy}=Object.prototype;function Cs(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(Lt(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(t_.call(i,t))return!1;return!0}}return!1}function Ln(i,t){return{userId:t,hasAudio:!!(i&bs),hasVideo:!!(i&As),hasAuxiliary:!!(i&Dn),hasSmall:!!(i&rl),audioMuted:!!(i&Tc),videoMuted:!!(i&Ic),audioAvailable:!!(i&bs)&&!(i&Tc),videoAvailable:!!(i&As)&&!(i&Ic)}}function hh(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!P(i.username)&&!P(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",P(i.credentialType)||(t.credentialType=i.credentialType)),t}function Ns(i,t=!0){if(!Oe(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 ur=function(i,t,e,r){if(!(er(i)&&er(t)))return 0;let o=0,s=Object.keys(t),n;for(let c=0,l=s.length;c<l;c++)if(n=s[c],!(P(t[n])||e&&e.includes(n)))if(er(i[n])&&er(t[n]))o+=ur(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=Po(t[n]),o+=1)}return o};function Po(i){if(ot(i)){let t=[];return i.forEach((e,r)=>{t[r]=Po(e)}),t}if(er(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Po(i[e])}),t}return i}var Ds=i=>{let t=[];if(ot(i))t=[...i];else if(Oe(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},fh=i=>Oe(i)?document.getElementById(i):i,r_=i=>{let t=l=>l<10?`0${l}`:`${l}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),c=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${c}`},bc=()=>r_(new Date);function dr(i,{keysToInclude:t,keysToExclude:e}){try{if(ot(i))return`[${i.map(n=>dr(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!Lt(i)||!ot(t)&&!ot(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]=Lt(i[n])||ot(i[n])?JSON.parse(dr(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function Un(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),dr(i,{keysToInclude:e})}function gh(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var cl=()=>{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},ws=i=>y(void 0,null,function*(){return new Promise((t,e)=>{let r;if(Oe(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 ue({code:q.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),Rc=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},Vn=i=>(Object.keys(i).forEach(t=>{ke(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(Lt(i[t])||ot(i[t]))&&Vn(i[t])}),i);function Fn(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function vc(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function Uo(i){return i.replace(/(^|[^:])\/{2,}/g,"$1/")}function Cc(i){var t;try{let{width:e,height:r,frameRate:o,sampleRate:s,sampleSize:n,channelCount:c}=(t=i.getSettings)==null?void 0:t.call(i),l=i.kind===D.AUDIO?`${s}x${n}@${c}`:`${e}x${r}@${o}`,m=i.stats?` stats: ${JSON.stringify(i.stats).replaceAll('"',"")}`:"";return`${i.id} ${i.readyState} muted:${i.muted} ${i.kind} ${i.label} ${l}${m}`}catch(e){return""}}function Nc(i,t){return i.width*i.height===t.width*t.height?1:cl()&&t.width>t.height&&i.height>t.width?Math.max(i.width/t.height,i.height/t.width,1):Math.max(i.width/t.width,i.height/t.height,1)}function ni(i){return i===90||i===270}function ai({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(l=>l.text()).then(l=>{try{s({data:JSON.parse(l)})}catch(m){s({data:l})}},n);let c=new XMLHttpRequest;c.onreadystatechange=()=>{if(c.readyState===4)if(c.status>=200&&c.status<300)try{let l=JSON.parse(c.response);s({data:l})}catch(l){s({data:c.response})}else n({status:c.status,statusText:c.statusText||"request failed!"})},c.timeout=r||5e3,c.open(e,i,!0),c.send(t)})}function dl(i){return y(this,null,function*(){let t=Ie(),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")),c=yield(yield(yield new Response(o)).blob()).arrayBuffer();return $.debug(`compressJSON ${e.length} -> ${c.byteLength} ${Ie()-t}ms`),c}catch(r){return e}})}var i_=Object.prototype.hasOwnProperty;var zi=i=>typeof i=="function",Eh=i=>typeof i=="undefined";var _h=i=>typeof i=="boolean";var ul=i=>i.isRemote;var ll=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 Th(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(ll(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(i_.call(i,t))return!1;return!0}}return!1}var o_=0,s_=1,Ih=2;function n_({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...c){let{retries:l=5,timeout:m=1e3}=t,f=0,E=-1,_=o_,v=(k,M)=>y(this,null,function*(){let N=n||this;try{let B=yield i.apply(N,c);f>0&&s&&s.call(this,f),f=0,k(B)}catch(B){let ee=()=>{clearTimeout(E),f=0,_=Ih,M(B)},me=()=>{_!==Ih&&f<(zi(l)?l():l)?(f++,_=s_,zi(r)&&r.call(this,f,ee),E=window.setTimeout(()=>{E=-1,v(k,M)},zi(m)?m(f):m)):(ee(),zi(o)&&o.call(this,B))};zi(e)?e.call(this,{error:B,retry:me,reject:M,retryFuncArgs:c,retriedCount:f}):me()}});return new Promise(v)}}var Xi=n_;var Ms=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=_h(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}`:""}]`),$.log(t,e,Eh(this.userId)||Th(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 Bs={};ei(Bs,{ANDROID_VERSION:()=>hl,CHROME_MAJOR_VERSION:()=>$r,CHROME_VERSION:()=>Jc,EDGE_VERSION:()=>Mc,EDG_MAJOR_VERSION:()=>fl,EDG_VERSION:()=>Oc,FIREFOX_MAJOR_VERSION:()=>wc,FIREFOX_VERSION:()=>Dc,HUAWEI_VERSION:()=>Hc,IE_VERSION:()=>l_,IOS_MAIN_VERSION:()=>Jt,IOS_VERSION:()=>Rr,IPADQQB_VERSION:()=>$c,IS_ANDROID:()=>mt,IS_ANDROID_WEBVIEW:()=>f_,IS_ANY_SAFARI:()=>Yi,IS_CHROME:()=>Fs,IS_CHROME_OS:()=>gl,IS_CHROMIUM_BASE:()=>ci,IS_DESKTOP_IOS_CHROME:()=>vl,IS_EDG:()=>Ps,IS_EDGE:()=>Vo,IS_ELECTRON:()=>p_,IS_FIREFOX:()=>Ht,IS_HEADLESS_CHROME:()=>Sl,IS_HONOR:()=>Tl,IS_HUAWEI:()=>_l,IS_HUAWEIBROWSER:()=>Jn,IS_IE:()=>bh,IS_IE8:()=>u_,IS_IOS:()=>lt,IS_IOS_13_OR_14:()=>Rl,IS_IOS_15_1:()=>bl,IS_IOS_CHROME:()=>Rh,IS_IPAD:()=>xs,IS_IPADQQB:()=>Gn,IS_IPAD_PRO:()=>pl,IS_IPHONE:()=>Qi,IS_IPOD:()=>Ah,IS_LINUX:()=>jn,IS_LOCAL:()=>vr,IS_MAC:()=>br,IS_MACQQB:()=>Wn,IS_MIBROWSER:()=>qn,IS_MQQB:()=>Vs,IS_NATIVE_ANDROID:()=>d_,IS_OLD_ANDROID:()=>c_,IS_OPENHARMONY:()=>Il,IS_OPPOBROWSER:()=>Xn,IS_SAFARI:()=>It,IS_SAFARI_15_1:()=>g_,IS_SAMSUNGBROWSER:()=>zn,IS_SOGOU:()=>Bn,IS_SOGOUM:()=>$n,IS_TBS:()=>Ar,IS_UCBROWSER:()=>El,IS_VIVOBROWSER:()=>Qn,IS_WECHAT:()=>Ls,IS_WIN:()=>Fo,IS_WQQB:()=>Hn,IS_WX:()=>m_,IS_X5MQQB:()=>Us,IS_XWEB:()=>ks,MACQQB_VERSION:()=>Fc,MI_VERSION:()=>Bc,MQQB_VERSION:()=>Os,OPENHARMONY_VERSION:()=>h_,OPPO_VERSION:()=>Gc,SAFARI_VERSION:()=>di,SAMSUNG_VERSION:()=>Wc,SOGOUM_VERSION:()=>xc,SOGOU_VERSION:()=>Pc,TBS_VERSION:()=>kc,UA_DATA_STRING:()=>yr,USER_AGENT:()=>tr,VIVO_VERSION:()=>jc,WECHAT_VERSION:()=>Uc,WQQB_VERSION:()=>Vc,XWEB_VERSION:()=>Lc,browserInfo:()=>Fr,getBrowserInfo:()=>vh,getChromeMajorVersion:()=>qc,getDeviceModel:()=>Yn,getGPUInfo:()=>Nl,getOSName:()=>$s,getOSNumber:()=>Zn,getOSString:()=>Bo,getOSType:()=>wl,getTerminalType:()=>Dl,getUserAgentData:()=>$o,isLocalStorageEnabled:()=>ui,isMobile:()=>Cl,isVersionLargerThan:()=>Al,isVersionSmallerThan:()=>yl});var tr=typeof navigator=="undefined"?"":navigator.userAgent,ye=i=>new RegExp(i,"i").test(tr),Et=i=>{if(ye(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=tr.match(t);if(e&&e[1])return e[1]}return""},ml=i=>{if(ye(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=tr.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Sh=/AppleWebKit\/([\d.]+)/i.exec(tr),a_=Sh?parseFloat(Sh[1]):NaN,xs=ye("iPad"),pl=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ye("Macintosh"),Qi=ye("iPhone")&&!xs,Ah=ye("iPod"),lt=Qi||xs||Ah||pl,mt=ye("Android"),hl=function(){if(mt){let i=tr.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}(),c_=mt&&ye("webkit")&&hl<2.3,d_=mt&&hl<5&&a_<537,Ht=ye("Firefox"),Dc=Et("Firefox"),wc=ml("Firefox"),Vo=ye("Edge"),Mc=Et("Edge"),Ps=ye("Edg"),Oc=Et("Edg"),fl=ml("Edg"),$n=ye("SogouMobileBrowser"),xc=Et("SogouMobileBrowser"),Bn=ye("MetaSr\\s"),Pc=Et("MetaSr\\s"),Ar=ye("TBS"),kc=Et("TBS"),ks=ye("XWEB"),Lc=Et("XWEB"),u_=ye("MSIE\\s8\\.0"),bh=ye("MSIE\\/\\d+"),l_=function(){if(bh){let i=/MSIE\s(\d+)\.\d/.exec(tr),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(tr)&&/rv:11.0/.test(tr)&&(t=11),t}return NaN}(),Ls=ye("(micromessenger|webbrowser)"),Uc=Et("MicroMessenger"),Us=!Ar&&ye("MQQBrowser")&&ye("COVC"),Vs=!Ar&&ye("MQQBrowser")&&!ye("COVC"),Os=Vs||Us?Et("MQQBrowser"):"",Hn=!Ar&&ye(" QQBrowser"),Vc=Et(" QQBrowser"),Wn=!Ar&&ye("QQBrowserLite"),Fc=Et("QQBrowserLite"),Gn=!Ar&&ye("MQBHD"),$c=Et("MQBHD"),Fo=ye("Windows"),br=!lt&&ye("MAC OS X"),jn=!mt&&ye("Linux"),gl=ye("CrOS"),m_=ye("MicroMessenger"),El=ye("UCBrowser"),p_=ye("Electron"),qn=ye("MiuiBrowser"),Bc=Et("MiuiBrowser"),Jn=ye("HuaweiBrowser"),_l=ye("Huawei")||ye("HUAWEI"),Tl=ye("Honor")||ye("HONOR"),Hc=Et("HuaweiBrowser"),zn=ye("SamsungBrowser"),Wc=Et("SamsungBrowser"),Xn=ye("HeyTapBrowser"),Gc=Et("HeyTapBrowser"),Qn=ye("VivoBrowser"),jc=Et("VivoBrowser"),Il=ye("OpenHarmony"),h_=Et("OpenHarmony"),qc=()=>ml("Chrome"),ci=ye("Chrome"),Fs=!Vo&&!Bn&&!$n&&!Ar&&!ks&&!Ps&&!Hn&&!qn&&!Jn&&!zn&&!Xn&&!Qn&&ci,Sl=ye("HeadlessChrome"),$r=qc(),Jc=Et("Chrome"),It=!ci&&!Vs&&!Us&&!Wn&&!Gn&&ye("Safari"),Yi=It||lt,di=Et("Version"),f_=/Android.*(wv|.0.0.0)/.test(tr),Rr=(()=>{if(pl)return di;if(lt){let i=tr.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})();function yl(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}function Al(i,t,e=!1){let r=i.split(".").map(s=>Number(s)),o=t.split(".").map(s=>Number(s));for(let s=0;s<Math.max(r.length,o.length);s++){let n=r[s]||0,c=o[s]||0;if(n>c)return!0;if(n<c)return!1}return e}var Jt=Number(Rr.split(".")[0]),g_=di==="15.1",bl=Rr==="15.1",Rl=(()=>{let i=Number(Rr.split(".")[0]);return i===14||i===13})(),Rh=ye("CriOS"),vl=Rh&&di==="11.1.1",vr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",ui=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Fr=vh();function vh(){let i=new Map([[Ht,["Firefox",Dc]],[Ps,["Edg",Oc]],[Fs,["Chrome",Jc]],[It,["Safari",di]],[Ar,["TBS",kc]],[ks,["XWEB",Lc]],[Ls&&Qi,["WeChat",Uc]],[Hn,["QQ(Win)",Vc]],[Vs,["QQ(Mobile)",Os]],[Us,["QQ(Mobile X5)",Os]],[Wn,["QQ(Mac)",Fc]],[Gn,["QQ(iPad)",$c]],[qn,["MI",Bc]],[Jn,["HW",Hc]],[zn,["Samsung",Wc]],[Xn,["OPPO",Gc]],[Qn,["VIVO",jc]],[Vo,["EDGE",Mc]],[$n,["SogouMobile",xc]],[Bn,["Sogou",Pc]]]),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:mt||lt||Qi||xs||Il}var yr="";function $o(){return y(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&&!yr&&(yr=`UAData: ${Ge.platform}/${Ge.platformVersion}`,Ge.architecture&&Ge.bitness&&(yr+=` ${Ge.architecture}/${Ge.bitness}`),Ge.mobile&&(yr+=" mobile"),Ge.model&&(yr+=` model: ${Ge.model.replace(/\s+/g,"/")}`),Ge.fullVersionList&&(yr+=` ${Ge.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),Ge}catch(i){return null}})}function Nl(){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 Yn(){return(Ge==null?void 0:Ge.model)||""}var yh=new Map([[mt,"Android"],[lt,"iOS"],[Fo,"Windows"],[br,"MacOS"],[jn,"Linux"],[gl,"ChromeOS"]]),$s=function(){return yh.get(!0)?yh.get(!0):Ge?Ge.platform:"unknown"};function Zn(){return Fo?1:mt?2:br?3:lt?4:jn?5:gl?6:0}var Bo=()=>{let i=$s();return i+=`/${Fr.name}/${It?Fr.version:Fr.version.split(".")[0]}`,Ge!=null&&Ge.platformVersion&&(i+=`/${Ge.platformVersion}`),Ge!=null&&Ge.architecture&&(i+=`/${Ge.architecture}`),i};function Dl(){return mt?4:Qi?2:xs?3:br?12:Fo?5:jn?13:Il?22:1}function wl(){return mt?"Android":Qi?"iPhone":xs?"iPad":br?"Mac":Fo?"Windows":jn?"Linux":"unknown"}var Nh=ji(Zi(),1),T_=new Nh.default,V=T_;var li=(ce=>(ce.ROOM_DESTROY="1",ce.JOIN_START="21",ce.JOIN_SCHEDULE_SUCCESS="22",ce.JOIN_SIGNAL_CONNECTION_START="23",ce.JOIN_SIGNAL_CONNECTION_END="24",ce.JOIN_SEND_CMD="25",ce.JOIN_RECEIVED_CMD_RES="26",ce.JOIN_SUCCESS="27",ce.JOIN_FAILED="28",ce.LEAVE_START="51",ce.LEAVE_SEND_CMD="52",ce.LEAVE_SUCCESS="53",ce.PUBLISH_START="61",ce.SEND_FIRST_VIDEO_FRAME="62",ce.PUBLISH_FAILED="63",ce.SUBSCRIBE_START="81",ce.SUBSCRIBE_SUCCESS="82",ce.SUBSCRIBE_FAILED="84",ce.UNSUBSCRIBE_SUCCESS="83",ce.LOCAL_TRACK_CAPTURE_START="101",ce.LOCAL_TRACK_CAPTURE_SUCCESS="102",ce.LOCAL_TRACK_CAPTURE_FAILED="103",ce.LOCAL_TRACK_PUBLISHED="104",ce.LOCAL_TRACK_UNPUBLISHED="105",ce.LOCAL_TRACK_REPLACED="106",ce.SWITCH_DEVICE_SUCCESS="107",ce.TRACK_MUTED="108",ce.TRACK_UNMUTED="109",ce.REMOTE_TRACK_SUBSCRIBED="110",ce.REMOTE_TRACK_UNSUBSCRIBED="111",ce.LOCAL_TRACK_RECAPTURE="112",ce.LOCAL_AUDIO_STARTED="113",ce.LOCAL_AUDIO_STOPPED="114",ce.REMOTE_AUDIO_STARTED="115",ce.REMOTE_AUDIO_STOPPED="116",ce.PLAY_TRACK_START="151",ce.PLAYER_STATE_CHANGED="152",ce.VIDEO_LOADED_DATA="153",ce.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",ce.SIGNAL_CONNECTION_STATE_CHANGED="201",ce.PEER_CONNECTION_STATE_CHANGED="202",ce.SINGLE_CONNECTION_STAT="203",ce.SPC_RECONNECTED="204",ce.HEARTBEAT_REPORT="251",ce.RECEIVED_PUBLISHED_USER_LIST="252",ce.REMOTE_PUBLISH_STATE_CHANGED="253",ce.AUDIO_LEVEL_INTERVAL="260",ce.NETWORK_QUALITY="261",ce.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",ce.QUALITY_LIMITATION_CHANGED="263",ce.LOG="264",ce.AUDIO_PROCESSOR_DEBUG="265",ce.SWITCH_ROOM_START="401",ce.SWITCH_ROOM_SUCCESS="407",ce.SWITCH_ROOM_FAILED="408",ce))(li||{});var U=li;var I_="%cTRTC%c%s",S_="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",y_="display: inline",Xc=class Xc{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);!ys&&!vn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){V.on(U.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&Tr[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),V.on(U.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),V.once(U.JOIN_FAILED,()=>{this.startUpload()}),V.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(Oe(r.userId)&&ke(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 y(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:c,logs:l}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:hc(),sdkAppId:String(c),userId:n,version:at,log:l.map(m=>m.log).join(`
|
|
4
|
-
`)}),c),l.forEach(m=>m.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Xi({retryFunction:()=>ai({url:si(e,qi.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(Rn()),`[${Ss(e)}] <${Tr[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){P(Tr[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(Oe(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var l;e.unshift(this.getPrefix(t));let n={log:e.reduce((m,f)=>`${m} ${this.logChunkToString(f)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(V.emit(U.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n),t<this._logLevel)return;let c=((l=Tr[t])==null?void 0:l.toLowerCase())||"info";Xc.PRINT_LOG_TAG?console[c](I_,S_,y_,...e):console[c](...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 Ms(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;Tr[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};u(Xc,"PRINT_LOG_TAG",!(lt||mt||Sl));var Ol=Xc,$=new Ol;var A_=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)})},ea=A_;var xl=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!ui())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(ui())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){$.warn(t)}}getItem(t){if(!ui())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){$.warn(e)}}setItem(t,e){if(ui())try{let r={expiresIn:Date.now()+fc,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){$.warn(r)}}deleteItem(t){if(!ui())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return $.warn(e),!1}}clear(){if(ui())try{localStorage.clear()}catch(t){$.warn(t)}}},Hs=new xl;var eo={};ei(eo,{HTTPS_API:()=>H_,IS_GET_CAPABILITIES_SUPPORTED:()=>tm,IS_GET_SETTINGS_SUPPORTED:()=>js,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Y_,IS_INSERTABLE_STREAM_SUPPORTED:()=>la,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>tT,IS_RTC_RTP_SENDER_SUPPORTED:()=>ua,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>of,IS_SEI_SUPPORTED:()=>ma,IS_SPC_SUPPORTED:()=>J_,basis:()=>K_,capabilityCheck:()=>im,checkSystemRequirementsInternal:()=>cd,decodeSupportStatus:()=>Xh,encodeSupportStatus:()=>Yl,getBrowserInfo:()=>nd,getDisplayResolution:()=>Qh,isAddTransceiverSupported:()=>ud,isBrowserSupported:()=>Zl,isCanvasCaptureStreamAPISupported:()=>Kh,isCanvasSmallStreamSupported:()=>ef,isGetReceiversSupported:()=>j_,isGetSendersSupported:()=>rf,isGetTransceiversSupported:()=>q_,isGetUserMediaSupported:()=>Yh,isMediaDevicesSupported:()=>ad,isMediaSessionSupported:()=>nf,isMediaStreamTrackProcessorSupported:()=>em,isReplaceTrackSupported:()=>X_,isRequestVideoFrameCallbackSupported:()=>Ei,isSIMDSupported:()=>Z_,isScaleResolutionDownBySupported:()=>tf,isScreenCaptureApiAvailable:()=>da,isSelectedCandidatePair:()=>W_,isSetParametersSupported:()=>Q_,isSmallStreamSupported:()=>dd,isStopTransceiverSupported:()=>z_,isTRTCSupported:()=>F_,isUnifiedPlanDefault:()=>G_,isUsedInHttpProtocol:()=>gi,isWebAudioSupported:()=>Zh,isWebCodecSupported:()=>sf,isWebCodecsSupported:()=>Kl,isWebRTCSupported:()=>rm,isWebTransportSupported:()=>af});var jl={};ei(jl,{AUDIO_LEVEL_SCALE:()=>pi,AudioCodecPipelineType:()=>Kc,AudioDecoderDowngradeState:()=>Ll,AudioPlayerMode:()=>$l,AudioType:()=>Vl,BASIC_TYPE:()=>hi,BannedReason:()=>Bl,CONNECTION_CLOSED_REASON:()=>wh,ClientEvent:()=>Pl,CodecType:()=>Uh,ConnectionEvent:()=>Dh,ConnectionState:()=>Yc,DECODE_FAILED_ERROR_CODE:()=>Gl,FacingMode:()=>Zc,FrameWorkType:()=>Qc,LeaveReason:()=>Hl,LocalTrackEvent:()=>ra,MULTI_VIDEO_DATA_TYPE:()=>mi,MediaType:()=>Dt,MediaTypeLabel:()=>b_,MonitorEventId:()=>oa,MutedFlag:()=>Oh,NetworkQualityValue:()=>kh,PlayerState:()=>Ho,ReceiveMode:()=>Lh,RemoteStreamType:()=>Hr,RemoteTrackEvent:()=>Ws,RoomEvent:()=>Ki,SMALL_MODE:()=>ed,SceneNumber:()=>kl,StreamEvent:()=>Mh,StreamType:()=>Ph,SubscribeMediaType:()=>ta,TIMER_TYPE:()=>Go,TRACK_ACTION:()=>xh,TRACK_KIND:()=>Ul,TrackEvent:()=>Br,UserRole:()=>zt,UserRoleNumber:()=>Wo,VideoCodec:()=>Wl,VideoCodecPipelineType:()=>na,VideoContentHint:()=>aa,VideoDecoderDowngradeState:()=>ia,VideoPlayerMode:()=>sa,VideoType:()=>Fl});var Qc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(Qc||{}),Dh=(M=>(M.TRACK_ADDED="track-added",M.TRACK_UPDATED="track-updated",M.TRACK_SUBSCRIBED="track-subscribed",M.STREAM_ADDED="stream-added",M.STREAM_REMOVED="stream-removed",M.STREAM_UPDATED="stream-updated",M.STREAM_PUBLISHED="stream-published",M.STREAM_SUBSCRIBED="stream-subscribed",M.STREAM_UNSUBSCRIBED="stream-unsubscribed",M.STATE_CHANGED="state-changed",M.ERROR="error",M.CONNECTION_STATE_CHANGED="connection-state-changed",M.FIREWALL_RESTRICTION="firewall-restriction",M.SEI_MESSAGE="sei-message",M.CLOSED="closed",M))(Dh||{}),wh=(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))(wh||{}),Pl=(N=>(N.STREAM_ADDED="stream-added",N.STREAM_REMOVED="stream-removed",N.STREAM_UPDATED="stream-updated",N.STREAM_SUBSCRIBED="stream-subscribed",N.CONNECTION_STATE_CHANGED="connection-state-changed",N.PEER_JOIN="peer-join",N.PEER_LEAVE="peer-leave",N.MUTE_AUDIO="mute-audio",N.MUTE_VIDEO="mute-video",N.UNMUTE_AUDIO="unmute-audio",N.UNMUTE_VIDEO="unmute-video",N.CLIENT_BANNED="client-banned",N.NETWORK_QUALITY="network-quality",N.AUDIO_VOLUME="audio-volume",N.SEI_MESSAGE="sei-message",N.ERROR="error",N))(Pl||{}),Mh=(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))(Mh||{}),ra=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c))(ra||{}),Ho=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(Ho||{}),Ki=(oe=>(oe.PEER_JOIN="peer-join",oe.PEER_LEAVE="peer-leave",oe.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",oe.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",oe.BANNED="banned",oe.NETWORK_QUALITY="network-quality",oe.AUDIO_VOLUME="audio-volume",oe.SEI_MESSAGE="sei-message",oe.ERROR="error",oe.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",oe.REMOTE_PUBLISHED="remote-published",oe.REMOTE_UNPUBLISHED="remote-unpublished",oe.FIREWALL_RESTRICTION="firewall-restriction",oe.HEARTBEAT_REPORT="heartbeat-report",oe.CUSTOM_MESSAGE="custom-message",oe.LAYER_DATA="layerData",oe.FIRST_VIDEO_FRAME="first-video-frame",oe.DUMP="dump",oe.AUDIO_FRAME="audio-frame",oe.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",oe))(Ki||{}),Br=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c))(Br||{}),Ws=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Ws||{}),Oh=(c=>(c[c.VIDEO=1]="VIDEO",c[c.SMALL=2]="SMALL",c[c.AUX=4]="AUX",c[c.AUDIO=8]="AUDIO",c[c.VIDEO_MUTE=16]="VIDEO_MUTE",c[c.AUX_MUTE=32]="AUX_MUTE",c[c.AUDIO_MUTE=64]="AUDIO_MUTE",c))(Oh||{}),kl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(kl||{}),Wo=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Wo||{}),zt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(zt||{}),Yc=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Yc||{}),Ll=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Ll||{}),ia=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(ia||{}),Ul=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(Ul||{}),xh=(e=>(e.ADD="add",e.REMOVE="remove",e))(xh||{}),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||{}),b_={1:"audio",2:"auxVideo",4:"video"},Vl=(t=>(t[t.opus=111]="opus",t))(Vl||{}),Fl=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Fl||{}),Ph=(e=>(e.Big="big",e.Small="small",e))(Ph||{}),Hr=(e=>(e.Main="main",e.Aux="auxiliary",e))(Hr||{}),mi=(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))(mi||{}),oa=(j=>(j[j.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",j[j.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",j[j.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",j[j.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",j[j.MUTE_AUDIO=32772]="MUTE_AUDIO",j[j.MUTE_VIDEO=32773]="MUTE_VIDEO",j[j.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",j[j.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",j[j.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",j[j.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",j[j.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",j[j.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",j[j.SWITCH_CAMERA=32780]="SWITCH_CAMERA",j[j.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",j[j.REPLACE_VIDEO=32782]="REPLACE_VIDEO",j[j.REPLACE_AUDIO=32783]="REPLACE_AUDIO",j[j.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",j[j.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",j[j.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",j[j.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",j[j.JOIN=32788]="JOIN",j[j.LEAVE=32789]="LEAVE",j[j.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",j[j.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",j[j.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",j[j.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",j[j.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",j[j.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",j[j.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",j[j.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",j[j.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",j[j.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",j[j.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",j[j.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",j[j.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",j[j.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",j[j.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",j[j.PUBLISH_AUX=32805]="PUBLISH_AUX",j[j.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",j[j.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",j[j.VIDEO_ENCODER=4004]="VIDEO_ENCODER",j[j.VIDEO_DECODER=4005]="VIDEO_DECODER",j))(oa||{}),kh=(c=>(c[c.UNKNOWN=0]="UNKNOWN",c[c.EXCELLENT=1]="EXCELLENT",c[c.GOOD=2]="GOOD",c[c.POOR=3]="POOR",c[c.BAD=4]="BAD",c[c.VERY_BAD=5]="VERY_BAD",c[c.DISCONNECTED=6]="DISCONNECTED",c))(kh||{}),Lh=(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))(Lh||{}),Zc=(e=>(e.user="user",e.environment="environment",e))(Zc||{}),sa=(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))(sa||{}),$l=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))($l||{}),Bl=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(Bl||{}),Hl=(m=>(m[m.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",m[m.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",m[m.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",m[m.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",m[m.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",m[m.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",m[m.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",m[m.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",m[m.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",m))(Hl||{}),pi=1e8,ta=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)}},hi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(hi||{}),Wl=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(Wl||{}),na=(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))(na||{}),Kc=(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))(Kc||{}),Uh=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(Uh||{}),Gl=(_=>(_[_.SUCCESS=0]="SUCCESS",_[_.FAILED=1]="FAILED",_[_.WEBCODEC_INIT=2]="WEBCODEC_INIT",_[_.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",_[_.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",_[_.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",_[_.WASM_INIT=6]="WASM_INIT",_[_.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",_[_.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",_[_.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",_[_.TEST=10]="TEST",_[_.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",_))(Gl||{}),aa=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(aa||{}),Go=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(Go||{}),ed=(e=>(e.CANVAS="canvas",e.API="api",e))(ed||{});var $e={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"},Xt={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: ${ct(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: ${ct(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 Vh=(i,t)=>t?`${Lr}/${i}/${t}`:`${Lr}/${i}/index.html`;var R_=()=>{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(el);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 Be(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",c="";We(Xt[t])?s=Xt[t](e):Oe(Xt[t])&&(s=Xt[t]);let{TRTC_ERROR_INFO:l,TRTC_ERROR_LINK:m}=R_();r?c=`${r.className}.html#${r.fnName}`:m&&m[t]&&(We(m[t])?c=m[t](e):Oe(m[t])&&(c=m[t]));let f=s;return Sr()&&(l&&l[t]&&(We(l[t])?n=l[t](e):Oe(l[t])&&(n=l[t])),n&&(o?f=`${n}
|
|
5
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${Vh("zh-cn",c)}
|
|
3
|
+
`}});var Cm=Ni(ui=>{"use strict";var Vr=Sm(),gg=Am(),Tg=Na();ui.grammar=Tg;ui.write=gg;ui.parse=Vr.parse;ui.parseParams=Vr.parseParams;ui.parseFmtpConfig=Vr.parseFmtpConfig;ui.parsePayloads=Vr.parsePayloads;ui.parseRemoteCandidates=Vr.parseRemoteCandidates;ui.parseImageAttributes=Vr.parseImageAttributes;ui.parseSimulcastStreamList=Vr.parseSimulcastStreamList});var sh=Ni((LU,sf)=>{"use strict";var of=sf.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(of).forEach(function(o){var i=of[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var cf=Ni(tr=>{"use strict";var as=function(o){return String(Number(o))===o?Number(o):o},JE=function(o,i,e,t){if(t&&!e)i[t]=as(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=as(o[r+1]))},qE=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;JE(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},nf=sh(),jE=RegExp.prototype.test.bind(/^([a-z])=(.*)/);tr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(jE).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(nf[s]||[]).length;a+=1){var c=nf[s][a];if(c.reg.test(n))return qE(c,t,n)}}),i.media=e,i};var af=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=as(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};tr.parseParams=function(o){return o.split(/;\s?/).reduce(af,{})};tr.parseFmtpConfig=tr.parseParams;tr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};tr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(as),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};tr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(af,{})})};tr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=as(e):(t=as(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var lf=Ni((UU,df)=>{"use strict";var nh=sh(),XE=/%[sdv%]/g,zE=function(o){var i=1,e=arguments,t=e.length;return o.replace(XE,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},vn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return zE.apply(null,r)},QE=["v","o","s","i","u","e","p","c","b","t","r","z","a"],YE=["i","c","b","a"];df.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||QE,t=i.innerOrder||YE,r=[];return e.forEach(function(s){nh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(vn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(vn(s,n,a))})})}),o.media.forEach(function(s){r.push(vn("m",nh.m[0],s)),t.forEach(function(n){nh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(vn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(vn(n,a,c))})})})}),r.join(`\r
|
|
4
|
+
`)+`\r
|
|
5
|
+
`}});var ah=Ni(ir=>{"use strict";var eo=cf(),ZE=lf();ir.write=ZE;ir.parse=eo.parse;ir.parseParams=eo.parseParams;ir.parseFmtpConfig=eo.parseFmtpConfig;ir.parsePayloads=eo.parsePayloads;ir.parseRemoteCandidates=eo.parseRemoteCandidates;ir.parseImageAttributes=eo.parseImageAttributes;ir.parseSimulcastStreamList=eo.parseSimulcastStreamList});import PG from"webrtc-adapter";var zp=Ge(tt());var Nh=(V=>(V[V.INVALID_PARAMETER=4096]="INVALID_PARAMETER",V[V.INVALID_OPERATION=4097]="INVALID_OPERATION",V[V.NOT_SUPPORTED=4098]="NOT_SUPPORTED",V[V.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",V[V.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",V[V.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",V[V.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",V[V.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",V[V.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",V[V.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",V[V.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",V[V.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",V[V.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",V[V.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",V[V.CLIENT_BANNED=16448]="CLIENT_BANNED",V[V.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",V[V.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",V[V.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",V[V.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",V[V.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",V[V.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",V[V.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",V[V.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",V[V.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",V[V.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",V[V.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",V[V.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",V[V.API_CALL_ABORTED=16461]="API_CALL_ABORTED",V[V.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",V[V.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",V[V.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",V[V.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",V[V.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",V[V.UNKNOWN=65535]="UNKNOWN",V))(Nh||{}),I=Nh;var s_=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},rd=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${s_(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=rd;var vh=new Date().getTime(),od=0,Dh=function(o){vh=o,od=vh-new Date().getTime();let i=new Date;i.setTime(o),y.info(`baseTime from server: ${i} offset: ${od}`)},ps=function(){return new Date().getTime()+od},Un=function(){let o=new Date;return o.setTime(ps()),o.toLocaleString()},so=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var _t={};vi(_t,{REPORT_TYPE:()=>So,buildSSOPackage:()=>Pi,bytes2ms:()=>Vh,calculateScaleResolutionDownNumber:()=>Eo,convertObjectNumberToInt:()=>Ns,copyProperties:()=>Uh,deepClone:()=>Nr,deepCloneBasic:()=>Qn,deepMerge:()=>oi,delay:()=>Li,fibonacci:()=>Dr,formatedTime:()=>jh,getConstructorName:()=>po,getContainerFromElement:()=>qh,getEnv:()=>Lh,getInternalVersion:()=>Wh,getLoggerUrl:()=>wi,getMediaStreamTrackInfo:()=>ta,getMuteStateFromFlag:()=>xi,getNetworkType:()=>vd,getNumNetworkType:()=>vr,getReconnectionTimeout:()=>Vt,getStringByteLength:()=>bs,getTurnServer:()=>Jh,getUint32Version:()=>Zn,getValueType:()=>Re,getViewListFromView:()=>go,glog:()=>Md,ipv4ToUint32:()=>_o,isArray:()=>Se,isAudioWorkletSupported:()=>$h,isBoolean:()=>de,isConstructor:()=>Or,isEmpty:()=>fo,isFunction:()=>ne,isLangChinese:()=>Ut,isMediaStreamTrack:()=>Fh,isNumber:()=>q,isObject:()=>ft,isOverseaSdkAppId:()=>ki,isPlainObject:()=>ze,isPortrait:()=>kd,isPromise:()=>lr,isRemoteTrack:()=>Hh,isRotate90Or270:()=>dt,isSetSinkIdSupported:()=>Gh,isString:()=>te,isUndefined:()=>E,loadImage:()=>To,loadVideo:()=>Xh,ms2bytes:()=>Bh,ms2samples:()=>Od,normalizeUrl:()=>ea,performanceNow:()=>B,promiseAny:()=>Mr,samples2ms:()=>Dd,setNetworkType:()=>Yn,stringify:()=>yt,stringifyIncludeValue:()=>ys,throttlePromise:()=>Kn});var Td={};vi(Td,{AUDIO_MUTE_BIT:()=>Gn,AUDIO_STAT_BIT:()=>cr,AUX_STAT_BIT:()=>Cr,AUX_STREAM_MSID:()=>ud,BACKEND_ENV:()=>$n,BASE_DOC_URL:()=>ti,BASE_HOST:()=>Oh,CAPABILITIES_KEYS:()=>qn,CLASS_NAME:()=>N_,CLOUD_CONSOLE_URL:()=>d_,CROSS_ROOM_BIT:()=>ld,DATA_FREEZE_TIMING:()=>Jn,DOC_URL:()=>l_,DTLS_STATE_UNKNOWN:()=>Pt,ENV_NAME:()=>Di,EXCHANGE_SDP_TIMEOUT:()=>_d,IS_WORKER:()=>no,IS_WORKLET:()=>_s,KIBANA_EVENT:()=>ct,LOCAL_STREAM_PUBLISH_STATE:()=>kh,LOGGER_CMD_TYPE:()=>sr,LOGGER_DOMAIN:()=>nd,LOGGER_DOMAIN_OVERSEA:()=>ad,LOG_LEVEL:()=>xt,LOG_LEVEL_NAME:()=>D_,MAIN_STREAM_MSID:()=>Es,MAX_RTT:()=>As,MICROPHONE_COMMUNICATIONS:()=>v_,MICROPHONE_DEFAULT:()=>br,MUTE_ALL_BIT:()=>m_,NAME:()=>p,NETWORK_TYPE:()=>Vn,NOT_SUPPORTED_H264:()=>Rr,PAUSED_RETRY_COUNT:()=>yr,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Ss,PEER_CONNECTION_STATE:()=>ge,PEER_LEAVE_REASON:()=>gd,RECOVER_CAPTURE_INTERVAL:()=>lo,REMOTE_STREAM_TYPE_AUX:()=>md,REMOTE_STREAM_TYPE_MAIN:()=>hd,RENDER_FREEZE_TIMING:()=>C_,SCHEDULE_DOMAIN:()=>Mi,SCHEDULE_TIMEOUT:()=>b_,SDP_SEMANTICS_PLAN_B:()=>ao,SDP_SEMANTICS_UNIFIED_PLAN:()=>dr,SECOND_HOST:()=>a_,SIGNAL_PING_PONG_INTERVAL:()=>h_,SIGNAL_PING_TIMEOUT:()=>u_,SIGNAL_RECONNECTION_COUNT:()=>I_,SMALL_STAT_BIT:()=>Ts,SPEAKER_DEFAULT:()=>Is,STORAGE_EXPIRES_TIME:()=>Bn,STREAM_TYPE_BIG:()=>R_,STREAM_TYPE_SMALL:()=>y_,SUBSCRIBE_SMALL_RETRY_COUNT:()=>co,SYNC_USER_LIST_INTERVAL:()=>A_,Scene:()=>ii,THIRD_HOST:()=>c_,TRANSPORT_DIRECTION:()=>ie,TRTC_ERROR_ASSISTANCE:()=>cd,TRTC_QUALITY_BAD:()=>T_,TRTC_QUALITY_DISCONNECTED:()=>S_,TRTC_QUALITY_EXCELLENT:()=>f_,TRTC_QUALITY_GOOD:()=>__,TRTC_QUALITY_POOR:()=>g_,TRTC_QUALITY_UNKNOWN:()=>p_,TRTC_QUALITY_VERY_BAD:()=>E_,UPDATE_OFFER_TIMEOUT:()=>fd,VIDEO_MUTE_BIT:()=>Wn,VIDEO_STAT_BIT:()=>ar,audioProfileMap:()=>Fn,defaultBigVideoProfile:()=>nr,defaultSmallVideoProfile:()=>dd,getRetryCount:()=>Oi,getScriptDir:()=>n_,innerVersion:()=>fs,loggerProxy:()=>gs,screenProfileMap:()=>Hn,setLoggerProxy:()=>Ar,setRetryCount:()=>pd,setVersion:()=>sd,version:()=>we,videoProfileMap:()=>Lt});var fs="4.15.00.1600",we="5.0.0";function sd(o){we=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));fs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var no=typeof importScripts!="undefined",_s=typeof registerProcessor!="undefined",n_=()=>{let o=no?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},gs="",Ar=o=>gs=o,Oh="web.sdk.qcloud.com",a_="web.sdk.tencent.cn",c_="web.sdk.cloud.tencent.cn",d_="https://console.cloud.tencent.com/trtc",ti=`https://${Oh}/trtc/webrtc/v5/doc`,l_=`${ti}/zh-cn/`,nd="https://yun.tim.qq.com",ad="https://apisgp.my-imcloud.com",cd="trtc_error_assistance",sr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Di={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},xt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(xt||{}),u_=18e3,h_=2e3,Vn={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Bn=7*24*3600*1e3,Fn={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}},Lt={"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}},nr=Lt["480p_2"],dd=Lt["120p_2"],Hn={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},p={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"},ie={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},$n={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ii=(e=>(e.LIVE="live",e.RTC="rtc",e))(ii||{}),ar=1,Ts=2,Cr=4,cr=8,Gn=64,Wn=16,m_=112,ld=128,Es="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ud="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",hd=p.MAIN,md=p.AUXILIARY,p_=0,f_=1,__=2,g_=3,T_=4,E_=5,S_=6,Pt="unknown",ge={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Mh=1/0;function pd(o){Mh=o}function Oi(){return Mh}var I_=30,ct={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"},A_=1e4,fd=1e4,_d=1e4,dr="unified-plan",ao="plan-b",Rr=1028,kh=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(kh||{}),Jn=500,C_=1e3,R_=p.BIG,y_=p.SMALL,Ss=10*1e3,Mi={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"},b_=2e3,N_={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},yr=5,br="default",Is=br,v_="communications",D_=Object.keys(xt),gd=["normal leave","timeout leave","kick","role change"],co=10,lo=2e3,qn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],As=10*1e3;var O_=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},Ed=Symbol(32),Sd=Symbol(16),Id=Symbol(8),ri=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return O_(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(Ed)}readU16(){return this.read(Sd)}readU8(){return this.read(Id)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===Ed){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===Sd){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===Id){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};ri.U32=Ed;ri.U16=Sd;ri.U8=Id;var M_=128,k_=127,DS=~k_,OS=Math.pow(2,31);function Ad(o){let i=new ri;for(;o>=128;)i.malloc(1)[0]=o&255|M_,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function jn(o,i=0){let e=new ri,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(Ad(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(Ad(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new ri;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=jn(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=jn(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(Ad(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Cs=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function Cd(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function Xe(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function Rd(o,i){return o[i]}function uo(o,i,e){return new TextDecoder().decode(w_(o,i,e))}function w_(o,i,e){return o.slice(i,i+e)}var yd=0,Xn=2654435769,zn=16,Nd=4,ho=2,mo=7;function x_(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function wh(o,i){let e=new Cs,t=x_(i,o,yd);yd=yd+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Cs;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let K=4;K<16;K++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let h=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(h.length+4),h.length&&n.writeBytes(h);let m=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(m.length+2),m.length&&n.writeBytes(m);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,te(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let A=new Uint8Array(n.data),g=null;t.encryption===1?g=new TextEncoder().encode(t.uin):t.encryption===2&&(g=new Uint8Array(16)),g&&(A=L_(A,g)),e.writeBytes(A);let T=new Uint8Array(e.data),O=T.length;return T[0]=O>>>24&255,T[1]=O>>>16&255,T[2]=O>>>8&255,T[3]=O&255,T}function L_(o,i){let e=o.length,r=(e+1+ho+mo)%8;r&&(r=8-r);let s=e+1+ho+mo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),h=0;c[0]=Math.floor(Math.random()*256)&248|r,h=1;for(let _=0;_<r;_++)c[h]=Math.floor(Math.random()*256)&255,h+=1;for(let _=0;_<ho;)if(h<8&&(c[h]=Math.floor(Math.random()*256)&255,h+=1,_+=1),h===8){bd(c,i,l,u,n,a),a+=8,h=0;for(let A=0;A<8;A++)u[A]=n[a-8+A]}let m=0;for(;m<e;)if(h<8&&(c[h]=o[m],h+=1,m+=1),h===8){bd(c,i,l,u,n,a),a+=8,h=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<mo;)if(h<8&&(c[h]=0,h+=1,_+=1),h===8){bd(c,i,l,u,n,a),a+=8,h=0;for(let A=0;A<8;A++)u[A]=n[a-8+A]}return n}function bd(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];P_(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function P_(o,i,e,t){let r=Xe(o,0),s=Xe(o,4),n=[];for(let c=0;c<4;c++)n[c]=Xe(i,c*4);let a=0;for(let c=0;c<zn;c++)a+=Xn,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;Cd(e,r,t),Cd(e,s,t+4)}var Lh=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ki=o=>Number(o)<14e8,wi=function(o,i){let e;gs?e=gs:e=ki(o)?ad:nd;let t=Math.floor(Math.random()*or(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},Rs="unknown";function vd(){if(Rs!=="unknown")return Rs;let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(Rs=Ph(t,r)),Rs}function Ph(o,i){if(Vn[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Yn(o){Rs=Ph(o)}function vr(){return Vn[vd()]}function Uh(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Vh(o,i=48e3){return Dd(o/4,i)}function Dd(o,i=48e3){return o*1e3/i}function Bh(o,i=48e3){return Od(o,i)*4}function Od(o,i=48e3){return o*i/1e3}var Md=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Ut=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},ze=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Dr(o,i=1,e=1){return o<=1?e:Dr(o-1,e,i+e)}function Vt(o){return o>8?30*1e3:Dr(o)*1e3}function Re(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ne=o=>typeof o=="function",E=o=>typeof o=="undefined",te=o=>typeof o=="string",q=o=>typeof o=="number",de=o=>typeof o=="boolean",ft=o=>Re(o)==="object",Se=o=>Re(o)==="array",Fh=o=>Re(o)==="MediaStreamTrack".toLowerCase(),Hh=o=>o.isRemote,lr=o=>Re(o)==="promise",Or=o=>ne(o)&&o.prototype.constructor===o,po=o=>Or(o)?o.prototype.constructor.name:"",$h=typeof AudioWorkletNode!="undefined",Gh="setSinkId"in HTMLMediaElement.prototype;function Mr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function B(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var xh=o=>+o<10?`0${o}`:o,Wh=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=xh(e[1])+xh(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},U_=Object.prototype.hasOwnProperty,{toString:$S}=Object.prototype;function fo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(ze(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(U_.call(o,i))return!1;return!0}}return!1}function xi(o,i){return{userId:i,hasAudio:!!(o&cr),hasVideo:!!(o&ar),hasAuxiliary:!!(o&Cr),hasSmall:!!(o&Ts),audioMuted:!!(o&Gn),videoMuted:!!(o&Wn),audioAvailable:!!(o&cr)&&!(o&Gn),videoAvailable:!!(o&ar)&&!(o&Wn)}}function Jh(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!E(o.username)&&!E(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",E(o.credentialType)||(i.credentialType=o.credentialType)),i}function _o(o,i=!0){if(!te(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var oi=function(o,i,e,t){if(!(ft(o)&&ft(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(E(i[n])||e&&e.includes(n)))if(ft(o[n])&&ft(i[n]))r+=oi(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Nr(i[n]),r+=1)}return r};function Nr(o){if(Se(o)){let i=[];return o.forEach((e,t)=>{i[t]=Nr(e)}),i}if(ft(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Nr(o[e])}),i}return o}var go=o=>{let i=[];if(Se(o))i=[...o];else if(te(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},qh=o=>te(o)?document.getElementById(o):o,V_=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},jh=()=>V_(new Date);function yt(o,{keysToInclude:i,keysToExclude:e}){try{if(Se(o))return`[${o.map(n=>yt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!ze(o)||!Se(i)&&!Se(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=ze(o[n])||Se(o[n])?JSON.parse(yt(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function ys(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),yt(o,{keysToInclude:e})}function bs(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var kd=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},To=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(te(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Zn=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Ns=o=>(Object.keys(o).forEach(i=>{q(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(ze(o[i])||Se(o[i]))&&Ns(o[i])}),o);function Li(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Kn(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function ea(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function ta(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===p.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function Eo(o,i){return o.width*o.height===i.width*i.height?1:kd()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function dt(o){return o===90||o===270}function Xh(o){return f(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function Qn(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=Qn(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=Qn(o[t],i)}),e}return o}var So=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(So||{});function B_(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return E(t)||(r=w(v({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Pi(o,i,e,t){try{let r=B_(o,i,e,t),s=jn(r);return wh(s,e)}catch(r){return JSON.stringify(o)}}function zh(o){let i=F_(o);return i==null?void 0:i.busiBuff}function F_(o){try{let i={},e=0;i.totalLength=Xe(o,e),e+=4,i.version=Xe(o,e),e+=4,i.encryption=Rd(o,e),e+=1,i.uinType=Rd(o,e),e+=1,i.uinLength=Xe(o,e),e+=4,i.uin=i.uinLength>4?uo(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=H_(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=Xe(o,e),e+=4,i.seqNo=Xe(o,e),e+=4,i.retCode=Xe(o,e),e+=4,i.retStrLength=Xe(o,e),e+=4,i.retStr=i.retStrLength?uo(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=Xe(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?uo(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=Xe(o,e),e+=4,i.cookie=i.cookieLength?uo(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=Xe(o,e),e+=4,i.busiBuffLength=Xe(o,e),e+=4,i.busiBuff=i.busiBuffLength?uo(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Qh(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Xn*zn>>>0;for(let s=0;s<zn;s++)t-=(e<<Nd)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<Nd)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Xn,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function H_(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Qh(r,i),n=s[0]&7,a=o.length-1-n-ho-mo,c=new Uint8Array(a),l=0,u=t,h=o.slice(0,8);e=8;let m=1;m+=n;for(let A=1;A<=ho;)if(m<8)m++,A++;else if(m===8){let g=wd(o,e,u,h,s,i);u=g.ivPreCrypt,h=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,m=0}let _=a;for(;_>0;)if(m<8)c[l++]=s[m]^u[m],m++,_--;else if(m===8){let A=wd(o,e,u,h,s,i);u=A.ivPreCrypt,h=A.ivCurCrypt,s=A.debiBuf,e=A.bufPos,m=0}for(let A=1;A<=mo;)if(m<8)s[m]^u[m],m++,A++;else if(m===8){if(e>=o.length)break;let g=wd(o,e,u,h,s,i);if(!g.success)break;u=g.ivPreCrypt,h=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,m=0}return c}function wd(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Qh(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}function Ui({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:zh(new Uint8Array(l))||l})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}var $_=Object.prototype.hasOwnProperty;var si=o=>typeof o=="function",Vi=o=>typeof o=="undefined";var ia=o=>typeof o=="boolean";var xd=o=>o.isRemote;var Ld=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Yh(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Ld(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if($_.call(o,i))return!1;return!0}}return!1}var G_=0,W_=1,Zh=2;function J_({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,h=-1,m=G_,_=(A,g)=>f(this,null,function*(){let T=n||this;try{let O=yield o.apply(T,a);u>0&&s&&s.call(this,u),u=0,A(O)}catch(O){let K=()=>{clearTimeout(h),u=0,m=Zh,g(O)},G=()=>{m!==Zh&&u<(si(c)?c():c)?(u++,m=W_,si(t)&&t.call(this,u,K),h=window.setTimeout(()=>{h=-1,_(A,g)},si(l)?l(u):l)):(K(),si(r)&&r.call(this,O))};si(e)?e.call(this,{error:O,retry:G,reject:g,retryFuncArgs:a,retriedCount:u}):G()}});return new Promise(_)}}var ni=J_;var Io=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=ia(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}`:""}]`),y.log(i,e,Vi(this.userId)||Yh(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var ko={};vi(ko,{ANDROID_VERSION:()=>Vd,CHROME_MAJOR_VERSION:()=>lt,CHROME_VERSION:()=>Ea,EDGE_VERSION:()=>oa,EDG_MAJOR_VERSION:()=>Bd,EDG_VERSION:()=>sa,FIREFOX_MAJOR_VERSION:()=>Ro,FIREFOX_VERSION:()=>ra,HUAWEI_VERSION:()=>fa,IE_VERSION:()=>Q_,IOS_MAIN_VERSION:()=>Je,IOS_VERSION:()=>gt,IPADQQB_VERSION:()=>ma,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>eg,IS_ANY_SAFARI:()=>ci,IS_CHROME:()=>Mo,IS_CHROME_OS:()=>Fd,IS_CHROMIUM_BASE:()=>it,IS_DESKTOP_IOS_CHROME:()=>zd,IS_EDG:()=>yo,IS_EDGE:()=>kr,IS_ELECTRON:()=>Z_,IS_FIREFOX:()=>ae,IS_HEADLESS_CHROME:()=>Jd,IS_HONOR:()=>Gd,IS_HUAWEI:()=>$d,IS_HUAWEIBROWSER:()=>Ls,IS_IE:()=>im,IS_IE8:()=>z_,IS_IOS:()=>Ie,IS_IOS_13_OR_14:()=>Xd,IS_IOS_15_1:()=>jd,IS_IOS_CHROME:()=>rm,IS_IPAD:()=>Co,IS_IPADQQB:()=>ks,IS_IPAD_PRO:()=>Ud,IS_IPHONE:()=>ur,IS_IPOD:()=>tm,IS_LINUX:()=>ws,IS_LOCAL:()=>Gt,IS_MAC:()=>$t,IS_MACQQB:()=>Ms,IS_MIBROWSER:()=>xs,IS_MQQB:()=>Do,IS_NATIVE_ANDROID:()=>X_,IS_OLD_ANDROID:()=>j_,IS_OPENHARMONY:()=>Wd,IS_OPPOBROWSER:()=>Us,IS_SAFARI:()=>xe,IS_SAFARI_15_1:()=>tg,IS_SAMSUNGBROWSER:()=>Ps,IS_SOGOU:()=>Ds,IS_SOGOUM:()=>vs,IS_TBS:()=>Ht,IS_UCBROWSER:()=>Hd,IS_VIVOBROWSER:()=>Vs,IS_WECHAT:()=>No,IS_WIN:()=>wr,IS_WQQB:()=>Os,IS_WX:()=>Y_,IS_X5MQQB:()=>vo,IS_XWEB:()=>bo,MACQQB_VERSION:()=>ha,MI_VERSION:()=>pa,MQQB_VERSION:()=>Ao,OPENHARMONY_VERSION:()=>K_,OPPO_VERSION:()=>ga,SAFARI_VERSION:()=>Bi,SAMSUNG_VERSION:()=>_a,SOGOUM_VERSION:()=>na,SOGOU_VERSION:()=>aa,TBS_VERSION:()=>ca,UA_DATA_STRING:()=>Bt,USER_AGENT:()=>Ft,VIVO_VERSION:()=>Ta,WECHAT_VERSION:()=>la,WQQB_VERSION:()=>ua,XWEB_VERSION:()=>da,browserInfo:()=>ai,getBrowserInfo:()=>om,getChromeMajorVersion:()=>Oo,getDeviceModel:()=>Lr,getGPUInfo:()=>Yd,getOSName:()=>Sa,getOSNumber:()=>Fs,getOSString:()=>Hi,getOSType:()=>ig,getTerminalType:()=>Zd,getUserAgentData:()=>xr,isLocalStorageEnabled:()=>Fi,isMobile:()=>Qd,isVersionLargerThan:()=>qd,isVersionSmallerThan:()=>Bs});var Ft=typeof navigator=="undefined"?"":navigator.userAgent,Q=o=>new RegExp(o,"i").test(Ft),Oe=o=>{if(Q(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Ft.match(i);if(e&&e[1])return e[1]}return""},Pd=o=>{if(Q(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Ft.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Kh=/AppleWebKit\/([\d.]+)/i.exec(Ft),q_=Kh?parseFloat(Kh[1]):NaN,Co=Q("iPad"),Ud=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Q("Macintosh"),ur=Q("iPhone")&&!Co,tm=Q("iPod"),Ie=ur||Co||tm||Ud,pe=Q("Android"),Vd=function(){if(pe){let o=Ft.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),j_=pe&&Q("webkit")&&Vd<2.3,X_=pe&&Vd<5&&q_<537,ae=Q("Firefox"),ra=Oe("Firefox"),Ro=Pd("Firefox"),kr=Q("Edge"),oa=Oe("Edge"),yo=Q("Edg"),sa=Oe("Edg"),Bd=Pd("Edg"),vs=Q("SogouMobileBrowser"),na=Oe("SogouMobileBrowser"),Ds=Q("MetaSr\\s"),aa=Oe("MetaSr\\s"),Ht=Q("TBS"),ca=Oe("TBS"),bo=Q("XWEB"),da=Oe("XWEB"),z_=Q("MSIE\\s8\\.0"),im=Q("MSIE\\/\\d+"),Q_=function(){if(im){let o=/MSIE\s(\d+)\.\d/.exec(Ft),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Ft)&&/rv:11.0/.test(Ft)&&(i=11),i}return NaN}(),No=Q("(micromessenger|webbrowser)"),la=Oe("MicroMessenger"),vo=!Ht&&Q("MQQBrowser")&&Q("COVC"),Do=!Ht&&Q("MQQBrowser")&&!Q("COVC"),Ao=Do||vo?Oe("MQQBrowser"):"",Os=!Ht&&Q(" QQBrowser"),ua=Oe(" QQBrowser"),Ms=!Ht&&Q("QQBrowserLite"),ha=Oe("QQBrowserLite"),ks=!Ht&&Q("MQBHD"),ma=Oe("MQBHD"),wr=Q("Windows"),$t=!Ie&&Q("MAC OS X"),ws=!pe&&Q("Linux"),Fd=Q("CrOS"),Y_=Q("MicroMessenger"),Hd=Q("UCBrowser"),Z_=Q("Electron"),xs=Q("MiuiBrowser"),pa=Oe("MiuiBrowser"),Ls=Q("HuaweiBrowser"),$d=Q("Huawei")||Q("HUAWEI"),Gd=Q("Honor")||Q("HONOR"),fa=Oe("HuaweiBrowser"),Ps=Q("SamsungBrowser"),_a=Oe("SamsungBrowser"),Us=Q("HeyTapBrowser"),ga=Oe("HeyTapBrowser"),Vs=Q("VivoBrowser"),Ta=Oe("VivoBrowser"),Wd=Q("OpenHarmony"),K_=Oe("OpenHarmony"),Oo=()=>Pd("Chrome"),it=Q("Chrome"),Mo=!kr&&!Ds&&!vs&&!Ht&&!bo&&!yo&&!Os&&!xs&&!Ls&&!Ps&&!Us&&!Vs&&it,Jd=Q("HeadlessChrome"),lt=Oo(),Ea=Oe("Chrome"),xe=!it&&!Do&&!vo&&!Ms&&!ks&&Q("Safari"),ci=xe||Ie,Bi=Oe("Version"),eg=/Android.*(wv|.0.0.0)/.test(Ft),gt=(()=>{if(Ud)return Bi;if(Ie){let o=Ft.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function Bs(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function qd(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var Je=Number(gt.split(".")[0]),tg=Bi==="15.1",jd=gt==="15.1",Xd=(()=>{let o=Number(gt.split(".")[0]);return o===14||o===13})(),rm=Q("CriOS"),zd=rm&&Bi==="11.1.1",Gt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Fi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),ai=om();function om(){let o=new Map([[ae,["Firefox",ra]],[yo,["Edg",sa]],[Mo,["Chrome",Ea]],[xe,["Safari",Bi]],[Ht,["TBS",ca]],[bo,["XWEB",da]],[No&&ur,["WeChat",la]],[Os,["QQ(Win)",ua]],[Do,["QQ(Mobile)",Ao]],[vo,["QQ(Mobile X5)",Ao]],[Ms,["QQ(Mac)",ha]],[ks,["QQ(iPad)",ma]],[xs,["MI",pa]],[Ls,["HW",fa]],[Ps,["Samsung",_a]],[Us,["OPPO",ga]],[Vs,["VIVO",Ta]],[kr,["EDGE",oa]],[vs,["SogouMobile",na]],[Ds,["Sogou",aa]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var ce=null;function Qd(){return ce&&typeof ce.mobile=="boolean"?ce.mobile:pe||Ie||ur||Co||Wd}var Bt="";function xr(){return f(this,null,function*(){if(ce)return ce;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ce=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ce&&!Bt&&(Bt=`UAData: ${ce.platform}/${ce.platformVersion}`,ce.architecture&&ce.bitness&&(Bt+=` ${ce.architecture}/${ce.bitness}`),ce.mobile&&(Bt+=" mobile"),ce.model&&(Bt+=` model: ${ce.model.replace(/\s+/g,"/")}`),ce.fullVersionList&&(Bt+=` ${ce.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),ce}catch(o){return null}})}function Yd(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function Lr(){return(ce==null?void 0:ce.model)||""}var em=new Map([[pe,"Android"],[Ie,"iOS"],[wr,"Windows"],[$t,"MacOS"],[ws,"Linux"],[Fd,"ChromeOS"]]),Sa=function(){return em.get(!0)?em.get(!0):ce?ce.platform:"unknown"};function Fs(){return wr?1:pe?2:$t?3:Ie?4:ws?5:Fd?6:0}var Hi=()=>{let o=Sa();return o+=`/${ai.name}/${xe?ai.version:ai.version.split(".")[0]}`,ce!=null&&ce.platformVersion&&(o+=`/${ce.platformVersion}`),ce!=null&&ce.architecture&&(o+=`/${ce.architecture}`),o};function Zd(){return pe?4:ur?2:Co?3:$t?12:wr?5:ws?13:Wd?22:1}function ig(){return pe?"Android":ur?"iPhone":Co?"iPad":$t?"Mac":wr?"Windows":ws?"Linux":"unknown"}var sm=Ge(tt(),1),rg=new sm.default,S=rg;var bt=(H=>(H.ROOM_DESTROY="1",H.JOIN_START="21",H.JOIN_SCHEDULE_SUCCESS="22",H.JOIN_SIGNAL_CONNECTION_START="23",H.JOIN_SIGNAL_CONNECTION_END="24",H.JOIN_SEND_CMD="25",H.JOIN_RECEIVED_CMD_RES="26",H.JOIN_SUCCESS="27",H.JOIN_FAILED="28",H.LEAVE_START="51",H.LEAVE_SEND_CMD="52",H.LEAVE_SUCCESS="53",H.PUBLISH_START="61",H.SEND_FIRST_VIDEO_FRAME="62",H.PUBLISH_FAILED="63",H.SUBSCRIBE_START="81",H.SUBSCRIBE_SUCCESS="82",H.SUBSCRIBE_FAILED="84",H.UNSUBSCRIBE_SUCCESS="83",H.LOCAL_TRACK_CAPTURE_START="101",H.LOCAL_TRACK_CAPTURE_SUCCESS="102",H.LOCAL_TRACK_CAPTURE_FAILED="103",H.LOCAL_TRACK_PUBLISHED="104",H.LOCAL_TRACK_UNPUBLISHED="105",H.LOCAL_TRACK_REPLACED="106",H.SWITCH_DEVICE_SUCCESS="107",H.TRACK_MUTED="108",H.TRACK_UNMUTED="109",H.REMOTE_TRACK_SUBSCRIBED="110",H.REMOTE_TRACK_UNSUBSCRIBED="111",H.LOCAL_TRACK_RECAPTURE="112",H.LOCAL_AUDIO_STARTED="113",H.LOCAL_AUDIO_STOPPED="114",H.REMOTE_AUDIO_STARTED="115",H.REMOTE_AUDIO_STOPPED="116",H.PLAY_TRACK_START="151",H.PLAYER_STATE_CHANGED="152",H.VIDEO_LOADED_DATA="153",H.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",H.SIGNAL_CONNECTION_STATE_CHANGED="201",H.PEER_CONNECTION_STATE_CHANGED="202",H.SINGLE_CONNECTION_STAT="203",H.SPC_RECONNECTED="204",H.HEARTBEAT_REPORT="251",H.RECEIVED_PUBLISHED_USER_LIST="252",H.REMOTE_PUBLISH_STATE_CHANGED="253",H.AUDIO_LEVEL_INTERVAL="260",H.NETWORK_QUALITY="261",H.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",H.QUALITY_LIMITATION_CHANGED="263",H.LOG="264",H.AUDIO_PROCESSOR_DEBUG="265",H.SSO="266",H.SWITCH_ROOM_START="401",H.SWITCH_ROOM_SUCCESS="407",H.SWITCH_ROOM_FAILED="408",H))(bt||{});var C=bt;var og="%cTRTC%c%s",sg="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ng="display: inline",Ia=class Ia{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);d(this,"_sso",!1);!no&&!_s&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e,t;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&xt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload),(t=i==null?void 0:i.config)!=null&&t.sso&&(this._sso=!0)}),S.on(C.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.once(C.JOIN_FAILED,()=>{this.startUpload()}),S.on(C.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(te(t.userId)&&q(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:Un(),sdkAppId:String(a),userId:n,version:we,log:c.map(h=>h.log).join(`
|
|
6
|
+
`)},u=this._sso?Pi(l,2002,a):JSON.stringify(l);yield this.uploadLogWithRetry(u,a,u instanceof Uint8Array),c.forEach(h=>h.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t){return ni({retryFunction:()=>Ui({url:wi(e,sr.LOG),body:i,timeout:5e3,priority:"low"}).then(r=>{t&&S.emit(C.SSO,{result:r.data==="ok"})}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(i){let e=new Date;return e.setTime(ps()),`[${so(e)}] <${xt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(xt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(te(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,s){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,u)=>`${l} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};if(S.emit(C.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=xt[i])==null?void 0:c.toLowerCase())||"info";Ia.PRINT_LOG_TAG?console[a](og,sg,ng,...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 Io(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;xt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(Ia,"PRINT_LOG_TAG",!(Ie||pe||Jd));var Kd=Ia,y=new Kd;var ag=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},Hs=ag;var el=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Fi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(Fi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){y.warn(i)}}getItem(i){if(!Fi())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){y.warn(e)}}setItem(i,e){if(Fi())try{let t={expiresIn:Date.now()+Bn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){y.warn(t)}}deleteItem(i){if(!Fi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return y.warn(e),!1}}clear(){if(Fi())try{localStorage.clear()}catch(i){y.warn(i)}}},wo=new el;var pi={};vi(pi,{HTTPS_API:()=>Ng,IS_GET_CAPABILITIES_SUPPORTED:()=>Rl,IS_GET_SETTINGS_SUPPORTED:()=>mi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Cl,IS_INSERTABLE_STREAM_SUPPORTED:()=>Ji,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Ua,IS_RTC_RTP_SENDER_SUPPORTED:()=>zs,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Bo,IS_SEI_SUPPORTED:()=>Ys,IS_SPC_SUPPORTED:()=>Vo,basis:()=>Mg,capabilityCheck:()=>bl,checkSystemRequirementsInternal:()=>xa,decodeSupportStatus:()=>wa,encodeSupportStatus:()=>El,getBrowserInfo:()=>Cg,getDisplayResolution:()=>bm,isAddTransceiverSupported:()=>ht,isBrowserSupported:()=>Sl,isCanvasCaptureStreamAPISupported:()=>Dm,isCanvasSmallStreamSupported:()=>La,isGetReceiversSupported:()=>Fr,isGetSendersSupported:()=>mr,isGetTransceiversSupported:()=>hi,isGetUserMediaSupported:()=>Nm,isMediaDevicesSupported:()=>ka,isMediaSessionSupported:()=>km,isMediaStreamTrackProcessorSupported:()=>js,isReplaceTrackSupported:()=>Al,isRequestVideoFrameCallbackSupported:()=>Hr,isSIMDSupported:()=>Og,isScaleResolutionDownBySupported:()=>Om,isScreenCaptureApiAvailable:()=>Xs,isSelectedCandidatePair:()=>hr,isSetParametersSupported:()=>Qs,isSmallStreamSupported:()=>Pa,isStopTransceiverSupported:()=>Dg,isTRTCSupported:()=>Rg,isUnifiedPlanDefault:()=>vg,isUsedInHttpProtocol:()=>Wi,isWebAudioSupported:()=>vm,isWebCodecSupported:()=>Mm,isWebCodecsSupported:()=>Il,isWebRTCSupported:()=>yl,isWebTransportSupported:()=>wm});var ml={};vi(ml,{AUDIO_LEVEL_SCALE:()=>Et,AudioCodecPipelineType:()=>ll,AudioDecoderDowngradeState:()=>ol,AudioPlayerMode:()=>cl,AudioType:()=>dm,BASIC_TYPE:()=>$i,BannedReason:()=>dl,CONNECTION_CLOSED_REASON:()=>il,CheckPermissionType:()=>hl,ClientEvent:()=>nm,CodecType:()=>pm,ConnectionEvent:()=>Wt,ConnectionState:()=>Tt,DECODE_FAILED_ERROR_CODE:()=>ul,FacingMode:()=>Ra,FrameWorkType:()=>Aa,LeaveReason:()=>mm,LocalTrackEvent:()=>xo,MULTI_VIDEO_DATA_TYPE:()=>Jt,MediaType:()=>Le,MediaTypeLabel:()=>cg,MonitorEventId:()=>$s,MutedFlag:()=>cm,NetworkQualityValue:()=>al,PlayerState:()=>Pr,ReceiveMode:()=>hm,RemoteStreamType:()=>ut,RemoteTrackEvent:()=>Lo,RoomEvent:()=>di,SMALL_MODE:()=>Gs,SceneNumber:()=>rl,StreamEvent:()=>am,StreamType:()=>um,SubscribeMediaType:()=>tl,TIMER_TYPE:()=>jt,TRACK_ACTION:()=>nl,TRACK_KIND:()=>sl,TrackEvent:()=>li,UserRole:()=>rt,UserRoleNumber:()=>Ur,VideoCodec:()=>qt,VideoCodecPipelineType:()=>ba,VideoContentHint:()=>Po,VideoDecoderDowngradeState:()=>Ca,VideoPlayerMode:()=>ya,VideoType:()=>lm});var Aa=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(Aa||{}),Wt=(g=>(g.TRACK_ADDED="track-added",g.TRACK_UPDATED="track-updated",g.TRACK_SUBSCRIBED="track-subscribed",g.STREAM_ADDED="stream-added",g.STREAM_REMOVED="stream-removed",g.STREAM_UPDATED="stream-updated",g.STREAM_PUBLISHED="stream-published",g.STREAM_SUBSCRIBED="stream-subscribed",g.STREAM_UNSUBSCRIBED="stream-unsubscribed",g.STATE_CHANGED="state-changed",g.ERROR="error",g.CONNECTION_STATE_CHANGED="connection-state-changed",g.FIREWALL_RESTRICTION="firewall-restriction",g.SEI_MESSAGE="sei-message",g.CLOSED="closed",g))(Wt||{}),il=(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))(il||{}),nm=(T=>(T.STREAM_ADDED="stream-added",T.STREAM_REMOVED="stream-removed",T.STREAM_UPDATED="stream-updated",T.STREAM_SUBSCRIBED="stream-subscribed",T.CONNECTION_STATE_CHANGED="connection-state-changed",T.PEER_JOIN="peer-join",T.PEER_LEAVE="peer-leave",T.MUTE_AUDIO="mute-audio",T.MUTE_VIDEO="mute-video",T.UNMUTE_AUDIO="unmute-audio",T.UNMUTE_VIDEO="unmute-video",T.CLIENT_BANNED="client-banned",T.NETWORK_QUALITY="network-quality",T.AUDIO_VOLUME="audio-volume",T.SEI_MESSAGE="sei-message",T.ERROR="error",T))(nm||{}),am=(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))(am||{}),xo=(a=>(a.DEVICE_AUTO_RECOVERED="1",a.DEVICE_RECOVER_FAILED="5",a.DEVICE_CHANGED="2",a.ERROR="3",a.PUBLISH_STATE_CHANGED="4",a.ENCODE_FAILED="6",a.TRACK_ENDED="7",a))(xo||{}),Pr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Pr||{}),di=(ee=>(ee.PEER_JOIN="peer-join",ee.PEER_LEAVE="peer-leave",ee.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",ee.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",ee.BANNED="banned",ee.NETWORK_QUALITY="network-quality",ee.AUDIO_VOLUME="audio-volume",ee.SEI_MESSAGE="sei-message",ee.ERROR="error",ee.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",ee.REMOTE_PUBLISHED="remote-published",ee.REMOTE_UNPUBLISHED="remote-unpublished",ee.FIREWALL_RESTRICTION="firewall-restriction",ee.HEARTBEAT_REPORT="heartbeat-report",ee.CUSTOM_MESSAGE="custom-message",ee.LAYER_DATA="layerData",ee.FIRST_VIDEO_FRAME="first-video-frame",ee.DUMP="dump",ee.AUDIO_FRAME="audio-frame",ee.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",ee))(di||{}),li=(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))(li||{}),Lo=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Lo||{}),cm=(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))(cm||{}),rl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(rl||{}),Ur=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Ur||{}),rt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(rt||{}),Tt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Tt||{}),ol=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(ol||{}),Ca=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Ca||{}),sl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(sl||{}),nl=(e=>(e.ADD="add",e.REMOVE="remove",e))(nl||{}),Le=(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))(Le||{}),cg={1:"audio",2:"auxVideo",4:"video"},dm=(i=>(i[i.opus=111]="opus",i))(dm||{}),lm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(lm||{}),um=(e=>(e.Big="big",e.Small="small",e))(um||{}),ut=(e=>(e.Main="main",e.Aux="auxiliary",e))(ut||{}),Jt=(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))(Jt||{}),$s=(M=>(M[M.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",M[M.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",M[M.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",M[M.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",M[M.MUTE_AUDIO=32772]="MUTE_AUDIO",M[M.MUTE_VIDEO=32773]="MUTE_VIDEO",M[M.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",M[M.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",M[M.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",M[M.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",M[M.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",M[M.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",M[M.SWITCH_CAMERA=32780]="SWITCH_CAMERA",M[M.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",M[M.REPLACE_VIDEO=32782]="REPLACE_VIDEO",M[M.REPLACE_AUDIO=32783]="REPLACE_AUDIO",M[M.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",M[M.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",M[M.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",M[M.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",M[M.JOIN=32788]="JOIN",M[M.LEAVE=32789]="LEAVE",M[M.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",M[M.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",M[M.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",M[M.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",M[M.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",M[M.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",M[M.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",M[M.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",M[M.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",M[M.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",M[M.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",M[M.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",M[M.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",M[M.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",M[M.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",M[M.PUBLISH_AUX=32805]="PUBLISH_AUX",M[M.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",M[M.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",M[M.VIDEO_ENCODER=4004]="VIDEO_ENCODER",M[M.VIDEO_DECODER=4005]="VIDEO_DECODER",M))($s||{}),al=(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))(al||{}),hm=(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))(hm||{}),Ra=(e=>(e.user="user",e.environment="environment",e))(Ra||{}),ya=(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))(ya||{}),cl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(cl||{}),dl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(dl||{}),mm=(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))(mm||{}),Et=1e8,tl=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},$i=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))($i||{}),qt=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(qt||{}),ba=(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))(ba||{}),ll=(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))(ll||{}),pm=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(pm||{}),ul=(m=>(m[m.SUCCESS=0]="SUCCESS",m[m.FAILED=1]="FAILED",m[m.WEBCODEC_INIT=2]="WEBCODEC_INIT",m[m.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",m[m.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",m[m.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",m[m.WASM_INIT=6]="WASM_INIT",m[m.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",m[m.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",m[m.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",m[m.TEST=10]="TEST",m[m.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",m))(ul||{}),Po=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(Po||{}),jt=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(jt||{}),Gs=(e=>(e.CANVAS="canvas",e.API="api",e))(Gs||{}),hl=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(hl||{});var L={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"},Ve={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(o){return`exchange sdp failed ${o.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(o){return`'${o}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(o){return`${o}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var fm=(o,i)=>i?`${ti}/${o}/${i}`:`${ti}/${o}/index.html`;var dg=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let o=localStorage==null?void 0:localStorage.getItem(cd);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function P(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";ne(Ve[i])?s=Ve[i](e):te(Ve[i])&&(s=Ve[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=dg();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ne(l[i])?a=l[i](e):te(l[i])&&(a=l[i]));let u=s;return Ut()&&(c&&c[i]&&(ne(c[i])?n=c[i](e):te(c[i])&&(n=c[i])),n&&(r?u=`${n}
|
|
7
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${fm("zh-cn",a)}
|
|
6
8
|
|
|
7
|
-
`:
|
|
9
|
+
`:u=`${n}
|
|
8
10
|
|
|
9
|
-
`,
|
|
10
|
-
Refer to: ${
|
|
11
|
-
`),f}var Ql=ji(qh(),1);var k_=1,L_=0,rd=class{constructor(t=!0){u(this,"countMap",new Map);u(this,"distributionMap",new Map);u(this,"version");u(this,"log",$.createLogger({id:"kv"}));t&&(V.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===D.AUDIO?501700:511700,cost:r})}),V.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===D.AUDIO?501700:511700,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:Rc(this.version||at),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,max:s=5e3}){var l;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;e>s&&(e=s),this.countMap.set(t,(this.countMap.get(t)||0)+1);let n=((l=this.distributionMap)==null?void 0:l.get(t))||new Map,c=0;if(ke(r))c=Math.floor(e/r);else for(let m=r.length-1;m>0;m--)if(e>r[m]){c=m;break}n.set(c,(n.get(c)||0)+1),this.distributionMap.set(t,n)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:k_,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&&(ke(e)?r=e:(!P(e.extraCode)||!P(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:L_,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},id=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J[J.use=500718]="use",J[J.switchRoom=500719]="switchRoom",J[J.sendSEIMessage=5e5]="sendSEIMessage",J[J.sendCustomMessage=500001]="sendCustomMessage",J))(id||{}),Jl=(_=>(_[_.AudioMixer=550700]="AudioMixer",_[_.AIDenoiser=551700]="AIDenoiser",_[_.VirtualBackground=570700]="VirtualBackground",_[_.Beauty=571700]="Beauty",_[_.Watermark=572700]="Watermark",_[_.BasicBeauty=574700]="BasicBeauty",_[_.CDNStreaming=590700]="CDNStreaming",_[_.DeviceDetector=591700]="DeviceDetector",_[_.Debug=592700]="Debug",_[_.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",_[_.VideoMixer=594700]="VideoMixer",_[_.AudioProcessor=595700]="AudioProcessor",_))(Jl||{}),zl=(_=>(_[_.AudioMixer=550701]="AudioMixer",_[_.AIDenoiser=551701]="AIDenoiser",_[_.VirtualBackground=570701]="VirtualBackground",_[_.Beauty=571701]="Beauty",_[_.Watermark=572701]="Watermark",_[_.BasicBeauty=574701]="BasicBeauty",_[_.CDNStreaming=590701]="CDNStreaming",_[_.DeviceDetector=591701]="DeviceDetector",_[_.Debug=592701]="Debug",_[_.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",_[_.VideoMixer=594701]="VideoMixer",_[_.AudioProcessor=595701]="AudioProcessor",_))(zl||{}),Xl=(_=>(_[_.AudioMixer=550702]="AudioMixer",_[_.AIDenoiser=551702]="AIDenoiser",_[_.VirtualBackground=570702]="VirtualBackground",_[_.Beauty=571702]="Beauty",_[_.Watermark=572702]="Watermark",_[_.BasicBeauty=574702]="BasicBeauty",_[_.CDNStreaming=590702]="CDNStreaming",_[_.DeviceDetector=591702]="DeviceDetector",_[_.Debug=592702]="Debug",_[_.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",_[_.VideoMixer=594702]="VideoMixer",_[_.AudioProcessor=595702]="AudioProcessor",_))(Xl||{});var U_=new rd(!0),qo=new rd(!1);var Q=U_;var Ce={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},V_=new Map([[Ht,["Firefox",Dc]],[Ps,["Edg",Oc]],[Fs,["Chrome",Jc]],[It,["Safari",di]],[Ar,["TBS",kc]],[ks,["XWEB",Lc]],[Ls&&Qi,["WeChat",Uc]],[Hn,["QQ(Win)",Vc]],[Vs,["QQ(Mobile)",Os]],[Us,["QQ(Mobile X5)",Os]],[Wn,["QQ(Mac)",Fc]],[Gn,["QQ(iPad)",$c]],[qn,["MI",Bc]],[Jn,["HW",Hc]],[zn,["Samsung",Wc]],[Xn,["OPPO",Gc]],[Qn,["VIVO",jc]],[Vo,["EDGE",Mc]],[$n,["SogouMobile",xc]],[Bn,["Sogou",Pc]]]);function nd(){let i=V_.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Zl=function(){return!(El||Vo||Ps&&fl<80||Ht&&wc<56)},Kl=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},ad=function(){if(!navigator.mediaDevices)return gi()||$.error(Xt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},Jh=!1;function gi(){return location.protocol==="http:"&&!vr?(Jh||$.error(Be({key:$e.NOT_SUPPORTED_HTTP})),Jh=!0,!0):!1}var em=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Yl=function(){return y(this,null,function*(){if(Ce.detail.isH264EncodeSupported&&Ce.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Ce.detail.isH264EncodeSupported,isVp8EncodeSupported:Ce.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(D.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(),Ce.detail.isH264EncodeSupported=t,Ce.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:Ce.detail.isH264EncodeSupported,isVp8EncodeSupported:Ce.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Xh=function(){return y(this,null,function*(){if(Ce.detail.isH264DecodeSupported&&Ce.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Ce.detail.isH264DecodeSupported,isVp8DecodeSupported:Ce.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return ud()?(r.addTransceiver(D.VIDEO,{direction:"recvonly"}),i=yield r.createOffer()):i=yield r.createOffer({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}}})},cd=vc(i=>y(void 0,null,function*(){let t=Date.now(),e=rm(),r=ad(),o=Kl();if(Ce.detail.isWebRTCSupported=e,Ce.detail.isMediaDevicesSupported=r,Ce.detail.isWebCodecsSupported=o,Ce.detail.isScreenShareSupported=da(),Ce.detail.isSmallStreamSupported=dd(),i===37)return Object.assign(Ce.detail,yield B_()),Ce.detail.isBrowserSupported=o,Ce.result=r&&o,Ce.result||$.error(`${navigator.userAgent} ${Un(Ce.detail,!1)}`),zh(i),Q.addNumber({key:523800,value:Date.now()-t}),Ce;if(Ce.result&&Ce.detail.isH264EncodeSupported&&Ce.detail.isVp8EncodeSupported&&Ce.detail.isH264DecodeSupported&&Ce.detail.isVp8DecodeSupported)return Ce;let s=Zl(),[{isH264EncodeSupported:n,isVp8EncodeSupported:c},{isH264DecodeSupported:l,isVp8DecodeSupported:m}]=yield Promise.all([Yl(),Xh()]);if(!n||!c){let f=yield Yl();$.warn(`detect encode again h264:${n} vp8:${c} result: ${JSON.stringify(f)}`),n=f.isH264EncodeSupported,c=f.isVp8EncodeSupported}if(n&&l&&mt&&ci&&!ks&&!Ar){let{encode:f,decode:E}=yield $_();n=f,l=E}return Ce.result=s&&e&&r&&(n||c)&&(l||m),Ce.detail.isBrowserSupported=s,Ce.detail.isWebRTCSupported=e,Ce.detail.isH264EncodeSupported=n,Ce.detail.isVp8EncodeSupported=c,Ce.detail.isH264DecodeSupported=l,Ce.detail.isVp8DecodeSupported=m,Ce.result||$.error(`${navigator.userAgent} ${Un(Ce.detail,!1)}`),zh(),Q.addNumber({key:523800,value:Date.now()-t}),Ce})),F_=function(){return Ce.result},da=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},od=null;function $_(){return y(this,null,function*(){return od||(od=new Promise(i=>y(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,c=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(c),m.close(),f.close(),l.getTracks().forEach(M=>M.stop())},c=setTimeout(()=>{e(),i(t)},2*1e3);let l=r.captureStream(),m=new RTCPeerConnection({}),f=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});m.addEventListener("icecandidate",M=>f.addIceCandidate(M.candidate)),f.addEventListener("icecandidate",M=>m.addIceCandidate(M.candidate)),m.addTrack(l.getVideoTracks()[0],l);let E=yield m.createOffer();yield m.setLocalDescription(E),yield f.setRemoteDescription(E);let _=yield f.createAnswer(),v=Ql.default.parse(_.sdp),k=v.media[0].rtp.findIndex(M=>M.codec==="H264");v.media[0].rtp=[v.media[0].rtp[k]],v.media[0].fmtp=v.media[0].fmtp.filter(M=>M.payload===v.media[0].rtp[0].payload),v.media[0].rtcpFb&&(v.media[0].rtcpFb=v.media[0].rtcpFb.filter(M=>M.payload===v.media[0].rtp[0].payload)),_.sdp=Ql.default.write(v),yield f.setLocalDescription(_),yield m.setRemoteDescription(_),n=setInterval(()=>y(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let[M,N]=yield Promise.all([m.getSenders()[0].getStats(),f.getReceivers()[0].getStats()]);t.encode||M.forEach(B=>{B.type==="outbound-rtp"&&B.mediaType===D.VIDEO&&B.bytesSent>0&&(t.encode=!0)}),t.decode||N.forEach(B=>{B.type==="inbound-rtp"&&B.mediaType===D.VIDEO&&B.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),$.warn("detectH264Supported failed",r),i({encode:!0,decode:!0})}})).then(i=>(i.encode||(i.decode=!0),(!i.encode||!i.decode)&&$.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${yr}`),i)),od)})}var sd=null;function B_(){return y(this,null,function*(){return sd||(sd=new Promise(i=>y(this,null,function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!Kl()){i(t);return}let e=null,r=null,o=null,s=()=>{o&&clearTimeout(o),e=null,r=null};try{e=document.createElement("canvas"),r=e.getContext("2d"),e.width=320,e.height=240;let n=0,c=()=>{!r||!e||(r.fillStyle=`hsl(${n%360}, 50%, 50%)`,r.fillRect(0,0,e.width,e.height),r.fillStyle="white",r.font="20px Arial",r.fillText(`Frame ${n}`,10,30),n++)};o=setTimeout(()=>{s(),i(t)},5e3);let l=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E"}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(l.map(f=>y(this,null,function*(){let E={type:f.type,encodeSupported:!1,decodeSupported:!1},_;try{_=yield new Promise((v,k)=>y(this,null,function*(){let M=new VideoEncoder({output:B=>{v(B),E.encodeSupported=!0},error:B=>{k(B)}});M.configure(f.encodeConfig),c();let N=new VideoFrame(e,{timestamp:0});M.encode(N,{keyFrame:!0}),N.close(),yield M.flush(),M.close()}))}catch(v){return $.warn(`${f.type} encoder error:`,v),E}try{yield new Promise((v,k)=>y(this,null,function*(){let M=new VideoDecoder({output:N=>{E.decodeSupported=!0,v(0),N.close()},error:k});M.configure(f.decodeConfig),M.decode(_),yield M.flush(),M.close()}))}catch(v){$.warn(`${f.type} decoder error:`,v)}return E})))).forEach(f=>{f.type==="h264"?(t.isH264EncodeSupported=f.encodeSupported,t.isH264DecodeSupported=f.decodeSupported):f.type==="vp8"&&(t.isVp8EncodeSupported=f.encodeSupported,t.isVp8DecodeSupported=f.decodeSupported)}),s(),i(t)}catch(n){s(),$.warn("detectWebCodecsSupported failed:",n),i(t)}})),sd)})}var H_=(i,t,e)=>{location.protocol==="http:"&&!vr&&(i[t]=()=>{throw new ue({code:q.INVALID_OPERATION,message:Xt.NOT_SUPPORTED_HTTP})})},W_=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(st(i.selected)&&!i.selected):!1};function Qh(){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 Yh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Zh(){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 Kh(){return"captureStream"in HTMLCanvasElement.prototype}function ef(){return Ls||lt||$r&&$r<63?!1:!!(Zl()&&Kh())}function tf(){return!($r<74||Vo||Jt<11||wc<46)}function dd(){return ef()||tf()}var G_=function(){if(P(window.RTCRtpTransceiver)||!ud()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:ol}),i.addTransceiver(D.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function j_(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function rf(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function q_(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ud(){return Jt===11&&!vl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var J_=!(!ud()||ci&&$r<86);function z_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ua="RTCRtpSender"in window;function X_(){return ua&&"replaceTrack"in window.RTCRtpSender.prototype}function Q_(){return ua&&"setParameters"in window.RTCRtpSender.prototype&&rf()}var Y_="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,js=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,tm=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,la=ua&&"createEncodedStreams"in window.RTCRtpSender.prototype&&qc()>=86,of="RTCRtpScriptTransform"in window,ma=ua&&(la||of),rm=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function sf(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return P(window.AudioDecoder)||(i.AudioDecoder=!0),P(window.AudioEncoder)||(i.AudioEncoder=!0),P(window.VideoDecoder)||(i.VideoDecoder=!0),P(window.VideoEncoder)||(i.VideoEncoder=!0),P(window.ImageDecoder)||(i.ImageDecoder=!0),i}function nf(){return"mediaSession"in navigator&&!P(navigator.mediaSession.setActionHandler)}function af(){return!P(window.WebTransport)}function Z_(){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 K_(){let i={browser:`${Fr.name}/${Fr.version}`,os:$s(),displayResolution:Qh(),isScreenShareSupported:da(),isWebRTCSupported:rm(),isGetUserMediaSupported:Yh(),isWebAudioSupported:Zh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:sf(),isMediaSessionSupported:nf(),isWebTransportSupported:af()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var cf="checkResult";function zh(i=30){Hs.setItem(cf+i,{ua:navigator.userAgent,checkResult:Ce})}function im(i){gi();let t=Hs.getItem(cf+i);t&&t.ua===navigator.userAgent&&t.checkResult&&eT(t.checkResult.detail,Ce.detail)&&(Ce=t.checkResult),cd(i)}function eT(i,t){return er(i)?Object.keys(t).every(e=>e in i):!1}function Ei(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var tT="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var uf=ji(Zi(),1);var df=Symbol("instance"),kA=Symbol("abortCtrl"),ld=Symbol("cacheResult"),pa=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,ga.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},ha=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function rT(i){return typeof i=="object"&&i&&"then"in i}var fa=new Map;function Qe(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let l=fa.get(r)||[];fa.has(r)||fa.set(r,l),l.push({from:i,to:t,action:n})}let c=s.value;s.value=function(...l){let m=this;if(e.context&&(m=de.get(typeof e.context=="function"?e.context.call(this,...l):e.context)),m.state===t)return e.sync?m[ld]:Promise.resolve(m[ld]);m.state instanceof pa&&m.state.action==e.abortAction&&m.state.abort(m);let f=null;Array.isArray(i)?i.length==0?m.state instanceof pa&&m.state.abort(m):(typeof m.state!="string"||!i.includes(m.state))&&(f=new ha(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(f=new ha(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let E=N=>{if(e.fail&&e.fail.call(this,N),e.sync){if(e.ignoreError)return N;throw N}else return e.ignoreError?Promise.resolve(N):Promise.reject(N)};if(f)return E(f);let _=m.state,v=new pa(_,t,n);ga.call(m,v);let k=N=>{var B;return m[ld]=N,v.aborted||(ga.call(m,t),(B=e.success)===null||B===void 0||B.call(this,m[ld])),N},M=N=>(ga.call(m,_,N),E(N));try{let N=c.apply(this,l);return rT(N)?N.then(k).catch(M):e.sync?k(N):Promise.resolve(k(N))}catch(N){return M(new ha(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${N}`,N instanceof Error?N:new Error(String(N))))}}}}var iT=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 ga(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(de.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var de=class i extends uf.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[df];o?this.name=o.name+"-"+o.count++:r[df]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=fa.get(t)||[],r=new Set,o=[],s=[],n=new Set,c=Object.getPrototypeOf(t);fa.has(c)&&(c.stateDiagram.forEach(m=>r.add(m)),c.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:f,action:E})=>{typeof m=="string"?o.push({from:m,to:f,action:E}):m.length?m.forEach(_=>{o.push({from:_,to:f,action:E})}):s.push({to:f,action:E})}),o.forEach(({from:m,to:f,action:E})=>{n.add(m),n.add(f),n.add(E+"ing"),r.add(`${m} --> ${E}ing : ${E}`),r.add(`${E}ing --> ${f} : ${E} \u{1F7E2}`),r.add(`${E}ing --> ${m} : ${E} \u{1F534}`)}),s.forEach(({to:m,action:f})=>{r.add(`${f}ing --> ${m} : ${f} \u{1F7E2}`),n.forEach(E=>{E!==m&&r.add(`${E} --> ${f}ing : ${f}`)})});let l=[...r];return Object.defineProperties(t,{stateDiagram:{value:l},allStates:{value:n}}),l}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={}){iT(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){ga.call(this,t)}};de.STATECHANGED="stateChanged";de.UPDATEAFSM="updateAFSM";de.INIT="[*]";de.ON="on";de.OFF="off";de.instances=new Map;de.instances2=new WeakMap;var sm=typeof window!="undefined",lf=sm&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},oT=sm&&window.cancelIdleCallback||function(i){clearTimeout(i)},mf=sm&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),_t=class _t{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=X({delay:2e3,count:0,backgroundTask:!0},r):t==="ric"?r=X({delay:1e4,count:0},r):t==="raf"?r=X({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=X({delay:2e3,count:0,backgroundTask:!0},r);let o=Te(X({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,_t.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){_t.sharedWorker||(_t.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
11
|
+
`,u+=s)),r&&(u+=`
|
|
12
|
+
Refer to: ${fm("en",a)}
|
|
13
|
+
`),u}var Tl=Ge(Cm(),1);var Eg=1,Sg=0,va=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",y.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),S.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}),S.on("266",({result:e})=>{e?this.addSuccessEvent({key:525700}):this.addFailedEvent({key:525700})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Zn(this.version||we),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,s])=>({uint32_item_key:r,uint32_item_value:s}))}))};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 s;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=((s=this.distributionMap)==null?void 0:s.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,max:s=5e3}){var c;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;e>s&&(e=s),this.countMap.set(i,(this.countMap.get(i)||0)+1);let n=((c=this.distributionMap)==null?void 0:c.get(i))||new Map,a=0;if(q(t))a=Math.floor(e/t);else for(let l=t.length-1;l>0;l--)if(e>t[l]){a=l;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:Eg,useUV:!1}),e)){let s=+String(i).slice(-3);s<800&&s>=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&&(q(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Sg,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},Da=(J=>(J[J.enterRoom=500700]="enterRoom",J[J.exitRoom=500701]="exitRoom",J[J.switchRole=500702]="switchRole",J[J.destroy=500703]="destroy",J[J.startLocalAudio=500704]="startLocalAudio",J[J.updateLocalAudio=500705]="updateLocalAudio",J[J.stopLocalAudio=500706]="stopLocalAudio",J[J.startLocalVideo=500707]="startLocalVideo",J[J.updateLocalVideo=500708]="updateLocalVideo",J[J.stopLocalVideo=500709]="stopLocalVideo",J[J.startScreenShare=500710]="startScreenShare",J[J.updateScreenShare=500711]="updateScreenShare",J[J.stopScreenShare=500712]="stopScreenShare",J[J.startRemoteVideo=500713]="startRemoteVideo",J[J.updateRemoteVideo=500714]="updateRemoteVideo",J[J.stopRemoteVideo=500715]="stopRemoteVideo",J[J.muteRemoteAudio=500716]="muteRemoteAudio",J[J.setRemoteAudioVolume=500717]="setRemoteAudioVolume",J[J.use=500718]="use",J[J.switchRoom=500719]="switchRoom",J[J.sendSEIMessage=5e5]="sendSEIMessage",J[J.sendCustomMessage=500001]="sendCustomMessage",J))(Da||{}),fl=(m=>(m[m.AudioMixer=550700]="AudioMixer",m[m.AIDenoiser=551700]="AIDenoiser",m[m.VirtualBackground=570700]="VirtualBackground",m[m.Beauty=571700]="Beauty",m[m.Watermark=572700]="Watermark",m[m.BasicBeauty=574700]="BasicBeauty",m[m.CDNStreaming=590700]="CDNStreaming",m[m.DeviceDetector=591700]="DeviceDetector",m[m.Debug=592700]="Debug",m[m.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",m[m.VideoMixer=594700]="VideoMixer",m[m.AudioProcessor=595700]="AudioProcessor",m))(fl||{}),_l=(m=>(m[m.AudioMixer=550701]="AudioMixer",m[m.AIDenoiser=551701]="AIDenoiser",m[m.VirtualBackground=570701]="VirtualBackground",m[m.Beauty=571701]="Beauty",m[m.Watermark=572701]="Watermark",m[m.BasicBeauty=574701]="BasicBeauty",m[m.CDNStreaming=590701]="CDNStreaming",m[m.DeviceDetector=591701]="DeviceDetector",m[m.Debug=592701]="Debug",m[m.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",m[m.VideoMixer=594701]="VideoMixer",m[m.AudioProcessor=595701]="AudioProcessor",m))(_l||{}),gl=(m=>(m[m.AudioMixer=550702]="AudioMixer",m[m.AIDenoiser=551702]="AIDenoiser",m[m.VirtualBackground=570702]="VirtualBackground",m[m.Beauty=571702]="Beauty",m[m.Watermark=572702]="Watermark",m[m.BasicBeauty=574702]="BasicBeauty",m[m.CDNStreaming=590702]="CDNStreaming",m[m.DeviceDetector=591702]="DeviceDetector",m[m.Debug=592702]="Debug",m[m.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",m[m.VideoMixer=594702]="VideoMixer",m[m.AudioProcessor=595702]="AudioProcessor",m))(gl||{});var Js=(c=>(c[c.ENCODER_TYPE=513700]="ENCODER_TYPE",c[c.ENCDER_HW_SW=513701]="ENCDER_HW_SW",c[c.ENCODE_RESULT=513702]="ENCODE_RESULT",c[c.ENCODE_FAILED_OS=513703]="ENCODE_FAILED_OS",c[c.ENCODE_H264_RESULT=513704]="ENCODE_H264_RESULT",c[c.ENCODE_H265_RESULT=513705]="ENCODE_H265_RESULT",c[c.ENCODE_VP8_RESULT=513706]="ENCODE_VP8_RESULT",c[c.ENCODE_H265_FALLBACK=513e3]="ENCODE_H265_FALLBACK",c))(Js||{}),qs=(T=>(T[T.DECODER_TYPE=514700]="DECODER_TYPE",T[T.DECODER_HW_SW=514701]="DECODER_HW_SW",T[T.DECODE_RESULT=514702]="DECODE_RESULT",T[T.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",T[T.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",T[T.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",T[T.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",T[T.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",T[T.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",T[T.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",T[T.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",T[T.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",T[T.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",T[T.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",T[T.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",T[T.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",T))(qs||{});var Ig=new va(!0),Br=new va(!1);var N=Ig;var Z={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},Ag=new Map([[ae,["Firefox",ra]],[yo,["Edg",sa]],[Mo,["Chrome",Ea]],[xe,["Safari",Bi]],[Ht,["TBS",ca]],[bo,["XWEB",da]],[No&&ur,["WeChat",la]],[Os,["QQ(Win)",ua]],[Do,["QQ(Mobile)",Ao]],[vo,["QQ(Mobile X5)",Ao]],[Ms,["QQ(Mac)",ha]],[ks,["QQ(iPad)",ma]],[xs,["MI",pa]],[Ls,["HW",fa]],[Ps,["Samsung",_a]],[Us,["OPPO",ga]],[Vs,["VIVO",Ta]],[kr,["EDGE",oa]],[vs,["SogouMobile",na]],[Ds,["Sogou",aa]]]);function Cg(){let o=Ag.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var Sl=function(){return!(Hd||kr||yo&&Bd<80||ae&&Ro<56)},Il=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},ka=function(){if(!navigator.mediaDevices)return Wi()||y.error(Ve.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},Rm=!1;function Wi(){return location.protocol==="http:"&&!Gt?(Rm||y.error(P({key:L.NOT_SUPPORTED_HTTP})),Rm=!0,!0):!1}var js=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},El=function(){return f(this,null,function*(){var r,s,n;if(Z.detail.isH264EncodeSupported&&Z.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Z.detail.isH264EncodeSupported,isVp8EncodeSupported:Z.detail.isVp8EncodeSupported,isH265EncodeSupported:Z.detail.isH265EncodeSupported};let o,i=!1,e=!1,t=!1;try{let a=new RTCPeerConnection,c=document.createElement(p.CANVAS);c.getContext("2d");let l=c.captureStream(0);return a.addTrack(l.getVideoTracks()[0],l),o=yield a.createOffer(),i=((r=o.sdp)==null?void 0:r.toLowerCase().indexOf("h264"))!==-1,e=((s=o.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,t=((n=o.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:i,isVp8EncodeSupported:e,isH265EncodeSupported:t}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},wa=function(){return f(this,null,function*(){var t;if(Z.detail.isH264DecodeSupported&&Z.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Z.detail.isH264DecodeSupported,isVp8DecodeSupported:Z.detail.isVp8DecodeSupported,isH265DecodeSupported:Z.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;ht()?(r.addTransceiver(p.VIDEO,{direction:"recvonly"}),o=yield r.createOffer()):o=yield r.createOffer({offerToReceiveVideo:!0}),o.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),o.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((t=o.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return r.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},xa=Kn(o=>f(void 0,null,function*(){let i=Date.now(),e=yl(),t=ka(),r=Il();if(Z.detail.isWebRTCSupported=e,Z.detail.isMediaDevicesSupported=t,Z.detail.isWebCodecsSupported=r,Z.detail.isScreenShareSupported=Xs(),Z.detail.isSmallStreamSupported=Pa(),o===37)return Object.assign(Z.detail,yield bg()),Z.detail.isBrowserSupported=r,Z.result=t&&r,Z.result||y.error(`${navigator.userAgent} ${ys(Z.detail,!1)}`),ym(o),N.addNumber({key:523800,value:Date.now()-i}),Z;if(Z.result&&Z.detail.isH264EncodeSupported&&Z.detail.isVp8EncodeSupported&&Z.detail.isH265EncodeSupported&&Z.detail.isH264DecodeSupported&&Z.detail.isVp8DecodeSupported&&Z.detail.isH265DecodeSupported)return Z;let s=Sl(),[{isH264EncodeSupported:n,isVp8EncodeSupported:a,isH265EncodeSupported:c},{isH264DecodeSupported:l,isVp8DecodeSupported:u,isH265DecodeSupported:h}]=yield Promise.all([El(),wa()]);if(!n||!a){let m=yield El();y.warn(`detect encode again h264:${n} vp8:${a} result: ${JSON.stringify(m)}`),n=m.isH264EncodeSupported,a=m.isVp8EncodeSupported}if(n&&l&&pe&&it&&!bo&&!Ht){let{encode:m,decode:_}=yield yg();n=m,l=_}return Z.result=s&&e&&t&&(n||a)&&(l||u)&&(c||h),Z.detail.isBrowserSupported=s,Z.detail.isWebRTCSupported=e,Z.detail.isH264EncodeSupported=n,Z.detail.isVp8EncodeSupported=a,Z.detail.isH265EncodeSupported=c,Z.detail.isH264DecodeSupported=l,Z.detail.isVp8DecodeSupported=u,Z.detail.isH265DecodeSupported=h,Z.result||y.error(`${navigator.userAgent} ${ys(Z.detail,!1)}`),ym(),N.addNumber({key:523800,value:Date.now()-i}),Z})),Rg=function(){return Z.result},Xs=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Oa=null;function yg(){return f(this,null,function*(){return Oa||(Oa=new Promise(o=>f(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 s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(g=>g.stop())},a=setTimeout(()=>{e(),o(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",g=>u.addIceCandidate(g.candidate)),u.addEventListener("icecandidate",g=>l.addIceCandidate(g.candidate)),l.addTrack(c.getVideoTracks()[0],c);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let m=yield u.createAnswer(),_=Tl.default.parse(m.sdp),A=_.media[0].rtp.findIndex(g=>g.codec==="H264");_.media[0].rtp=[_.media[0].rtp[A]],_.media[0].fmtp=_.media[0].fmtp.filter(g=>g.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(g=>g.payload===_.media[0].rtp[0].payload)),m.sdp=Tl.default.write(_),yield u.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[g,T]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||g.forEach(O=>{O.type==="outbound-rtp"&&O.mediaType===p.VIDEO&&O.bytesSent>0&&(i.encode=!0)}),i.decode||T.forEach(O=>{O.type==="inbound-rtp"&&O.mediaType===p.VIDEO&&O.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),y.warn("detectH264Supported failed",t),o({encode:!0,decode:!0})}})).then(o=>(o.encode||(o.decode=!0),(!o.encode||!o.decode)&&y.warn(`detectH264Supported encode: ${o.encode} decode: ${o.decode} ${Bt}`),o)),Oa)})}var Ma=null;function bg(){return f(this,null,function*(){return Ma||(Ma=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!Il()){o(i);return}let e=null,t=null,r=null,s=()=>{r&&clearTimeout(r),e=null,t=null};try{e=document.createElement("canvas"),t=e.getContext("2d"),e.width=320,e.height=240;let n=0,a=()=>{!t||!e||(t.fillStyle=`hsl(${n%360}, 50%, 50%)`,t.fillRect(0,0,e.width,e.height),t.fillStyle="white",t.font="20px Arial",t.fillText(`Frame ${n}`,10,30),n++)};r=setTimeout(()=>{s(),o(i)},5e3);let c=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E"}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(c.map(u=>f(this,null,function*(){let h={type:u.type,encodeSupported:!1,decodeSupported:!1},m;try{m=yield new Promise((_,A)=>f(this,null,function*(){let g=new VideoEncoder({output:O=>{_(O),h.encodeSupported=!0},error:O=>{A(O)}});g.configure(u.encodeConfig),a();let T=new VideoFrame(e,{timestamp:0});g.encode(T,{keyFrame:!0}),T.close(),yield g.flush(),g.close()}))}catch(_){return y.warn(`${u.type} encoder error:`,_),h}try{yield new Promise((_,A)=>f(this,null,function*(){let g=new VideoDecoder({output:T=>{h.decodeSupported=!0,_(0),T.close()},error:A});g.configure(u.decodeConfig),g.decode(m),yield g.flush(),g.close()}))}catch(_){y.warn(`${u.type} decoder error:`,_)}return h})))).forEach(u=>{u.type==="h264"?(i.isH264EncodeSupported=u.encodeSupported,i.isH264DecodeSupported=u.decodeSupported):u.type==="vp8"&&(i.isVp8EncodeSupported=u.encodeSupported,i.isVp8DecodeSupported=u.decodeSupported)}),s(),o(i)}catch(n){s(),y.warn("detectWebCodecsSupported failed:",n),o(i)}})),Ma)})}var Ng=(o,i,e)=>{location.protocol==="http:"&&!Gt&&(o[i]=()=>{throw new b({code:I.INVALID_OPERATION,message:Ve.NOT_SUPPORTED_HTTP})})},hr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(de(o.selected)&&!o.selected):!1};function bm(){let o="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";o+=`${i} * ${e}`}return o}function Nm(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function vm(){let o={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){o.isSupported=!0;break}return o.isSupported}function Dm(){return"captureStream"in HTMLCanvasElement.prototype}function La(){return No||Ie||lt&<<63?!1:!!(Sl()&&Dm())}function Om(){return!(lt<74||kr||Je<11||Ro<46)}function Pa(){return La()||Om()}var vg=function(){if(E(window.RTCRtpTransceiver)||!ht()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:dr}),o.addTransceiver(p.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function Fr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function mr(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function hi(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function ht(){return Je===11&&!zd?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Vo=!(!ht()||it&<<86);function Dg(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var zs="RTCRtpSender"in window;function Al(){return zs&&"replaceTrack"in window.RTCRtpSender.prototype}function Qs(){return zs&&"setParameters"in window.RTCRtpSender.prototype&&mr()}var Cl="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,mi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Rl=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ji=zs&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Oo()>=86,Bo="RTCRtpScriptTransform"in window,Ys=zs&&(Ji||Bo),yl=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Mm(){let o={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return E(window.AudioDecoder)||(o.AudioDecoder=!0),E(window.AudioEncoder)||(o.AudioEncoder=!0),E(window.VideoDecoder)||(o.VideoDecoder=!0),E(window.VideoEncoder)||(o.VideoEncoder=!0),E(window.ImageDecoder)||(o.ImageDecoder=!0),o}function km(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function wm(){return!E(window.WebTransport)}function Og(){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 Mg(){let o={browser:`${ai.name}/${ai.version}`,os:Sa(),displayResolution:bm(),isScreenShareSupported:Xs(),isWebRTCSupported:yl(),isGetUserMediaSupported:Nm(),isWebAudioSupported:vm(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Mm(),isMediaSessionSupported:km(),isWebTransportSupported:wm()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var xm="checkResult";function ym(o=30){wo.setItem(xm+o,{ua:navigator.userAgent,checkResult:Z})}function bl(o){Wi();let i=wo.getItem(xm+o);i&&i.ua===navigator.userAgent&&i.checkResult&&kg(i.checkResult.detail,Z.detail)&&(Z=i.checkResult),xa(o)}function kg(o,i){return ft(o)?Object.keys(i).every(e=>e in o):!1}function Hr(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Ua="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Pm=Ge(tt(),1);var Lm=Symbol("instance"),uA=Symbol("abortCtrl"),Va=Symbol("cacheResult"),Zs=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,tn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Ks=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function wg(o){return typeof o=="object"&&o&&"then"in o}var en=new Map;function Te(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=en.get(t)||[];en.has(t)||en.set(t,c),c.push({from:o,to:i,action:n})}let a=s.value;s.value=function(...c){let l=this;if(e.context&&(l=$.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Va]:Promise.resolve(l[Va]);l.state instanceof Zs&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof Zs&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new Ks(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new Ks(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let h=T=>{if(e.fail&&e.fail.call(this,T),e.sync){if(e.ignoreError)return T;throw T}else return e.ignoreError?Promise.resolve(T):Promise.reject(T)};if(u)return h(u);let m=l.state,_=new Zs(m,i,n);tn.call(l,_);let A=T=>{var O;return l[Va]=T,_.aborted||(tn.call(l,i),(O=e.success)===null||O===void 0||O.call(this,l[Va])),T},g=T=>(tn.call(l,m,T),h(T));try{let T=a.apply(this,c);return wg(T)?T.then(A).catch(g):e.sync?A(T):Promise.resolve(A(T))}catch(T){return g(new Ks(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${T}`,T instanceof Error?T:new Error(String(T))))}}}}var xg=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 tn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit($.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var $=class o extends Pm.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=o.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[Lm];r?this.name=r.name+"-"+r.count++:t[Lm]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=en.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);en.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(m=>{r.push({from:m,to:u,action:h})}):s.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}`)}),s.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 c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=o.instances.get(i),e||o.instances.set(i,e=new o(i,void 0,Object.create(o.prototype)))):(e=o.instances2.get(i),e||o.instances2.set(i,e=new o(i.constructor.name,void 0,Object.create(o.prototype)))),e}static getState(i){var e;return(e=o.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){xg(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){tn.call(this,i)}};$.STATECHANGED="stateChanged";$.UPDATEAFSM="updateAFSM";$.INIT="[*]";$.ON="on";$.OFF="off";$.instances=new Map;$.instances2=new WeakMap;var vl=typeof window!="undefined",Um=vl&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Lg=vl&&window.cancelIdleCallback||function(o){clearTimeout(o)},Vm=vl&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Me=class Me{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=w(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,Me.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Me.sharedWorker||(Me.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
12
14
|
const timers = new Map();
|
|
13
15
|
self.onmessage = function(e) {
|
|
14
16
|
const { taskId, delay, type } = e.data;
|
|
@@ -21,14 +23,15 @@ Refer to: ${Vh("en",c)}
|
|
|
21
23
|
timers.delete(taskId);
|
|
22
24
|
}
|
|
23
25
|
};
|
|
24
|
-
`],{type:"application/javascript"}))),
|
|
25
|
-
${r.stack}`)),this.sendRequest(si(this._configs.sdkAppId,qi.LOG),o)}sendRequest(t,e){setTimeout(()=>ai({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},je=new nm;var Jo=new WeakMap;function zo({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let c=Xi({retryFunction:n.value,settings:i,onError({error:l,retry:m,reject:f,retryFuncArgs:E}){var _;t?t.call(this,l,()=>{var v;(v=Jo.get(o))!=null&&v.has(s)?m():f(l)},f,E):(_=Jo.get(o))!=null&&_.has(s)?m():f(l)},onRetrying(l,m){var f;zi(e)&&e.call(this,l,m),(f=Jo.get(o))!=null&&f.has(s)&&(Jo.get(o).get(s).stopRetry=m)},onRetryFailed:r});return n.value=function(...l){let m=Jo.get(o);return m?m.set(s,{args:l}):Jo.set(o,new Map([[s,{args:l}]])),c.apply(this,l).finally(()=>{var f;return(f=Jo.get(o))==null?void 0:f.delete(s)})},n}}var jr=class extends de{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=Oo,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 isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}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 y(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=Be({key:$e.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ue({code:q.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Yi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(D.ENDED),this._interval>0&&vt.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():bl?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 Vt(this.element,this.element).add(D.PLAYING,e).add(D.ENDED,e).add(D.PAUSE,e).add(D.ERROR,e).add(D.LOADEDDATA,e).add(D.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Gr==null||Gr.create(e,e).add(D.ENDED,r).add(D.MUTE,r).add(D.UNMUTE,r),e.readyState===D.ENDED&&this.handleTrackEvent({type:D.ENDED}),e.muted&&this.handleTrackEvent({type:D.MUTE})}}bindAutoPlayEvent(){V.on(U.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ht(e)}unbindEvents(){this.element&&ht(this.element),this.unbindTrackEvents(),V.off(U.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case D.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(D.PLAYING),this._interval&&(vt.clearTask(this._interval),this._interval=-1);break;case D.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(D.ENDED);break;case D.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(D.PAUSE),lt&&(this._interval=vt.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case D.ERROR:if(this.element&&this.element.error){this.handlePaused(D.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}-${ri.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),Tl||_l?this.emit(et.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case D.LOADEDDATA:this.kind===D.VIDEO&&this.emit(et.LOADED_DATA);break;case D.LOADEDMETADATA:this.kind===D.VIDEO&&this.emit(et.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"}),Q.addSuccessEvent({key:this.kind===D.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),je.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Q.addFailedEvent({key:this.kind===D.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(et.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{Fn(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,c;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),o((c=this.element)==null?void 0:c.error)}),Fn(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){return y(this,null,function*(){switch(e.type){case D.ENDED:this.handleStopped(D.ENDED);break;case D.MUTE:this.handlePaused(D.MUTE);break;case D.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(D.UNMUTE));break}})}handlePlaying(e){var r;this._log.debug("handlePlaying",e),(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(et.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(et.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(et.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};Z([zo({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],jr.prototype,"doReplayByRecreateMediaStream",1),Z([Qe([],"PLAYING",{sync:!0})],jr.prototype,"handlePlaying",1),Z([Qe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],jr.prototype,"handlePaused",1),Z([Qe([],"STOPPED",{sync:!0})],jr.prototype,"handleStopped",1);var _i="trtc_autoplay",am=`${_i}_mask`,qs=`${_i}_wrapper`,pf=`${_i}_header`,cm=`${_i}_content`,md=`${_i}_action_wrapper`,dm=`${_i}_question`,um=`${_i}_collapse`,pd=`${_i}_action_confirm`,hf=`${_i}_detail`,ff="#2473E8",mm="dialog",nT=`${mm}-show`,aT=`${mm}-1`,cT=`${mm}-2`,gf=!1,pm=()=>!!document.querySelector(`.${qs}`),_f=`${Lr}/${Sr()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Ef=`<br><a href='${_f}' target='_blank'>${Sr()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,dT=`${Sr()?`\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${Ef}`:`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. ${Ef}`}`,lm=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(Sr()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!gf){let t=document.createElement("style");t.innerHTML=`.${am}{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;}.${am} div:not(.${md}){display:block !important;}.${qs}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${qs} a{color:${ff};}.${pf}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${cm}{margin:8px 0;}.${md}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${um}{margin-right:auto;cursor:pointer}.${dm}{height:100%;line-height:16px;cursor:pointer;}.${pd}{margin-left:8px;color:#fff;background:${ff};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${pd}:hover{opacity:0.9;}.${um},.${pd},.${cm},.${dm}{font-size:14px;}@media screen and (max-width:750px){.${qs}{width:80vw;}}`,document.head.appendChild(t),gf=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${am}"><div class='${qs}'><div class='${pf}'>${location.host}</div><div class='${cm}'>${this.content}</div><div class='${hf}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${dT}</div><div class='${md}'></div></div></div>`.trim();let e=document.createElement("button");e.className=pd,e.innerText=Sr()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=dm,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
`],{type:"application/javascript"}))),Me.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Me.workerTasks.get(e.data.taskId);r&&(Me.isBreakLoop(r)?((t=Me.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Me.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),Me.workerTasks.set(i.taskID,i),Me.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Me.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=B(),t,r=()=>{if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Me.isBreakLoop(i))return i.ricID=Um(r,{timeout:i.delay})};return i.ricID=Um(r,{timeout:i.delay})}static raf(i){let e=B(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=B()-e,e=B(),i.callback(),i.loopCount+=1,Me.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=B()-e,t>=i.delay&&(e=B()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Me.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let s=()=>{if(document.hidden){let n=B()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",s),i.onVisibilitychange=s,document.hidden&&s()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(i);return e&&clearInterval(e),t&&clearTimeout(t),r&&Vm&&Vm(r),s&&Lg(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.hasTask(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Me,"taskMap",new Map),d(Me,"currentTaskID",1),d(Me,"sharedWorker",null),d(Me,"workerTasks",new Map);var Nl=Me,re=Nl;var IA={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:p.SEI_MESSAGE,ERROR:"error"};var he={LOADED_DATA:p.LOADEDDATA,LOADED_META_DATA:p.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var fi={};vi(fi,{create:()=>Qe,remove:()=>ve});var rn=new WeakMap;function Qe(o,i){rn.has(o)||rn.set(o,[]);let e=rn.get(o),r={add:(s,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,s,n)),i.addEventListener(s,n)):(e.push(i.off.bind(i,s,n)),i.on(s,n)),r)};return r}function ve(o){let i=rn.get(o);i&&(i.forEach(e=>e()),rn.delete(o))}var Dl=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");d(this,"_sso",!1);typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:we,env:Di.QCLOUD,browserVersion:ai.name+ai.version,ua:navigator.userAgent}),S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&(this._sso=!0)})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){Gt||!y.isAbleToUpload||this._configs.env===Di.QCLOUD&&this.uploadEventToKibana(w(v({},i),{result:"success"}))}logFailedEvent(i){if(Gt||!y.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:s}=i,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||I.UNKNOWN};this._configs.env===Di.QCLOUD&&this.uploadEventToKibana(w(v({},n),{error:r}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let r={timestamp:Un(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:we,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
+
${t.stack}`));let s=this._sso?Pi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(wi(this._configs.sdkAppId,sr.LOG),s)}sendRequest(i,e){setTimeout(()=>Ui({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},se=new Dl;var _i=new WeakMap;function St({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=ni({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var _;(_=_i.get(r))!=null&&_.has(s)?l():u(c)},u,h):(m=_i.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;si(e)&&e.call(this,c,l),(u=_i.get(r))!=null&&u.has(s)&&(_i.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=_i.get(r);return l?l.set(s,{args:c}):_i.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=_i.get(r))==null?void 0:u.delete(s)})},n}}function on({fnName:o,callback:i,validateArgs:e=!0}){return function(t,r,s){let n=s.value;return s.value=function(...a){var c,l;if((c=_i.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=_i.get(t).get(o),m=!0;if(e){for(let _ of h)if(!a.find(A=>A===_)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=_i.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var gi=class extends ${constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=yr,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 isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return f(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=P({key:L.PLAY_FAILED,data:{media:this.kind,error:e}});if(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&&!ci?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.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():jd?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 Qe(this.element,this.element).add(p.PLAYING,e).add(p.ENDED,e).add(p.PAUSE,e).add(p.ERROR,e).add(p.LOADEDDATA,e).add(p.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);fi==null||fi.create(e,e).add(p.ENDED,t).add(p.MUTE,t).add(p.UNMUTE,t),e.readyState===p.ENDED&&this.handleTrackEvent({type:p.ENDED}),e.muted&&this.handleTrackEvent({type:p.MUTE})}}bindAutoPlayEvent(){S.on(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&ve(e)}unbindEvents(){this.element&&ve(this.element),this.unbindTrackEvents(),S.off(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case p.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(p.ENDED);break;case p.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(p.PAUSE),Ie&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case p.ERROR:if(this.element&&this.element.error){this.handlePaused(p.ERROR);let{code:r,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${s} userAgent: ${navigator.userAgent}`),se.uploadEvent({log:`stat-${this.kind}-${ct.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),Gd||$d?this.emit(he.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(he.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(he.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),se.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),N.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(he.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Li(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,a;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),Li(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){return f(this,null,function*(){switch(e.type){case p.ENDED:this.handleStopped(p.ENDED);break;case p.MUTE:this.handlePaused(p.MUTE);break;case p.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),yield this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(he.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};D([St({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],gi.prototype,"doReplayByRecreateMediaStream",1),D([Te([],"PLAYING",{sync:!0})],gi.prototype,"handlePlaying",1),D([Te("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],gi.prototype,"handlePaused",1),D([Te([],"STOPPED",{sync:!0})],gi.prototype,"handleStopped",1);var qi="trtc_autoplay",Ol=`${qi}_mask`,Fo=`${qi}_wrapper`,Bm=`${qi}_header`,Ml=`${qi}_content`,Ba=`${qi}_action_wrapper`,kl=`${qi}_question`,wl=`${qi}_collapse`,Fa=`${qi}_action_confirm`,Fm=`${qi}_detail`,Hm="#2473E8",Ll="dialog",Ug=`${Ll}-show`,Vg=`${Ll}-1`,Bg=`${Ll}-2`,$m=!1,Pl=()=>!!document.querySelector(`.${Fo}`),Wm=`${ti}/${Ut()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Gm=`<br><a href='${Wm}' target='_blank'>${Ut()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Fg=`${Ut()?`\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${Gm}`:`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. ${Gm}`}`,xl=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Ut()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!$m){let i=document.createElement("style");i.innerHTML=`.${Ol}{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;}.${Ol} div:not(.${Ba}){display:block !important;}.${Fo}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Fo} a{color:${Hm};}.${Bm}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ml}{margin:8px 0;}.${Ba}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${wl}{margin-right:auto;cursor:pointer}.${kl}{height:100%;line-height:16px;cursor:pointer;}.${Fa}{margin-left:8px;color:#fff;background:${Hm};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Fa}:hover{opacity:0.9;}.${wl},.${Fa},.${Ml},.${kl}{font-size:14px;}@media screen and (max-width:750px){.${Fo}{width:80vw;}}`,document.head.appendChild(i),$m=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${Ol}"><div class='${Fo}'><div class='${Bm}'>${location.host}</div><div class='${Ml}'>${this.content}</div><div class='${Fm}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Fg}</div><div class='${Ba}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Fa,e.innerText=Ut()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=kl,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
28
|
<svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
|
|
27
29
|
<path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
|
|
28
30
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
29
31
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
30
32
|
</svg>
|
|
31
|
-
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=um,o.innerText=`${Sr()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${md}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){pm()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${qs}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",$.info("show autoplay dialog"),je.uploadEvent({log:nT}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){$.warn("confirm clicked, try resume stream"),V.emit(U.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${hf}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||je.uploadEvent({log:aT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(_f,"_blank"),this._isQuestionClicked||je.uploadEvent({log:cT}),this._isQuestionClicked=!0}},Tf=lm;var rr=class extends jr{constructor(e){super(e,D.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,P(e.viewMirror)||(this.viewMirror=e.viewMirror),P(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(D.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(D.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(D.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===D.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o,s;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===D.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.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=Oo,this._log.info(`view container ${(s=this.container)==null?void 0:s.id} is recreated`)),this._pausedRetryCount>0&&!pm()&&(this._log.info(`[${Oo-this._pausedRetryCount+1}/${Oo}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;r===D.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):r===D.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,c;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&&((c=this.container)==null||c.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(et.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(Ei()&&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 c;return(c=this.element)==null?void 0:c.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function Ti(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),$.info("worklet addModule success")}catch(e){throw $.info(`worklet addModule catch error. ${e.message}`),e}})}var _a;typeof AudioContext!="undefined"?_a=AudioContext:typeof webkitAudioContext!="undefined"?_a=webkitAudioContext:typeof mozAudioContext!="undefined"&&(_a=mozAudioContext);var Cr,If=-1;Sf();function Sf(){try{if(Cr)return;Cr=new _a({sampleRate:48e3}),Cr.onstatechange=()=>{$.info(`context state: ${Cr.state}${Cr.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Js()},clearTimeout(If)}catch(i){$.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof _a}`),If=setTimeout(Sf,1e3)}}var Js=()=>{Cr.state==="suspended"?(zs(),document.addEventListener("click",Js)):Cr.state==="interrupted"?zs():(document.removeEventListener("visibilitychange",Js),document.removeEventListener("click",Js))},hm=0,fm=-1;function zs(){return new Promise((i,t)=>{if(Cr.state==="running")return i();Date.now()-hm<1e3?(clearTimeout(fm),fm=setTimeout(()=>{hm=Date.now(),Cr.resume().then(i,t)},1e3)):(clearTimeout(fm),hm=Date.now(),Cr.resume().then(i,t))}).catch(i=>{$.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Js)})}document.addEventListener("click",Js);var ze=i=>Cr;var ft=class{constructor(t){this.name=t;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,"nextInputChannelMap",new Map);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){$.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(),Q.addSuccessEvent({key:502701})}catch(o){$.error(o),Q.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(),Q.addSuccessEvent({key:502702})}catch(e){$.error(e),Q.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{let r=this.nextInputChannelMap.get(e);t._connect(e.node,r)||e.connectNext(t)})}_connect(t,e=0){return!this.node||!t?!1:((this.node2||this.node).connect(t,0,e),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,e=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,e),t}},hd=class extends ft{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 c=0;c<e.length;c++)s=e[c]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},Ta=class{constructor(){u(this,"source",new ft);u(this,"gain",new ft);u(this,"destination",new ft)}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(ze().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(Ia(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}},Xs=class extends Ta{constructor(e){super();this.context=e;u(this,"aec",new ft("aec"));u(this,"mixNode",new ft("mixNode"));u(this,"silentNode",new ft("silentNode"));u(this,"denoiser",new ft("denoiser"));u(this,"voiceChanger",new ft("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},fd=class{constructor(){u(this,"audioContext",ze("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]}},yf=new WeakMap;function Ia(i){let t=yf.get(i);if(t)return t;let e=ze();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return yf.set(i,t),t}var ir=class ir{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,V.on(U.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ir.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ir.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);';ir.workletReady=Ti(ir.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return ir.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ir.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{ir.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:ri.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=ze("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{ir.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,V.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(ir,"lastMessageTime",0),u(ir,"audioContext",ze("volume-meter")),u(ir,"workletReady");var gd=ir,Ed=class extends ft{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new gd(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return y(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()}}},_d=gd;var vf=ji(Zi(),1);var bf=i=>t=>t.deviceId===i;var Sa=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&&Qs(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(bf(o.deviceId))){let s=`${this.kind}${this.type}Added`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(bf(o.deviceId))){let s=`${this.kind}${this.type}Removed`;$.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},gm=class extends vf.EventEmitter{constructor(){super();u(this,"audioInputs",new Sa(D.AUDIO));u(this,"videoInputs",new Sa(D.VIDEO));u(this,"audioOutputs",new Sa(D.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||vt.run("interval",()=>{this.update()},{delay:1e4}))}init(){Td().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return y(this,arguments,function*(e=0){let r=yield Td(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},St=vn||ys?null:new gm;function Qs(i){return i.deviceId===i.groupId&&i.groupId===""}function Td(){return y(this,arguments,function*(i=0){if(gi()||!ad())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{Qs(r)&&(r.kind===D.AUDIO_INPUT?e.audio=!0:r.kind===D.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&&zs()}catch(o){$.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&&Em.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Qt(i=!1){return St.update(i?1:0).then(t=>t.audioInputs.devices)}function or(i=!1){return St.update(i?2:0).then(t=>t.videoInputs.devices)}var Rf=!1;function Cf(){return y(this,null,function*(){try{Rf||(Rf=!0,$.info(`speakers:${(yield to()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function to(i=!1){return y(this,null,function*(){return(lt||It)&&(i=!1),St.update(i?1:0).then(t=>t.audioOutputs.devices)})}var Em=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}_${D.VIDEO_INPUT}`;return!!Em.has(r)}function Df(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}_${D.AUDIO_INPUT}`;return!!Em.has(r)}function _m(i,t){return y(this,null,function*(){let r=(yield Qt()).find(o=>o.deviceId===xo);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function wf(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===D.AUDIO&&i===xo?yield _m(e,r):!0})}var Id,Tm=class extends Ta{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new hd);this.volumeMeter=new Ed({log:this.log}),this.volumeDestination=new ft,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Sd=class i extends jr{constructor(e){super(e,D.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",ze("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((Rr==="15.2"||Rr==="15.3"||Rr==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=Id||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,ke(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===Id&&(Id=void 0),this.bindElementEvents()}play(e){return y(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(ze("player").createAnalyser()),Cf(),Bt(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return y(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()}},yd=class extends Sd{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(et.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)}},Ad=class extends Sd{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new ft);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(ze("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(et.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"):lt||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ht(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&&Yi&&(Id=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Xo=class extends de{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?Ad:rr}){var c;super();u(this,"id",ea());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,"rotation");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=$.createLogger({id:`${this.kind[0]}t`,userId:(c=s||this.room)==null?void 0:c.userId,remoteUserId:this instanceof Ii?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Ii}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(et.PLAYER_STATE_CHANGED,l=>{V.emit(U.PLAYER_STATE_CHANGED,X({track:this},l)),this.emit("player-state-changed",l)}),this.kind===D.VIDEO&&(this.player.on(et.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(et.LOADED_DATA),V.emit(U.VIDEO_LOADED_DATA,{track:this})}),this.player.on(et.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(et.LOADED_META_DATA)}),this.player.on(et.MEDIA_TRACK_CHANGED,l=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(f=>f.setTrack(l))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(et.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||$}get kind(){return this.mediaType===1?D.AUDIO:D.VIDEO}get strMediaType(){return this.mediaType===4?D.VIDEO:this.mediaType===2?D.SCREEN:D.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 y(this,null,function*(){let o=ot(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!P(r.muted)&&this.setPlayerMute(r.muted),r&&!P(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof rr&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),ot(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!P(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===D.VIDEO)&&this.setPlayerMute(!0),r&&!P(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof rr&&(this.player.setObjectFit(this.objectFit),r&&!P(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof rr&&this.player.setContainer(o)),V.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),ot(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!==D.VIDEO||P(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(st(this.mirror)){o.setViewMirror(this.mirror),!this.isRemote&&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 y(this,null,function*(){if(!this._outputTrack||this.kind===D.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var c;e.find(l=>n===l)||(s.stop(),(c=this.subVideoPlayerMap)==null||c.delete(n))});for(let[s,n]of e.entries()){let c=this.subVideoPlayerMap.get(n);c?r&&(P(r.objectFit)||c.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new rr({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(ul(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return y(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),V.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){Vt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ht(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(ul(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 Tf;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 rr?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,c,l;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((c=this.player.element)==null?void 0:c.videoWidth)||0,s=(r==null?void 0:r.height)||((l=this.player.element)==null?void 0:l.videoHeight)||0;e===et.LOADED_META_DATA&&!o&&!s||(e===et.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,ni(this.rotation)&&([o,s]=[s,o]),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`)}};Z([Qe([],de.INIT,{sync:!0})],Xo.prototype,"close",1);var uT=Object.prototype.hasOwnProperty,{toString:lv}=Object.prototype;function lT(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(Lt(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(uT.call(i,t))return!1;return!0}}return!1}var ya=lT;var mT=function(i){return y(this,null,function*(){let t=hT(i);$.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Qt(),$.info(`microphones: ${dr(e.map(s=>Te(X({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield or(),$.info(`cameras: ${dr(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return tm&&s.getTracks().forEach(n=>{$.info(`${n.kind} capabilities: ${dr(n.getCapabilities(),{keysToInclude:yc})}`)}),t.audio&&zs(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=Be({key:$e.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=Be({key:$e.MICROPHONE_NOT_FOUND}))),new ue({code:q.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},pT=Xi({retryFunction:mT,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,(!It||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&&Mf(r[0].microphoneId,!1),r[0].cameraId&&Mf(r[0].cameraId,!0)},onRetrying:i=>{$.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{je.logFailedEvent({eventType:ri.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{je.logSuccessEvent({eventType:ri.GET_USER_MEDIA_RETRY}),je.uploadEvent({log:`stat-${ri.GET_USER_MEDIA_RETRY}-success-${i}`})}});function Mf(i,t){return y(this,null,function*(){let r=(t?yield or():yield Qt()).find(o=>o.deviceId===i);r&&We(r.getCapabilities)&&$.warn(dr(r.getCapabilities(),{keysToInclude:yc}))})}function hT(i){return{audio:fT(i),video:gT(i)}}function fT(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!ya(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(ke(i.channelCount)&&(t.channelCount=i.channelCount),st(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),st(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),st(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),ya(t)?!0:t)}function gT(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&&!ya(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&&br&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),ya(e)?!0:e)}var Of=pT;function ro(i){return xe((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function xf(i){return xe((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function xe(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Pf=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&$.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{$.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var ET=0,bd=class{constructor(){u(this,"log",$.createLogger({id:`fq${++ET}`}));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=X({},t),o=new Promise((c,l)=>{r.resolve=c,r.reject=l});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()})}},kf=new WeakMap,Lf=new WeakMap;function Rd(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=kf.get(this)||new bd;return kf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function vd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let c=Lf.get(this)||new Map,l=c.get(s(n))||new bd;return c.set(s(n),l),Lf.set(this,c),l.push({fn:o,args:n,context:this})},r}}function Cd(i,t){return xe((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),c=Ie();return Ji(n)?n.then(l=>(t?Q.addSuccessEvent({key:s,cost:Ie()-c}):Q.addSuccessEvent({key:s}),l)).catch(l=>{throw Q.addFailedEvent({key:s,error:l}),l}):(Q.addSuccessEvent({key:s}),n)}catch(n){throw Q.addFailedEvent({key:s,error:n}),n}})}var Qo=class Qo extends Xo{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){Vt(e,e).add(D.MUTE,this.onTrackMuted).add(D.UNMUTE,this.onTrackUnmuted).add(D.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===D.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ht(e)}setStateToReady(){}capture(e){return y(this,null,function*(){var r;try{let o=Ie();V.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 Of(e));let n=s.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),V.emit(U.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ie()-o}),s}catch(o){throw V.emit(U.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),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),V.emit(U.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.mediaTrack&&js){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield wf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),Td().then(n=>{let c=n.find(l=>l.deviceId===e);c&&this.emit("2",c)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===D.AUDIO&&!Df(this.mediaTrack)||this.kind===D.VIDEO&&!Nf(this.mediaTrack)||this._isRecapturing||e&&br&&It)}onTrackMuted(){if(super.onTrackMuted(),Pf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Rs){setTimeout(()=>this.onTrackMuted(),Rs);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((lt||mt)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return y(this,null,function*(){if(Bt(Qo.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Rs){setTimeout(()=>this.onTrackEnded(),Rs);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return y(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 Qt():yield or()).find(c=>c.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}),V.emit(U.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),V.emit(U.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof Nr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(Aa.get(r)||0)+1;if(Aa.set(r,o),o>=3){let s=e?(yield or()).find(n=>!Aa.has(n.deviceId)):(yield Qt()).find(n=>!Aa.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}stopCapture(){var e;this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};Z([Qe(de.INIT,"ready",{ignoreError:!0,sync:!0})],Qo.prototype,"setStateToReady",1),Z([Rd()],Qo.prototype,"capture",1),Z([Qe("ready","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),V.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,c;if(!((((c=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:c.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let l=this.kind===D.AUDIO,m=this.stat.bytesSent>0;Q[m?"addSuccessEvent":"addFailedEvent"]({key:l?503700:513702}),m||(Q.addEnum({key:l?503701:513703,value:Zn()}),je.uploadEvent({log:`stat-encode-failed-${this.kind}-${Yn()||Bo()}`,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})}}),Cd(521714,!1)],Qo.prototype,"publish",1),Z([xe(e=>function(){return y(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)})}),Qe([],"ready",{sync:!0})],Qo.prototype,"unpublish",1);var Ii=Qo,Aa=new Map;V.on(U.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&Aa.delete(i.track.deviceId)});var qr=class i extends Ii{constructor(e){super(1,yd);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 ft);u(this,"_output",new ft);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});u(this,"mixedAudioReferenceMap",new Map);this.manager=e,this.pipeline=new Xs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return _d.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 y(this,null,function*(){let r=this.trackSettings||{};Q.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),Q.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),Q.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 y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===xo){if(yield _m(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}),V.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(){St&&!St.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&St.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),nt(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Qt();r[0]?this.recapture(r[0].deviceId):St.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return y(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let c=n.getConstraints(),l=!1;!P(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,c.echoCancellation=e,l=!0),!P(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,c.noiseSuppression=r,l=!0),!P(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,c.autoGainControl=o,l=!0),l&&(Ht||It?yield n.applyConstraints(c).catch(m=>this._log.warn("update3A failed: ",m)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&Q.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),lt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(ze().createGain()),this._output.setNode(ze().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(It||lt))return this.update3A({echoCancellation:e})}addDenoiser(e){var r;if($r<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}Q.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,r){if(this.mixedAudioReferenceMap.has(r))return;this.log.info(`mixAudioReference() => ${r}`);let o=Ia(e),s=new ft,n=ze().createGain();n.gain.value=1;let c=new ft;s.pipeTo(c).pipeTo(this.pipeline.mixNode),s.setNode(o),c.setNode(n),this.mixedAudioReferenceMap.set(r,[s,c])}unMixAudioReference(e){let[r,o]=this.mixedAudioReferenceMap.get(e)||[];r&&(this.log.info(`unMixAudioReference() => ${e}`),r.deleteNode(),o==null||o.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,r){let[o,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=r/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,r,o,s){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(r),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,r,o,s){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach(([e,r])=>{e.deleteNode(),r.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),St.off("audioInputAdded",this.handleMicrophoneAdded,this),St.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Bt(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Qt()).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 Yo=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 c=this.dataView.getInt8(n);switch(c){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),c==0?o++:o=0,r.push(c);break;default:o=0,r.push(c);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 Nd=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 c=0;c<r;c++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Yo(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)),c=n.reduce((_,v)=>_+v.dataView.byteLength,0),l=new ArrayBuffer(c+t.data.byteLength),m=new DataView(l),f=new DataView(t.data),E=0;for(let _=0;_<n.length;_++)for(let v=0;v<n[_].dataView.byteLength;v++)m.setInt8(E++,n[_].dataView.getInt8(v));for(let _=0;_<t.data.byteLength;_++)m.setInt8(E++,f.getInt8(_));return t.data=l,n.length}return 0}};var Zo=class Zo extends Ii{constructor(e,r=4){super(r,rr);u(this,"profile",X({},Nn));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 Nd);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(Te(X({},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(!(!js||!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 y(this,null,function*(){var r,o,s;if(Oe(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(Zo.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Bt(Zo.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=this.fallbackProfile(e);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(Te(X({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var c;if(!this.mediaTrack)return;let{width:e=0,height:r=0}=(this.sourceTrack||this.mediaTrack).getSettings(),o=e*r,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(Jt===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(c=this.sourceTrack||this.mediaTrack)==null?void 0:c.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:l=0,height:m=0}=(this.sourceTrack||this.mediaTrack).getSettings(),f=l*m;if(n&&f&&o&&f===o){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:D.VIDEO,videoType:D.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},r=this.sourceTrack||this.mediaTrack;return js&&r&&Object.assign(e,r.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Nc(this.settings,this.profile)}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 y(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),V.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}})}updateSmallConfig(e){var o,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let r=!this.small;this.small=this.fallbackProfile(e,!0),(o=this.manager)==null||o.update(),r&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,r=!1){let o=e.width>e.height,s=X({},e);return e.width*e.height<=160*120&&mt&&ci&&(this.log.warn(`${r?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=o?240:180,s.height=o?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Rl&&(s.width=o?1280:720,s.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),yl(Rr,"14.3")&&Al(Rr,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!r&&this.avoidCropping&&(ci||Ht)&&!Cl()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,r;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(r=this.room)==null||r.enableSmall(!1))}listenDeviceChange(){St&&!St.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&St.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),nt(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield or();r[0]?this.recapture(r[0].deviceId):St.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(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 P(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){St.off("videoInputAdded",this.handleCameraAdded,this),St.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Bt(Zo.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield or()).find(s=>s.deviceId!==e);if(o)yield Bt(Zo.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))}setRotation(e){this.manager&&(this.isScreen||P(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};Z([ro(function(e){this.setContentHint(e.contentHint||"motion")})],Zo.prototype,"capture",1);var Nr=Zo;var Dd=ea();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Dd,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var IT=function(i){return y(this,null,function*(){let t=null,e=AT(i);$.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Fs&&$r<74||It||Ht)&&$.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){$.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield ST(o,i.captureElement))}if(i.audio){let s=yT(i);$.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function ST(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&We(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===Dd))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){$.warn(`cropTo target failed ${r}`)}})}function yT(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return P(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function AT(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:It?{max:i.width}:{ideal:i.width,max:i.width},height:It?{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 Ff=IT;var io=class extends Nr{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}`}get isShareCurrentTab(){var e,r;try{return Dd===((r=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:r.handle)}catch(o){return}}capture(f){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:c,captureElement:l,preferDisplaySurface:m}){try{let E;return c||n?(E=new MediaStream,c&&E.addTrack(c),n&&E.addTrack(n)):E=yield Ff({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:l,preferDisplaySurface:m}),yield this.setInputMediaStreamTrack(E.getVideoTracks()[0]),E}catch(E){throw this.log.error(`getDisplayMedia error observed ${E}`),E instanceof ue?E:new ue({code:q.INITIALIZE_FAILED,name:E.name,message:E.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};Z([ro(function(e){this.setContentHint(e.contentHint||"detail")})],io.prototype,"capture",1);var Ko=class extends qr{constructor(t){super(t),this._log.id=`s-${this._log.id}`}addAudioProcessor(t,e,r,o){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(o),this.enableTrackAEC(!1)}removeAudioProcessor(t,e,r,o){this.pipeline.aec.node===o&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var bT='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}});',Sm;function ba(i,t=48e3,e=1,r){return y(this,null,function*(){let o=ze("dump");Sm||(Sm=Ti(o,URL.createObjectURL(new Blob([bT],{type:"application/javascript"})))),yield Sm;let s=o.sampleRate,n=new AudioWorkletNode(o,"dumper",{numberOfInputs:i.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:t}});return n.channelCountMode="explicit",n.channelCount=e,r&&n.port.postMessage({port:r},[r]),i.forEach((c,l)=>c.connect(n,0,l)),new ReadableStream({start(c){n.port.onmessage=l=>{c.enqueue(l.data)}},cancel(){i.forEach(c=>c.disconnect(n)),n.port.close()}})})}var wd=class extends fd{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",$.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"audioProcessor");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);u(this,"getPCMAbortCtrlMap",new Map);u(this,"audioFrameEventConfigMap",new Map);u(this,"audioReferenceMap",new Map);u(this,"isLocalAudioNeedAudioProcess",!1);u(this,"isScreenAudioNeedAudioProcess",!1);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}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var f,E;if(!this._localAudioTrack)return;let r=[],o=[];(f=this._localAudioPipline)!=null&&f.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(E=this._localAudioPipline)!=null&&E.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=[],c=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),l=()=>{for(let _=0;_<o.length;_++){let v=URL.createObjectURL(new Blob(n[_])),k=document.createElement("a");k.href=v,k.download=`${o[_]}.pcm`,k.style.display="none",document.body.appendChild(k),k.click(),URL.revokeObjectURL(v),k.remove()}clearTimeout(c),s.abort("download")},m=ba(r).then(_=>_.pipeTo(new WritableStream({write(v){v.forEach((k,M)=>n[M]=n[M]?n[M].concat(k[0]):[k[0]])}}),s).catch(v=>l));return{then:m.then.bind(m),download:l}}getPCM(e,r){var B,ee,me;if(P(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:o,sampleRate:s=48e3,channelCount:n=1,port:c}=(r===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(r)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info(`getPCM ${r||"local"}`);let l=Math.floor(s*.04),m=new Float32Array(l),f=new Float32Array(l),E,_,v=0,k=new AbortController,M=r===""?(B=this._localAudioTrack)==null?void 0:B.mediaTrack:(me=(ee=this.room)==null?void 0:ee.remotePublishedUserMap.get(r))==null?void 0:me.remoteAudioTrack.mediaTrack;if(!M){this.log.info(`getPCM failed: ${r||"local"} has no audio track`);return}let N=ze().createMediaStreamSource(new MediaStream([M]));return ba([N],s,n,c).then(oe=>oe.pipeTo(new WritableStream({write(Xe){Xe[0][0]&&(v+Xe[0][0].length>l?(m.set(Xe[0][0].subarray(0,l-v),v),E=Xe[0][0].subarray(l-v),Xe[0][1]&&(f.set(Xe[0][1].subarray(0,l-v),v),_=Xe[0][1].subarray(l-v)),v+=l-v):(E&&(m.set(E,v),v+=E.length,E=void 0),_&&(f.set(_,v),_=void 0),m.set(Xe[0][0],v),Xe[0][1]&&f.set(Xe[0][1],v),v+=Xe[0][0].length),v>=l&&(v=0,e({userId:r,sampleRate:s,channelCount:n,data:n===1?m:[m,f]}),m=new Float32Array(l),f=new Float32Array(l)))}}),k).catch(Xe=>this.log.warn(`stop getPCM reason:${Xe}`))),k}get hasScreenAudioTrack(){return!P(this._localScreenAudioTrack)}get hasAudioTrack(){return!P(this._localAudioTrack)}changeInput(e){if(e instanceof Ko)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((r,o)=>{e.mixAudioReference(r,o)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof qr)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((r,o)=>{e.mixAudioReference(r,o)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Si)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,r){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(e,r)}unMixAudioReference(e){var r;(r=this._localAudioTrack)==null||r.unMixAudioReference(e)}setAudioReferenceVolume(e,r){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(e,r)}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 Ko?delete this._localScreenAudioTrack:e instanceof qr?delete this._localAudioTrack:e instanceof Si}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}addAudioProcessor(e,r,o,s){var n;this.audioProcessor=[e,r,o,s],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((c,l)=>{var m;(m=this._localAudioTrack)==null||m.mixAudioReference(c,l)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((c,l)=>{var m;(m=this._localScreenAudioTrack)==null||m.mixAudioReference(c,l)}))}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()}removeAudioProcessor(e,r,o,s){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,r,o,s)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type: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 c;(c=this.room)==null||c.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(c=>{var l;(l=this.room)==null||l.emit("audio-frame",c)},""),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(){V.on("113",this.handleLocalTrackStarted,this),V.on("114",this.handleLocalTrackStopped,this),V.on("115",this.handleRemoteTrackStarted,this),V.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){V.off("113",this.handleLocalTrackStarted),V.off("114",this.handleLocalTrackStopped),V.off("115",this.handleRemoteTrackStarted),V.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:r,refId:o,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(o)||!r||(this.audioReferenceMap.set(o,r),!this.audioProcessor))return;this.mixAudioReference(r,o)}else if(e==="remove")this.audioReferenceMap.get(o)&&(this.audioReferenceMap.delete(o),this.unMixAudioReference(o));else if(e==="updateVolume"){if(!this.audioProcessor||P(s))return;this.setAudioReferenceVolume(o,s)}}};function $f(i=30,t=2){return xe((e,r)=>function(...o){return new Promise((s,n)=>{let c=setTimeout(()=>{let l=new ue({code:q.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});$.warn(l),t===2?n(l):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(c)})})})}var np={};ei(np,{Events:()=>dt,Inspect:()=>lr,LastSink:()=>es,Sink:()=>fe,Subscribe:()=>ts,TimeoutError:()=>Ra,audit:()=>sI,bindCallback:()=>GT,bindNodeCallback:()=>jT,buffer:()=>xT,bufferCount:()=>OT,bufferTime:()=>bI,call:()=>Bf,catchError:()=>rp,combineLatest:()=>Wf,concat:()=>CT,concatMap:()=>gI,concatMapTo:()=>EI,count:()=>zT,create:()=>Pe,debounce:()=>nI,debounceTime:()=>aI,defer:()=>Gf,delay:()=>RI,deliver:()=>_e,dispose:()=>Md,elementAt:()=>cI,empty:()=>Na,every:()=>pI,exhaustMap:()=>II,exhaustMapTo:()=>SI,filter:()=>sr,find:()=>dI,findIndex:()=>uI,first:()=>lI,fromAnimationFrame:()=>HT,fromArray:()=>LT,fromEvent:()=>Ne,fromEventPattern:()=>UT,fromFetch:()=>VT,fromIterable:()=>FT,fromPromise:()=>Jf,fromReadableStream:()=>BT,fromReader:()=>$T,groupBy:()=>yI,identity:()=>RT,ignoreElements:()=>ZT,iif:()=>DT,inspect:()=>Hf,interval:()=>Nm,last:()=>mI,map:()=>so,mapTo:()=>fI,max:()=>XT,merge:()=>vm,mergeMap:()=>_I,mergeMapTo:()=>TI,min:()=>QT,never:()=>qT,nothing:()=>He,of:()=>kT,pairwise:()=>hI,pipe:()=>be,race:()=>Cm,range:()=>WT,reduce:()=>Dm,retry:()=>NI,scan:()=>tp,share:()=>yi,shareReplay:()=>NT,skip:()=>eI,skipUntil:()=>tI,skipWhile:()=>Ld,startWith:()=>va,subject:()=>yt,subscribe:()=>Le,sum:()=>YT,switchMap:()=>no,switchMapTo:()=>Ai,take:()=>Dr,takeLast:()=>KT,takeUntil:()=>Ye,takeWhile:()=>zf,tap:()=>Da,throttle:()=>iI,throwError:()=>JT,timeInterval:()=>AI,timeout:()=>sp,timer:()=>Ca,toPromise:()=>vI,toReadableStream:()=>CI,withLatestFrom:()=>MT,zip:()=>wT});function He(...i){}var Bf=i=>i(),RT=i=>i;function Md(){this.dispose()}var Hf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",vT=1,lr=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new ym(t,this,this.streamId++);return dt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},es=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=He,this.error=He,this.next=He,this.dispose=He,this.subscribe=He,this.doDefer()}subscribe(t){return t instanceof lr?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Bf),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}},fe=class extends es{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)}},ts=class extends es{constructor(t,e=He,r=He,o=He){if(super(),this._next=e,this._error=r,this._complete=o,this.then=He,t instanceof lr){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{dt.defer(s,0)}),dt.create(s),dt.pipe(s),this.sourceId=s.id,this.subscribe(t),dt.subscribe({id:s.id,end:!0}),e==He?this._next=n=>dt.next(s,0,n):this.next=n=>{dt.next(s,0,n),e(n)},o==He?this._complete=()=>dt.complete(s,0):this.complete=()=>{this.dispose(),dt.complete(s,0),o()},r==He?this._error=n=>dt.complete(s,0,n):this.error=n=>{this.dispose(),dt.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 be(i,...t){return t.reduce((e,r)=>r(e),i)}function Pe(i,t,e){if(Hf()){let r=Object.defineProperties(Object.setPrototypeOf(i,lr.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}});dt.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof lr&&dt.addSource(r,s)}return r}return i}function _e(i,t){return function(...e){return r=>{if(r instanceof lr){let o=Pe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,dt.pipe(o),o}else return o=>r(new i(o,...e))}}}function oo(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var ym=class extends fe{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{dt.defer(this.source,this.id)})}next(t){dt.next(this.source,this.id,t),this.sink.next(t)}complete(){dt.complete(this.source,this.id),this.sink.complete()}error(t){dt.complete(this.source,this.id,t),this.sink.error(t)}},dt={addSource(i,t){oo("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){oo("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){oo("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){oo("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){oo("defer",{id:i.id,streamId:t})},pipe(i){oo("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){oo("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=vT++),oo("create",{name:i.toString(),id:i.id})}},Ra=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var Od=class extends es{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 yi(){return i=>{let t=new Od(i);if(i instanceof lr){let e=Pe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,dt.pipe(e),e}return Pe(t.add.bind(t),"share",arguments)}}function vm(...i){return Pe(t=>{let e=new fe(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function Cm(...i){return Pe(t=>{let e=new Map;i.forEach(r=>{let o=new fe(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 CT(...i){return Pe(t=>{let e=0,r=i.length,o=new fe(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 Od(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Pe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function DT(i,t,e){return Pe(r=>i()?t(r):e(r),"iif",arguments)}function Wf(...i){return Pe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},c=(l,m)=>{let f=new fe(t);f.next=E=>{--r===0?(f.next=_=>{s[m]=_,t.next(s)},f.next(E)):s[m]=E},f.complete=n,f.subscribe(l)};i.forEach(c)},"combineLatest",arguments)}function wT(...i){return Pe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(c,l)=>{let m=new fe(t),f=[];o[l]=f,m.next=E=>{f.push(E),o.every(_=>_.length)&&t.next(o.map(_=>_.shift()))},m.complete=s,m.subscribe(c)};i.forEach(n)},"zip",arguments)}function va(...i){return t=>Pe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var Am=class extends fe{constructor(t,...e){super(t);let r=new fe(this.sink);r.next=o=>this.buffer=o,r.complete=He,r.subscribe(Wf(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},MT=_e(Am,"withLatestFrom"),bm=class extends fe{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()}},OT=_e(bm,"bufferCount"),Rm=class extends fe{constructor(t,e){super(t),this.buffer=[];let r=new fe(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=He,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},xT=_e(Rm,"buffer");var PT=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 c(f){try{m(r.next(f))}catch(E){n(E)}}function l(f){try{m(r.throw(f))}catch(E){n(E)}}function m(f){f.done?s(f.value):o(f.value).then(c,l)}m((r=r.apply(i,t||[])).next())})};function yt(i){let t=arguments,e=yi()(Pe(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=He,e.complete=He,e.error=He,e}function Gf(i){return Pe(t=>t.subscribe(i()),"defer",arguments)}var jf=i=>t=>{setTimeout(()=>i(t))},qf=i=>jf(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function kT(...i){return Pe(qf(i),"of",arguments)}function LT(i){return Pe(qf(i),"fromArray",arguments)}function Nm(i){return Pe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function Ca(i,t){return Pe(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 xd(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function UT(i,t){return Pe(xd(i,t),"fromEventPattern",arguments)}function Ne(i,t){if("on"in i&&"off"in i)return Pe(xd(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Pe(xd(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Pe(xd(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Jf(i){return Pe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function VT(i,t){return Pe(Gf(()=>Jf(fetch(i,t))),"fromFetch",arguments)}function FT(i){return Pe(jf(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=>PT(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 Pe(e=>{t(e)},"fromReader",arguments)}function BT(i){return Pe(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 HT(){return Pe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function WT(i,t){return Pe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function GT(i,t,...e){return Pe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function jT(i,t,...e){return Pe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function qT(){return Pe(()=>{},"never",arguments)}function JT(i){return Pe(t=>t.error(i),"throwError",arguments)}function Na(){return Pe(i=>i.complete(),"empty",arguments)}var rs=class extends fe{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)}},Dm=_e(rs,"reduce"),zT=i=>_e(rs,"count")((t,e)=>i(e)?t+1:t,0),XT=()=>_e(rs,"max")(Math.max),QT=()=>_e(rs,"min")(Math.min),YT=()=>_e(rs,"sum")((i,t)=>i+t,0);var wm=class extends fe{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},sr=_e(wm,"filter"),Mm=class extends fe{next(t){}},ZT=_e(Mm,"ignoreElements"),Om=class extends fe{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Dr=_e(Om,"take"),xm=class extends fe{constructor(t,e){super(t);let r=new fe(t);r.next=()=>t.complete(),r.complete=Md,r.subscribe(e)}},Ye=_e(xm,"takeUntil"),Pm=class extends fe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},zf=_e(Pm,"takeWhile"),KT=i=>Dm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),km=class extends fe{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},eI=_e(km,"skip"),Lm=class extends fe{constructor(t,e){super(t),t.next=He;let r=new fe(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Md,r.subscribe(e)}},tI=_e(Lm,"skipUntil"),Um=class extends fe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},Ld=_e(Um,"skipWhile"),rI={leading:!0,trailing:!1},Vm=class extends fe{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)}},Pd=class extends fe{constructor(t,e,r=rI){super(t),this.durationSelector=e,this.config=r,this._throttle=new Vm(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=He,this._throttle.complete(),super.complete()}},iI=_e(Pd,"throttle"),oI={leading:!1,trailing:!0},sI=i=>_e(Pd,"audit")(i,oI),Fm=class extends fe{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},kd=class extends fe{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Fm(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()}},nI=_e(kd,"debounce"),aI=i=>_e(kd,"debounceTime")(t=>Ca(i)),$m=class extends fe{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()}},cI=_e($m,"elementAt"),dI=i=>t=>Dr(1)(Ld(e=>!i(e))(t)),Bm=class extends fe{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}},uI=_e(Bm,"findIndex"),Hm=class extends fe{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()}},lI=_e(Hm,"first"),Wm=class extends fe{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()}},mI=_e(Wm,"last"),Gm=class extends fe{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()}},pI=_e(Gm,"every");var jm=class extends fe{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))}},tp=_e(jm,"scan"),qm=class extends fe{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},hI=_e(qm,"pairwise"),Ud=class extends fe{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},so=_e(Ud,"map"),fI=i=>_e(Ud,"mapTo")(t=>i),Ys=class extends fe{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()}},Zs=class extends fe{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()}},Vd=class extends Ys{},Fd=class extends Zs{next(t){this.subInner(t,Vd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Vd)}}},no=_e(Fd,"switchMap");function Wd(i){return(t,e)=>i(()=>t,e)}var Ai=Wd(_e(Fd,"switchMapTo")),Jm=class extends Ys{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},$d=class extends Zs{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(),Jm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},gI=_e($d,"concatMap"),EI=Wd(_e($d,"concatMapTo")),zm=class extends Ys{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Bd=class extends Zs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,zm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},_I=_e(Bd,"mergeMap"),TI=Wd(_e(Bd,"mergeMapTo")),Xm=class extends Ys{dispose(){this.context.resetNext(),super.dispose()}},Hd=class extends Zs{next(t){this.next=He,this.subInner(t,Xm)}},II=_e(Hd,"exhaustMap"),SI=Wd(_e(Hd,"exhaustMapTo")),Qm=class extends fe{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=yt(),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)}},yI=_e(Qm,"groupBy"),Ym=class extends fe{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}},AI=_e(Ym,"timeInterval"),Zm=class extends fe{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()}},bI=_e(Zm,"bufferTime"),Km=class extends fe{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)}},RI=_e(Km,"delay"),ep=class extends fe{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},rp=_e(ep,"catchError");var vI=()=>i=>new Promise((t,e)=>{let r;new ts(i,o=>r=o,e,()=>t(r))}),CI=()=>i=>{let t;return new ReadableStream({start(e){t=new ts(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},Le=(i=He,t=He,e=He)=>r=>new ts(r,i,t,e),ip=class extends fe{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)}))}},Da=_e(ip,"tap"),op=class extends fe{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ra(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},sp=_e(op,"timeout"),NI=(i=1/0)=>t=>{if(t instanceof lr){let e=Pe(r=>{let o=i,s=new fe(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,dt.pipe(e),e}else return e=>{let r=i,o=new fe(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Jr=class Jr extends Xo{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",yt(Ne(this,Jr.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new de(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new de(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),be(vm(Ne(this,de.STATECHANGED),Ne(this.remotePublishState,de.STATECHANGED)),so(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Le(l=>{this.availableState.state!==(l?de.ON:de.OFF)&&(this.availableState.state=l?de.ON:de.OFF),this.updatePlayingState(l)}));let s=be(Ne(this.player,et.ERROR),sr(l=>l.code===MediaError.MEDIA_ERR_DECODE)),n=be(Ca(5e3),sr(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===D.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),c=be(Cm(s,n),Ye(Ne(this,de.INIT)));be(this._triggerCheckDecodeSubject,sr(()=>!this.ignoreDecodeError),Ai(c),Le(l=>{this.reportDecodeResult(!1,l)}))}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===Jr.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===de.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===D.AUDIO;Q[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(Q.addEnum({key:o?504701:514703,value:Zn()}),je.uploadEvent({log:`stat-decode-failed-${this.kind}-${Yn()||Bo()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===D.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?de.ON:de.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(Jr,"STATE_SUBSCRIBE","subscribe"),Z([$f(5,1)],Jr.prototype,"waitHasMediaTrack",1),Z([Qe(de.INIT,Jr.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),V.emit(U.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Cd(521716,!1)],Jr.prototype,"subscribe",1),Z([Qe(Jr.STATE_SUBSCRIBE,de.INIT,{sync:!0,success(){this.log.info("unsubscribed"),V.emit(U.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Jr.prototype,"unsubscribe",1);var Ks=Jr;var Si=class extends Ks{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 _d.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 wI=[-1,-1,1,-1,-1,1,1,1],MI=[0,0,1,0,0,1,1,1];var Gt=class extends de{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 Ft){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&Jt!==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(MI),this.positionBuffer=this.createBuffer(wI),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 ue({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 Tt&&this.render(e)||this.context instanceof Ft&&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 Tt){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()),this.emit("render"),!0):!1}getInfo(){var E;let{totalFrames:e,x:r,y:o,width:s,height:n,name:c,cost:l}=this,m=Date.now(),f=(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:f,name:c,cost:l},X({parent:(E=this.input)==null?void 0:E.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}};Z([Qe(de.INIT,"connected",{sync:!0})],Gt.prototype,"connect",1),Z([Qe("connected",de.INIT,{ignoreError:!0,sync:!0})],Gt.prototype,"disconnect",1),Z([Qe([],"closed",{sync:!0})],Gt.prototype,"close",1);var Qf=be(Nm(250),so(()=>performance.now()),yi()),Yf=i=>t=>{let e=0,r=performance.now();be(Qf,so(o=>(o-r)/i>>0),sr(o=>o!=e?(e=o,!0):!1))(t)},Gd=i=>t=>{let e=performance.now();be(Qf,Ld(r=>r-e<i),Dr(1))(t)};var xI=[0,1,1,1,0,0,1,0],is=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 Ft?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(xI)}start(e){this.log.info(`${this.name} start render ${e} fps`),vt.clearTask(this._intervalId),this._intervalId=vt.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(vt.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Tt){let o=this.context.ctx.getError();o&&this.context.destroy(new ue({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(),this.emit("render"),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(vt.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),vt.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),vt.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},en=class extends is{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",Ne(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(di)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Ne(this._videoTrack,"mute"),be(Ne(this._videoTrack,"ended"),Ye(this._closedOb),Le(()=>{this.context.destroy(new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=be(this._muteOb,Ye(this._closedOb),Ai(Gd(5e3)),sr(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Le(()=>{this.context.destroy(new ue({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()}},jd=class extends en{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var qd=class extends en{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 wa=class extends Gt{constructor(e,r){super(e,X({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);u(this,"shouldUpdate",!0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,Jt===16&&(this._canvasRendered=yt(),be(this._canvasRendered,va(this._image),no(o=>o instanceof HTMLCanvasElement?Ne(o,"rendered"):Na()),Ye(Ne(this,"closed")),Le(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Ei()&&!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 c;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,(c=this._lastImage)==null||c.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let l=this.context.ctx;l.texSubImage2D(l.TEXTURE_2D,0,0,0,l.RGBA,l.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let l=this.context.ctx;l.texImage2D(l.TEXTURE_2D,0,l.RGBA,l.RGBA,l.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)}},Ma=class extends wa{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",be(Ne(this._player,et.PLAYER_STATE_CHANGED),Ye(Ne(this,"closed")),sr(({state:s})=>s==="PLAYING"),Le(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},bi=class extends Ma{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,e,r){super(t,new rr({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 kI=`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=wl,r.innerText=`${Ut()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ba}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){Pl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Fo}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",y.info("show autoplay dialog"),se.uploadEvent({log:Ug}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){y.warn("confirm clicked, try resume stream"),S.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Fm}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:Vg}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Wm,"_blank"),this._isQuestionClicked||se.uploadEvent({log:Bg}),this._isQuestionClicked=!0}},Jm=xl;var ot=class extends gi{constructor(e){super(e,p.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,E(e.viewMirror)||(this.viewMirror=e.viewMirror),E(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(p.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(p.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(p.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r,s;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===p.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.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=yr,this._log.info(`view container ${(s=this.container)==null?void 0:s.id} is recreated`)),this._pausedRetryCount>0&&!Pl()&&(this._log.info(`[${yr-this._pausedRetryCount+1}/${yr}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let n=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} scaleX(-1)`)}}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){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(he.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(Hr()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function ji(o,i){return f(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),y.info("worklet addModule success")}catch(e){throw y.info(`worklet addModule catch error. ${e.message}`),e}})}var sn;typeof AudioContext!="undefined"?sn=AudioContext:typeof webkitAudioContext!="undefined"?sn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(sn=mozAudioContext);var Xt,qm=-1;jm();function jm(){try{if(Xt)return;Xt=new sn({sampleRate:48e3}),Xt.onstatechange=()=>{y.info(`context state: ${Xt.state}${Xt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Ho()},clearTimeout(qm)}catch(o){y.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof sn}`),qm=setTimeout(jm,1e3)}}var Ho=()=>{Xt.state==="suspended"?($o(),document.addEventListener("click",Ho)):Xt.state==="interrupted"?$o():(document.removeEventListener("visibilitychange",Ho),document.removeEventListener("click",Ho))},Ul=0,Vl=-1;function $o(){return new Promise((o,i)=>{if(Xt.state==="running")return o();Date.now()-Ul<1e3?(clearTimeout(Vl),Vl=setTimeout(()=>{Ul=Date.now(),Xt.resume().then(o,i)},1e3)):(clearTimeout(Vl),Ul=Date.now(),Xt.resume().then(o,i))}).catch(o=>{y.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",Ho)})}document.addEventListener("click",Ho);var Ee=o=>Xt;var De=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){y.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){y.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){y.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=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},Ha=class extends De{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},nn=class{constructor(){d(this,"source",new De);d(this,"gain",new De);d(this,"destination",new De)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(an(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}},Go=class extends nn{constructor(e){super();this.context=e;d(this,"aec",new De("aec"));d(this,"mixNode",new De("mixNode"));d(this,"silentNode",new De("silentNode"));d(this,"denoiser",new De("denoiser"));d(this,"voiceChanger",new De("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},$a=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Xm=new WeakMap;function an(o){let i=Xm.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return Xm.set(o,i),i}var It=class It{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-It.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!It.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);';It.workletReady=ji(It.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return It.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(It.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{It.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:ct.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{It.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(It,"lastMessageTime",0),d(It,"audioContext",Ee("volume-meter")),d(It,"workletReady");var Ga=It,cn=class extends De{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new Ga(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},$r=Ga;var Zm=Ge(tt(),1);var Qm=o=>i=>i.deviceId===o;var dn=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Jo(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Qm(r.deviceId))){let s=`${this.kind}${this.type}Added`;y.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Qm(r.deviceId))){let s=`${this.kind}${this.type}Removed`;y.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Bl=class extends Zm.EventEmitter{constructor(){super();d(this,"audioInputs",new dn(p.AUDIO));d(this,"videoInputs",new dn(p.VIDEO));d(this,"audioOutputs",new dn(p.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(){Wo().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield Wo(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Pe=_s||no?null:new Bl;function Jo(o){return o.deviceId===o.groupId&&o.groupId===""}function Wo(){return f(this,arguments,function*(o=0){if(Wi()||!ka())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Jo(t)&&(t.kind===p.AUDIO_INPUT?e.audio=!0:t.kind===p.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&$o()}catch(r){y.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&&Fl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function mt(o=!1){return Pe.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return Pe.update(o?2:0).then(i=>i.videoInputs.devices)}var Ym=!1;function Km(){return f(this,null,function*(){try{Ym||(Ym=!0,y.info(`speakers:${(yield pr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function pr(o=!1){return f(this,null,function*(){return(Ie||xe)&&(o=!1),Pe.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Fl=new Set;function ep(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.VIDEO_INPUT}`;return!!Fl.has(t)}function tp(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${p.AUDIO_INPUT}`;return!!Fl.has(t)}function Hl(o,i){return f(this,null,function*(){let t=(yield mt()).find(r=>r.deviceId===br);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function ip(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===p.AUDIO&&o===br?yield Hl(e,t):!0})}var Wa,$l=class extends nn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new Ha);this.volumeMeter=new cn({log:this.log}),this.volumeMeterAfter3A=new cn({log:this.log}),this.volumeDestination=new De,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Ja=class o extends gi{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new $l(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((gt==="15.2"||gt==="15.3"||gt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Wa||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,q(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===Wa&&(Wa=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),Km(),We(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},qa=class extends Ja{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(he.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)}},ja=class extends Ja{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new De);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(he.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"):Ie||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),ve(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&&ci&&(Wa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Gr=class extends ${constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?ja:ot}){var a;super();d(this,"id",Hs());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=y.createLogger({id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof zt?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof zt}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(he.PLAYER_STATE_CHANGED,c=>{S.emit(C.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===p.VIDEO&&(this.player.on(he.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_DATA),S.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(he.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(he.LOADED_META_DATA)}),this.player.on(he.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(he.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||y}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get strMediaType(){return this.mediaType===4?p.VIDEO:this.mediaType===2?p.SCREEN:p.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Se(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!E(t.muted)&&this.setPlayerMute(t.muted),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ot&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Se(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!E(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===p.VIDEO)&&this.setPlayerMute(!0),t&&!E(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ot&&(this.player.setObjectFit(this.objectFit),t&&!E(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ot&&this.player.setContainer(r)),S.emit(C.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Se(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==p.VIDEO||E(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(de(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===p.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(E(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ot({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(xd(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?C.TRACK_MUTED:C.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){Qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(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(xd(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 Jm;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 ot?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===he.LOADED_META_DATA&&!r&&!s||(e===he.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,dt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};D([Te([],$.INIT,{sync:!0})],Gr.prototype,"close",1);var Hg=Object.prototype.hasOwnProperty,{toString:GR}=Object.prototype;function $g(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(ze(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Hg.call(o,i))return!1;return!0}}return!1}var Ti=$g;var Gg=function(o){return f(this,null,function*(){let i=Jg(o);y.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield mt(),y.info(`microphones: ${yt(e.map(s=>w(v({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),y.info(`cameras: ${yt(t,{keysToInclude:r})}`));try{let s=yield navigator.mediaDevices.getUserMedia(i);return Rl&&s.getTracks().forEach(n=>{y.info(`${n.kind} capabilities: ${yt(n.getCapabilities(),{keysToInclude:qn})}`)}),i.audio&&$o(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=P({key:L.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=P({key:L.MICROPHONE_NOT_FOUND}))),new b({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},Wg=ni({retryFunction:Gg,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!xe||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&rp(t[0].microphoneId,!1),t[0].cameraId&&rp(t[0].cameraId,!0)},onRetrying:o=>{y.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:ct.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:ct.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${ct.GET_USER_MEDIA_RETRY}-success-${o}`})}});function rp(o,i){return f(this,null,function*(){let t=(i?yield At():yield mt()).find(r=>r.deviceId===o);t&&ne(t.getCapabilities)&&y.warn(yt(t.getCapabilities(),{keysToInclude:qn}))})}function Jg(o){return{audio:qg(o),video:jg(o)}}function qg(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!Ti(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(q(o.channelCount)&&(i.channelCount=o.channelCount),de(o.echoCancellation)&&!o.echoCancellation&&(i.echoCancellation=!1),de(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),de(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),Ti(i)?!0:i)}function jg(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!Ti(e)?e:(o.width&&(e.width={ideal:o.width},i&&!ae&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!ae&&(e.height.max=o.height)),ae&&$t&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),Ti(e)?!0:e)}var op=Wg;function Xa(o){return Y((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function st(o){return Y((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function za(o){return Y((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Y(o){return function(i,e,t){return t.value=o(t.value,e),t}}var sp=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&y.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{y.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var Xg=0,Qa=class{constructor(){d(this,"log",y.createLogger({id:`fq${++Xg}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=v({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},ln=new WeakMap,Ya=new WeakMap;function Nt(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=ln.get(this)||new Qa;return ln.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function np(o){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=ln.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let u=!0;return c.args.forEach(h=>{s.find(m=>m===h)||(u=!1)}),u?(c.reject(new b({code:I.API_CALL_ABORTED,message:o})),!1):!0});n.queue=a}return r.apply(this,s)},t}}function Za(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=ln.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Ya.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:o}))}),ln.delete(this),Ya.delete(this),r.apply(this,s)},t}}function Xi(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Ya.get(this)||new Map,c=a.get(s(n))||new Qa;return a.set(s(n),c),Ya.set(this,a),c.push({fn:r,args:n,context:this})},t}}function pt(o,i){return Y((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=B();return lr(n)?n.then(c=>(i?N.addSuccessEvent({key:s,cost:B()-a}):N.addSuccessEvent({key:s}),c)).catch(c=>{throw N.addFailedEvent({key:s,error:c}),c}):(N.addSuccessEvent({key:s}),n)}catch(n){throw N.addFailedEvent({key:s,error:n}),n}})}var Wr=class Wr extends Gr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"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){Qe(e,e).add(p.MUTE,this.onTrackMuted).add(p.UNMUTE,this.onTrackUnmuted).add(p.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===p.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){ve(e)}setStateToReady(){}capture(e){return f(this,null,function*(){var t;try{let r=B();S.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),s=yield op(e));let n=s.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.sourceTrack=n,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:B()-r}),s}catch(r){throw S.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),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(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&mi){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield ip({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),Wo().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===p.AUDIO&&!tp(this.mediaTrack)||this.kind===p.VIDEO&&!ep(this.mediaTrack)||this._isRecapturing||e&&$t&&xe)}onTrackMuted(){if(super.onTrackMuted(),sp(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<lo){setTimeout(()=>this.onTrackMuted(),lo);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Ie||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(We(Wr.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<lo){setTimeout(()=>this.onTrackEnded(),lo);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let s;(this.kind==="audio"?yield mt():yield At()).find(a=>a.deviceId===e)&&(s=e),t.deviceId=s}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof Be;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(un.get(t)||0)+1;if(un.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!un.has(n.deviceId)):(yield mt()).find(n=>!un.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};D([Te($.INIT,"ready",{ignoreError:!0,sync:!0})],Wr.prototype,"setStateToReady",1),D([Nt()],Wr.prototype,"capture",1),D([Te("ready","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),S.emit(C.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,c,l,u,h;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let m=this.kind===p.AUDIO,_=this.stat.bytesSent>0;if(N[_?"addSuccessEvent":"addFailedEvent"]({key:m?503700:513702}),!m){let A=((l=(c=this.room)==null?void 0:c.videoCodec)==null?void 0:l.toUpperCase())||"H264";N[_?"addSuccessEvent":"addFailedEvent"]({key:Js[`ENCODE_${A}_RESULT`]})}_||(N.addEnum({key:m?503701:513703,value:Fs()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${Lr()||Hi()}`,userId:this.userId}),this.log.warn(m?"encode failed":`${(h=(u=this.room)==null?void 0:u.videoCodec)==null?void 0:h.toUpperCase()} encode failed`),this.emit("6",this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"started",reason:"error",error:new b({message:`${m?"audio":"video"} encode failed`,code:m?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED})}))}},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})}}),pt(521714,!1)],Wr.prototype,"publish",1),D([Y(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),Te([],"ready",{sync:!0})],Wr.prototype,"unpublish",1);var zt=Wr,un=new Map;S.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&un.delete(o.track.deviceId)});var Ct=class o extends zt{constructor(e){super(1,qa);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new De);d(this,"_output",new De);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);this.manager=e,this.pipeline=new Go(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return $r.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};N.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),N.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),N.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield We(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!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:r,retryWhenExactFailed:s,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===br){if(yield Hl(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(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){Pe&&!Pe.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Pe.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield mt();t[0]?this.recapture(t[0].deviceId):Pe.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!E(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!E(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!E(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(ae||xe?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),Ie&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(xe||Ie))return this.update3A({echoCancellation: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)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=an(e),s=new De,n=Ee().createGain();n.gain.value=1;let a=new De;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r,s){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}removeAudioProcessor(e,t,r,s){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Pe.off("audioInputAdded",this.handleMicrophoneAdded,this),Pe.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield We(o.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield mt()).find(s=>s.deviceId!==e);if(r)yield We(o.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 zi=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 s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}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 s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}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 s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let s=0;s<t.byteLength;s++,e++)r.setInt8(s,this.dataView.getInt8(e));return r}};var Ka=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new zi(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,_)=>m+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),h=0;for(let m=0;m<n.length;m++)for(let _=0;_<n[m].dataView.byteLength;_++)l.setInt8(h++,n[m].dataView.getInt8(_));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Jr=class Jr extends zt{constructor(e,t=4){super(t,ot);d(this,"profile",v({},nr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Ka);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(w(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(!(!mi||!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 f(this,null,function*(){var t,r,s;if(te(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,We(Jr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),We(Jr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,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:s})}setProfile(e){let t=this.fallbackProfile(e);t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(w(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return f(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(Je===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:p.VIDEO,videoType:p.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return mi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Eo(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=v({},e);return e.width*e.height<=160*120&&pe&&it&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Xd&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),Bs(gt,"14.3")&&qd(gt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&(it||ae)&&!Qd()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){Pe&&!Pe.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Pe.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),Ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield At();t[0]?this.recapture(t[0].deviceId):Pe.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return E(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){Pe.off("videoInputAdded",this.handleCameraAdded,this),Pe.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield We(Jr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield We(Jr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||E(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};D([st(function(e){this.setContentHint(e.contentHint||"motion")})],Jr.prototype,"capture",1);var Be=Jr;var Gl={};vi(Gl,{REPORT_TYPE:()=>So,buildSSOPackage:()=>Pi,bytes2ms:()=>Vh,calculateScaleResolutionDownNumber:()=>Eo,convertObjectNumberToInt:()=>Ns,copyProperties:()=>Uh,deepClone:()=>Nr,deepCloneBasic:()=>Qn,deepMerge:()=>oi,delay:()=>Li,fibonacci:()=>Dr,formatedTime:()=>jh,getConstructorName:()=>po,getContainerFromElement:()=>qh,getEnv:()=>Lh,getInternalVersion:()=>Wh,getLoggerUrl:()=>wi,getMediaStreamTrackInfo:()=>ta,getMuteStateFromFlag:()=>xi,getNetworkType:()=>vd,getNumNetworkType:()=>vr,getReconnectionTimeout:()=>Vt,getStringByteLength:()=>bs,getTurnServer:()=>Jh,getUint32Version:()=>Zn,getValueType:()=>Re,getViewListFromView:()=>go,glog:()=>Md,ipv4ToUint32:()=>_o,isArray:()=>Se,isAudioWorkletSupported:()=>$h,isBoolean:()=>de,isConstructor:()=>Or,isEmpty:()=>fo,isFunction:()=>ne,isLangChinese:()=>Ut,isMediaStreamTrack:()=>Fh,isNumber:()=>q,isObject:()=>ft,isOverseaSdkAppId:()=>ki,isPlainObject:()=>ze,isPortrait:()=>kd,isPromise:()=>lr,isRemoteTrack:()=>Hh,isRotate90Or270:()=>dt,isSetSinkIdSupported:()=>Gh,isString:()=>te,isUndefined:()=>E,loadImage:()=>To,loadVideo:()=>Xh,ms2bytes:()=>Bh,ms2samples:()=>Od,normalizeUrl:()=>ea,performanceNow:()=>B,promiseAny:()=>Mr,samples2ms:()=>Dd,setNetworkType:()=>Yn,stringify:()=>yt,stringifyIncludeValue:()=>ys,throttlePromise:()=>Kn});var Yg=[-1,-1,1,-1,-1,1,1,1],Zg=[0,0,1,0,0,1,1,1];var Ye=class extends ${constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Fe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&Je!==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(Zg),this.positionBuffer=this.createBuffer(Yg),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 ke&&this.render(e)||this.context instanceof Fe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof ke){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let h=!E(a)&&!E(c)&&!E(l)&&!E(u);return this.ctx2d&&e?(e instanceof ImageData?h?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var h;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},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}};D([Te($.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),D([Te("connected",$.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),D([Te([],"closed",{sync:!0})],Ye.prototype,"close",1);var Du={};vi(Du,{Events:()=>ye,Inspect:()=>vt,LastSink:()=>qr,Sink:()=>W,Subscribe:()=>jr,TimeoutError:()=>hn,audit:()=>wT,bindCallback:()=>TT,bindNodeCallback:()=>ET,buffer:()=>aT,bufferCount:()=>nT,bufferTime:()=>ZT,call:()=>cp,catchError:()=>yu,combineLatest:()=>lp,concat:()=>tT,concatMap:()=>WT,concatMapTo:()=>JT,count:()=>AT,create:()=>oe,debounce:()=>xT,debounceTime:()=>LT,defer:()=>up,delay:()=>KT,deliver:()=>j,dispose:()=>ec,elementAt:()=>PT,empty:()=>fn,every:()=>HT,exhaustMap:()=>XT,exhaustMapTo:()=>zT,filter:()=>Si,find:()=>UT,findIndex:()=>VT,first:()=>BT,fromAnimationFrame:()=>_T,fromArray:()=>lT,fromEvent:()=>me,fromEventPattern:()=>uT,fromFetch:()=>hT,fromIterable:()=>mT,fromPromise:()=>pp,fromReadableStream:()=>fT,fromReader:()=>pT,groupBy:()=>QT,identity:()=>Kg,ignoreElements:()=>bT,iif:()=>rT,inspect:()=>dp,interval:()=>Yl,last:()=>FT,map:()=>_n,mapTo:()=>GT,max:()=>CT,merge:()=>zl,mergeMap:()=>qT,mergeMapTo:()=>jT,min:()=>RT,never:()=>ST,nothing:()=>le,of:()=>dT,pairwise:()=>$T,pipe:()=>ue,race:()=>Ql,range:()=>gT,reduce:()=>Zl,retry:()=>rE,scan:()=>Ru,share:()=>Qi,shareReplay:()=>iT,skip:()=>vT,skipUntil:()=>DT,skipWhile:()=>sc,startWith:()=>mn,subject:()=>nt,subscribe:()=>be,sum:()=>yT,switchMap:()=>Xo,switchMapTo:()=>zr,take:()=>Yi,takeLast:()=>NT,takeUntil:()=>He,takeWhile:()=>fp,tap:()=>vu,throttle:()=>MT,throwError:()=>IT,timeInterval:()=>YT,timeout:()=>iE,timer:()=>pn,toPromise:()=>eE,toReadableStream:()=>tE,withLatestFrom:()=>sT,zip:()=>oT});function le(...o){}var cp=o=>o(),Kg=o=>o;function ec(){this.dispose()}var dp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",eT=1,vt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Jl(i,this,this.streamId++);return ye.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},qr=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=le,this.error=le,this.next=le,this.dispose=le,this.subscribe=le,this.doDefer()}subscribe(i){return i instanceof vt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cp),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}},W=class extends qr{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)}},jr=class extends qr{constructor(i,e=le,t=le,r=le){if(super(),this._next=e,this._error=t,this._complete=r,this.then=le,i instanceof vt){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{ye.defer(s,0)}),ye.create(s),ye.pipe(s),this.sourceId=s.id,this.subscribe(i),ye.subscribe({id:s.id,end:!0}),e==le?this._next=n=>ye.next(s,0,n):this.next=n=>{ye.next(s,0,n),e(n)},r==le?this._complete=()=>ye.complete(s,0):this.complete=()=>{this.dispose(),ye.complete(s,0),r()},t==le?this._error=n=>ye.complete(s,0,n):this.error=n=>{this.dispose(),ye.complete(s,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 ue(o,...i){return i.reduce((e,t)=>t(e),o)}function oe(o,i,e){if(dp()){let t=Object.defineProperties(Object.setPrototypeOf(o,vt.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}});ye.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof vt&&ye.addSource(t,s)}return t}return o}function j(o,i){return function(...e){return t=>{if(t instanceof vt){let r=oe(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,ye.pipe(r),r}else return r=>t(new o(r,...e))}}}function fr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var Jl=class extends W{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{ye.defer(this.source,this.id)})}next(i){ye.next(this.source,this.id,i),this.sink.next(i)}complete(){ye.complete(this.source,this.id),this.sink.complete()}error(i){ye.complete(this.source,this.id,i),this.sink.error(i)}},ye={addSource(o,i){fr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){fr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){fr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){fr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){fr("defer",{id:o.id,streamId:i})},pipe(o){fr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){fr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=eT++),fr("create",{name:o.toString(),id:o.id})}},hn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var tc=class extends qr{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 Qi(){return o=>{let i=new tc(o);if(o instanceof vt){let e=oe(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,ye.pipe(e),e}return oe(i.add.bind(i),"share",arguments)}}function zl(...o){return oe(i=>{let e=new W(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function Ql(...o){return oe(i=>{let e=new Map;o.forEach(t=>{let r=new W(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function tT(...o){return oe(i=>{let e=0,t=o.length,r=new W(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function iT(o){return i=>{let e=new tc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},oe(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function rT(o,i,e){return oe(t=>o()?i(t):e(t),"iif",arguments)}function lp(...o){return oe(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new W(i);u.next=h=>{--t===0?(u.next=m=>{s[l]=m,i.next(s)},u.next(h)):s[l]=h},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function oT(...o){return oe(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new W(i),u=[];r[c]=u,l.next=h=>{u.push(h),r.every(m=>m.length)&&i.next(r.map(m=>m.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function mn(...o){return i=>oe((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var ql=class extends W{constructor(i,...e){super(i);let t=new W(this.sink);t.next=r=>this.buffer=r,t.complete=le,t.subscribe(lp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},sT=j(ql,"withLatestFrom"),jl=class extends W{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()}},nT=j(jl,"bufferCount"),Xl=class extends W{constructor(i,e){super(i),this.buffer=[];let t=new W(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=le,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},aT=j(Xl,"buffer");var cT=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(h){n(h)}}function c(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function nt(o){let i=arguments,e=Qi()(oe(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=le,e.complete=le,e.error=le,e}function up(o){return oe(i=>i.subscribe(o()),"defer",arguments)}var hp=o=>i=>{setTimeout(()=>o(i))},mp=o=>hp(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function dT(...o){return oe(mp(o),"of",arguments)}function lT(o){return oe(mp(o),"fromArray",arguments)}function Yl(o){return oe(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function pn(o,i){return oe(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>{clearTimeout(r)};e.defer(s)},"timer",arguments)}function ic(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function uT(o,i){return oe(ic(o,i),"fromEventPattern",arguments)}function me(o,i){if("on"in o&&"off"in o)return oe(ic(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return oe(ic(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return oe(ic(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pp(o){return oe(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function hT(o,i){return oe(up(()=>pp(fetch(o,i))),"fromFetch",arguments)}function mT(o){return oe(hp(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function pT(o){let i=e=>cT(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return oe(e=>{i(e)},"fromReader",arguments)}function fT(o){return oe(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function _T(){return oe(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function gT(o,i){return oe((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function TT(o,i,...e){return oe(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function ET(o,i,...e){return oe(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function ST(){return oe(()=>{},"never",arguments)}function IT(o){return oe(i=>i.error(o),"throwError",arguments)}function fn(){return oe(o=>o.complete(),"empty",arguments)}var Xr=class extends W{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Zl=j(Xr,"reduce"),AT=o=>j(Xr,"count")((i,e)=>o(e)?i+1:i,0),CT=()=>j(Xr,"max")(Math.max),RT=()=>j(Xr,"min")(Math.min),yT=()=>j(Xr,"sum")((o,i)=>o+i,0);var Kl=class extends W{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Si=j(Kl,"filter"),eu=class extends W{next(i){}},bT=j(eu,"ignoreElements"),tu=class extends W{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Yi=j(tu,"take"),iu=class extends W{constructor(i,e){super(i);let t=new W(i);t.next=()=>i.complete(),t.complete=ec,t.subscribe(e)}},He=j(iu,"takeUntil"),ru=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},fp=j(ru,"takeWhile"),NT=o=>Zl((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),ou=class extends W{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},vT=j(ou,"skip"),su=class extends W{constructor(i,e){super(i),i.next=le;let t=new W(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=ec,t.subscribe(e)}},DT=j(su,"skipUntil"),nu=class extends W{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},sc=j(nu,"skipWhile"),OT={leading:!0,trailing:!1},au=class extends W{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)}},rc=class extends W{constructor(i,e,t=OT){super(i),this.durationSelector=e,this.config=t,this._throttle=new au(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=le,this._throttle.complete(),super.complete()}},MT=j(rc,"throttle"),kT={leading:!1,trailing:!0},wT=o=>j(rc,"audit")(o,kT),cu=class extends W{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},oc=class extends W{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new cu(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()}},xT=j(oc,"debounce"),LT=o=>j(oc,"debounceTime")(i=>pn(o)),du=class extends W{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()}},PT=j(du,"elementAt"),UT=o=>i=>Yi(1)(sc(e=>!o(e))(i)),lu=class extends W{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}},VT=j(lu,"findIndex"),uu=class extends W{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()}},BT=j(uu,"first"),hu=class extends W{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()}},FT=j(hu,"last"),mu=class extends W{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()}},HT=j(mu,"every");var pu=class extends W{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))}},Ru=j(pu,"scan"),fu=class extends W{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},$T=j(fu,"pairwise"),nc=class extends W{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},_n=j(nc,"map"),GT=o=>j(nc,"mapTo")(i=>o),qo=class extends W{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()}},jo=class extends W{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()}},ac=class extends qo{},cc=class extends jo{next(i){this.subInner(i,ac),this.next=e=>{this.currentSink.dispose(),this.subInner(e,ac)}}},Xo=j(cc,"switchMap");function hc(o){return(i,e)=>o(()=>i,e)}var zr=hc(j(cc,"switchMapTo")),_u=class extends qo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},dc=class extends jo{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(),_u),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},WT=j(dc,"concatMap"),JT=hc(j(dc,"concatMapTo")),gu=class extends qo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},lc=class extends jo{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,gu),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},qT=j(lc,"mergeMap"),jT=hc(j(lc,"mergeMapTo")),Tu=class extends qo{dispose(){this.context.resetNext(),super.dispose()}},uc=class extends jo{next(i){this.next=le,this.subInner(i,Tu)}},XT=j(uc,"exhaustMap"),zT=hc(j(uc,"exhaustMapTo")),Eu=class extends W{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=nt(),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)}},QT=j(Eu,"groupBy"),Su=class extends W{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}},YT=j(Su,"timeInterval"),Iu=class extends W{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()}},ZT=j(Iu,"bufferTime"),Au=class extends W{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)}},KT=j(Au,"delay"),Cu=class extends W{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},yu=j(Cu,"catchError");var eE=()=>o=>new Promise((i,e)=>{let t;new jr(o,r=>t=r,e,()=>i(t))}),tE=()=>o=>{let i;return new ReadableStream({start(e){i=new jr(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},be=(o=le,i=le,e=le)=>t=>new jr(t,o,i,e),bu=class extends W{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)}))}},vu=j(bu,"tap"),Nu=class extends W{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new hn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},iE=j(Nu,"timeout"),rE=(o=1/0)=>i=>{if(i instanceof vt){let e=oe(t=>{let r=o,s=new W(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,ye.pipe(e),e}else return e=>{let t=o,r=new W(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var oE=ue(Yl(250),_n(()=>performance.now()),Qi());var _p=o=>i=>{let e=performance.now();ue(oE,sc(t=>t-e<o),Yi(1))(i)};var nE=[0,1,1,1,0,0,1,0],Qr=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Fe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(nE)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ke){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code: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){this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),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)}},zo=class extends Qr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",me(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Bi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=me(this._videoTrack,"mute"),ue(me(this._videoTrack,"ended"),He(this._closedOb),be(()=>{this.context.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ue(this._muteOb,He(this._closedOb),zr(_p(5e3)),Si(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),be(()=>{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()}},mc=class extends zo{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var pc=class extends zo{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var gn=class extends Ye{constructor(e,t){super(e,v({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,Je===16&&(this._canvasRendered=nt(),ue(this._canvasRendered,mn(this._image),Xo(r=>r instanceof HTMLCanvasElement?me(r,"rendered"):fn()),He(me(this,"closed")),be(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Hr()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Tn=class extends gn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",ue(me(this._player,he.PLAYER_STATE_CHANGED),He(me(this,"closed")),Si(({state:s})=>s==="PLAYING"),be(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Dt=class extends Tn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new ot({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()}},fc=class extends Ye{constructor(e,t,r){super(e,w(v({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
34
|
+
`);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var cE=`
|
|
32
35
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
33
36
|
attribute vec4 a_position;
|
|
34
37
|
attribute vec2 a_texCoord;
|
|
@@ -38,7 +41,7 @@ void main() {
|
|
|
38
41
|
gl_Position = a_position;
|
|
39
42
|
v_texCoord = a_texCoord;
|
|
40
43
|
}
|
|
41
|
-
`,
|
|
44
|
+
`,dE=`
|
|
42
45
|
// \u7247\u5143\u7740\u8272\u5668
|
|
43
46
|
precision mediump float;
|
|
44
47
|
varying vec2 v_texCoord;
|
|
@@ -46,66 +49,32 @@ uniform sampler2D u_texture;
|
|
|
46
49
|
|
|
47
50
|
void main() {
|
|
48
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
49
|
-
} `;var os=class extends de{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 bi(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new en(this,e)}createVideoImageSource(e,r){return new wa(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new Ma(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(os,"_ids",0);var UI={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},tn=class tn extends os{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}_${os._ids++}`),this.ctx=this._canvas.getContext("webgl2",UI),!this.ctx)throw new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,kI),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,LI),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let r="";return e&&(r=e.message,this.error=e,Q.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(tn,"UNAVAILABLE","unavailable"),Z([Qe(de.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),Q.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),Q.addSuccessEvent({key:512700})}})],tn.prototype,"create",1),Z([Qe("created",de.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(tn.UNAVAILABLE,e),this.removeAllListeners()}})],tn.prototype,"destroy",1);var Tt=tn,Ft=class extends os{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${os._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new ue({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,Q.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(),Q.addSuccessEvent({key:512703})}};Z([Qe(de.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),Q.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),Q.addSuccessEvent({key:512701})}})],Ft.prototype,"create",1),Z([Qe("created",de.INIT,{ignoreError:!0,sync:!0})],Ft.prototype,"destroy",1);function VI(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var ao=class extends Ks{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(st(r==null?void 0:r.canvasRender)?r.canvasRender:Jt===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 Ft({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new is(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Ei()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=VI(r);if(!ke(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(c=>c.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(c=>c.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)}},Jd=class extends ao{constructor(e,r){super(e,r,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var rn=new Map;V.on(U.JOIN_SUCCESS,({room:i})=>{nt(i.userId,{eventId:32788})});V.on(U.LEAVE_START,({room:i})=>{nt(i.userId,{eventId:32789})});V.on(U.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),nt(i.room.userId,{eventId:t})}});V.on(U.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),nt(i.room.userId,{eventId:t})}});V.on(U.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?nt(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):nt(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});V.on(U.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===D.AUDIO?nt(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):nt(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});V.on(U.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&nt(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&nt(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&nt(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});V.on(U.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&nt(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&nt(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&nt(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});V.on(U.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&nt(i.room.userId,{eventId:i.kind===D.VIDEO?32780:32781})});V.on(U.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&nt(i.room.userId,{eventId:i.kind===D.VIDEO?32782:32783})});V.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&&nt(i.userId,{eventId:r})});V.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&&nt(i.userId,{eventId:s,remoteUserId:r})});V.on(U.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let c=o?1:0;s||(c=o?3:2);let l=r==="h264"?0:2,m={eventId:4004,param1:c,param2:l,streamType:n||2};e&&(m.remoteUserId=e,m.eventId=4005),nt(t,m),Q.addEnum({key:e?514701:513701,value:c}),Q.addEnum({key:e?514700:513700,value:l})});V.on(U.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===D.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),nt(i.userId,e)}});function nt(i,t){let e=Te(X({},t),{timestamp:Rn()});rn.has(i)?rn.get(i).push(e):rn.set(i,[e])}function Zf(i){if(rn.has(i)){let t=rn.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 rn.delete(i),t}return[]}function Kf(...i){return xe((t,e)=>function(...r){return FI.call(this,i,r,e,this._name),t.apply(this,r)})}function FI(i,t,e,r){try{if(ot(i))for(let o=0;o<i.length;o++)zd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else zd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}catch(o){throw $.error(o),o}}function zd({rule:i,value:t,key:e,fnName:r,className:o}){if(P(t)){if(i.required)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(P(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let c=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(c=!0),We(i.type[l])&&t instanceof i.type[l]&&(c=!0),Oe(i.type[l])&&ct(t)===i.type[l].toLowerCase()&&(c=!0);if(!c)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:i.type.map(l=>Lo(l)?vs(l):Oe(l)?l:ct(l))},fnName:r,value:t},link:{className:o,fnName:r}})})}else if(!P(i.type)&&ct(t)!==i.type)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_TYPE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.allowEmpty===!1){let c=ke(t)&&(t===0||Number.isNaN(t)),l=Oe(t)&&t.trim()==="";if(c||l)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_EMPTY,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}if(i.notLessThanZero&&ke(t)&&t<0)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!P(i.min)&&ke(t)&&t<i.min)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_MIN,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!P(i.max)&&ke(t)&&t>i.max)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_MAX,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}else if(We(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.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 ue({code:q.INVALID_PARAMETER,message:Be({key:$e.INVALID_PARAMETER_RANGE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});let{properties:s}=i;Lt(s)&&er(t)&&Object.keys(s).forEach(c=>{zd.call(this,{rule:s[c],value:t&&t[c],key:`${e}.${c}`,fnName:r,className:o})});let{arrayItem:n}=i;Lt(n)&&ot(t)&&t.forEach((c,l)=>{zd.call(this,{rule:n,value:c,key:`${e}[${l}]`,fnName:r,className:o})}),We(i.validate)&&i.validate.call(this,t,e,r,o,this)}var $I=ji(Zi(),1);var BI=Object.create,Kd=Object.defineProperty,HI=Object.defineProperties,ig=Object.getOwnPropertyDescriptor,WI=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertyNames,eg=Object.getOwnPropertySymbols,GI=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty,jI=Object.prototype.propertyIsEnumerable,dp=(i,t,e)=>t in i?Kd(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Qd=(i,t)=>{for(var e in t||(t={}))sg.call(t,e)&&dp(i,e,t[e]);if(eg)for(var e of eg(t))jI.call(t,e)&&dp(i,e,t[e]);return i},Yd=(i,t)=>HI(i,WI(t)),qI=(i,t)=>function(){return t||(0,i[og(i)[0]])((t={exports:{}}).exports,t),t.exports},JI=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of og(t))sg.call(i,o)||o===e||Kd(i,o,{get:()=>t[o],enumerable:!(r=ig(t,o))||r.enumerable});return i},zI=(i,t,e)=>(e=i!=null?BI(GI(i)):{},JI(!t&&i&&i.__esModule?e:Kd(e,"default",{value:i,enumerable:!0}),i)),Ri=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?ig(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&&Kd(t,e,s),s},wr=(i,t,e)=>dp(i,typeof t!="symbol"?t+"":t,e),XI=qI({"../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(m,f,E){this.fn=m,this.context=f,this.once=E||!1}function n(m,f,E,_,v){if(typeof E!="function")throw new TypeError("The listener must be a function");var k=new s(E,_||m,v),M=r?r+f:f;return m._events[M]?m._events[M].fn?m._events[M]=[m._events[M],k]:m._events[M].push(k):(m._events[M]=k,m._eventsCount++),m}function c(m,f){--m._eventsCount==0?m._events=new o:delete m._events[f]}function l(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),l.prototype.eventNames=function(){var m,f,E=[];if(this._eventsCount===0)return E;for(f in m=this._events)e.call(m,f)&&E.push(r?f.slice(1):f);return Object.getOwnPropertySymbols?E.concat(Object.getOwnPropertySymbols(m)):E},l.prototype.listeners=function(m){var f=r?r+m:m,E=this._events[f];if(!E)return[];if(E.fn)return[E.fn];for(var _=0,v=E.length,k=new Array(v);_<v;_++)k[_]=E[_].fn;return k},l.prototype.listenerCount=function(m){var f=r?r+m:m,E=this._events[f];return E?E.fn?1:E.length:0},l.prototype.emit=function(m,f,E,_,v,k){var M=r?r+m:m;if(!this._events[M])return!1;var N,B,ee=this._events[M],me=arguments.length;if(ee.fn){switch(ee.once&&this.removeListener(m,ee.fn,void 0,!0),me){case 1:return ee.fn.call(ee.context),!0;case 2:return ee.fn.call(ee.context,f),!0;case 3:return ee.fn.call(ee.context,f,E),!0;case 4:return ee.fn.call(ee.context,f,E,_),!0;case 5:return ee.fn.call(ee.context,f,E,_,v),!0;case 6:return ee.fn.call(ee.context,f,E,_,v,k),!0}for(B=1,N=new Array(me-1);B<me;B++)N[B-1]=arguments[B];ee.fn.apply(ee.context,N)}else{var oe,Xe=ee.length;for(B=0;B<Xe;B++)switch(ee[B].once&&this.removeListener(m,ee[B].fn,void 0,!0),me){case 1:ee[B].fn.call(ee[B].context);break;case 2:ee[B].fn.call(ee[B].context,f);break;case 3:ee[B].fn.call(ee[B].context,f,E);break;case 4:ee[B].fn.call(ee[B].context,f,E,_);break;default:if(!N)for(oe=1,N=new Array(me-1);oe<me;oe++)N[oe-1]=arguments[oe];ee[B].fn.apply(ee[B].context,N)}}return!0},l.prototype.on=function(m,f,E){return n(this,m,f,E,!1)},l.prototype.once=function(m,f,E){return n(this,m,f,E,!0)},l.prototype.removeListener=function(m,f,E,_){var v=r?r+m:m;if(!this._events[v])return this;if(!f)return c(this,v),this;var k=this._events[v];if(k.fn)k.fn!==f||_&&!k.once||E&&k.context!==E||c(this,v);else{for(var M=0,N=[],B=k.length;M<B;M++)(k[M].fn!==f||_&&!k[M].once||E&&k[M].context!==E)&&N.push(k[M]);N.length?this._events[v]=N.length===1?N[0]:N:c(this,v)}return this},l.prototype.removeAllListeners=function(m){var f;return m?(f=r?r+m:m,this._events[f]&&c(this,f)):(this._events=new o,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=r,l.EventEmitter=l,t!==void 0&&(t.exports=l)}}),QI=zI(XI(),1),tg=Symbol("instance"),pO=Symbol("abortCtrl"),Xd=Symbol("cacheResult"),cp=class{constructor(i,t,e){this.oldState=i,this.newState=t,this.action=e,this.aborted=!1}abort(i){this.aborted=!0,Pa.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Zd=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function YI(i){return typeof i=="object"&&i&&"then"in i}var xa=new Map;function co(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let l=xa.get(r)||[];xa.has(r)||xa.set(r,l),l.push({from:i,to:t,action:n})}let c=s.value;s.value=function(...l){let m=this;if(e.context&&(m=jt.get(typeof e.context=="function"?e.context.call(this,...l):e.context)),m.state===t)return e.sync?m[Xd]:Promise.resolve(m[Xd]);m.state instanceof cp&&m.state.action==e.abortAction&&m.state.abort(m);let f=null;Array.isArray(i)?i.length==0?m.state instanceof cp&&m.state.abort(m):typeof m.state=="string"&&i.includes(m.state)||(f=new Zd(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(f=new Zd(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let E=N=>{if(e.fail&&e.fail.call(this,N),e.sync){if(e.ignoreError)return N;throw N}return e.ignoreError?Promise.resolve(N):Promise.reject(N)};if(f)return E(f);let _=m.state,v=new cp(_,t,n);Pa.call(m,v);let k=N=>{var B;return m[Xd]=N,v.aborted||(Pa.call(m,t),(B=e.success)===null||B===void 0||B.call(this,m[Xd])),N},M=N=>(Pa.call(m,_,N),E(N));try{let N=c.apply(this,l);return YI(N)?N.then(k).catch(M):e.sync?k(N):Promise.resolve(k(N))}catch(N){return M(new Zd(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${N}`,N instanceof Error?N:new Error(String(N))))}}}}function ZI(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new Zd(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var KI=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 Pa(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 mr extends QI.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=mr.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[tg];o?this.name=o.name+"-"+o.count++:r[tg]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=xa.get(t)||[],r=new Set,o=[],s=[],n=new Set,c=Object.getPrototypeOf(t);xa.has(c)&&(c.stateDiagram.forEach(m=>r.add(m)),c.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:f,action:E})=>{typeof m=="string"?o.push({from:m,to:f,action:E}):m.length?m.forEach(_=>{o.push({from:_,to:f,action:E})}):s.push({to:f,action:E})}),o.forEach(({from:m,to:f,action:E})=>{n.add(m),n.add(f),n.add(E+"ing"),r.add(`${m} --> ${E}ing : ${E}`),r.add(`${E}ing --> ${f} : ${E} \u{1F7E2}`),r.add(`${E}ing --> ${m} : ${E} \u{1F534}`)}),s.forEach(({to:m,action:f})=>{r.add(`${f}ing --> ${m} : ${f} \u{1F7E2}`),n.forEach(E=>{E!==m&&r.add(`${E} --> ${f}ing : ${f}`)})});let l=[...r];return Object.defineProperties(t,{stateDiagram:{value:l},allStates:{value:n}}),l}static get(t){let e;return typeof t=="string"?(e=mr.instances.get(t),e||mr.instances.set(t,e=new mr(t,void 0,Object.create(mr.prototype)))):(e=mr.instances2.get(t),e||mr.instances2.set(t,e=new mr(t.constructor.name,void 0,Object.create(mr.prototype)))),e}static getState(t){var e;return(e=mr.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){KI(mr.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Pa.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 on=class extends jt{constructor(){super(...arguments),wr(this,"decoder"),wr(this,"config")}initialize(){return y(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(Yd(Qd({},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 eS(){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,c=0,l={wasmBinary:o,postRun:()=>{i=new l.VideoDecoder({videoInfo(m,f){n=m,c=f,console.log("video info",m,f)},yuvData(m,f){let E=n*c,_=E>>2,v=l.HEAPU32[m>>2],k=l.HEAPU32[1+(m>>2)],M=l.HEAPU32[2+(m>>2)],N=l.HEAPU8.subarray(v,v+E),B=l.HEAPU8.subarray(k,k+_),ee=l.HEAPU8.subarray(M,M+_),me=new Uint8Array(E+_+_);me.set(N),me.set(B,E),me.set(ee,E+_);let oe=new VideoFrame(me,{codedWidth:n,codedHeight:c,format:"I420",timestamp:f});e?(s==null||s.drawImage(oe,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:oe},[oe])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(l)}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:"")}}}Ri([co([jt.INIT,"closed"],"initialized")],on.prototype,"initialize",1),Ri([co("initialized","configured",{sync:!0})],on.prototype,"configure",1),Ri([ZI("configured")],on.prototype,"decode",1),Ri([co([],jt.INIT,{sync:!0})],on.prototype,"reset",1),Ri([co([],"closed",{ignoreError:!0,sync:!0})],on.prototype,"close",1);var Oa=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,wr(this,"worker"),wr(this,"decoder"),wr(this,"config"),wr(this,"module",{}),wr(this,"width",0),wr(this,"height",0)}initialize(i){return y(this,null,function*(){var t;if(this.workerMode){let r=new RegExp("\\{(.+)\\}","s").exec(eS.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=c=>{if(c.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(c.data.type==="yuvData"){let{videoFrame:l}=c.data;this.emit("videoFrame",l)}}})}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)],c=this.module.HEAPU8.subarray(o,o+e),l=this.module.HEAPU8.subarray(s,s+r),m=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",{y:c,u:l,v:m,timestamp:t});let f=new Uint8Array(e+r+r);f.set(c),f.set(l,e),f.set(m,e+r),this.emit("videoFrame",new VideoFrame(f,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};Ri([co([jt.INIT,"closed"],"initialized")],Oa.prototype,"initialize",1),Ri([co("initialized","configured",{sync:!0})],Oa.prototype,"configure",1),Ri([co([],jt.INIT,{sync:!0})],Oa.prototype,"reset",1),Ri([co([],"closed",{sync:!0})],Oa.prototype,"close",1);var tS=(()=>{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,d)=>{e=a,r=d});var s,n,c,l=Object.assign({},o),m="./this.program",f=typeof window=="object",E=typeof importScripts=="function",_=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(f||E)&&(E?_=self.location.href:typeof document!="undefined"&&document.currentScript&&(_=document.currentScript.src),i&&(_=i),_=_.indexOf("blob:")!==0?_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=a=>{var d=new XMLHttpRequest;return d.open("GET",a,!1),d.send(null),d.responseText},E&&(c=a=>{var d=new XMLHttpRequest;return d.open("GET",a,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),n=(a,d,p)=>{var h=new XMLHttpRequest;h.open("GET",a,!0),h.responseType="arraybuffer",h.onload=()=>{h.status==200||h.status==0&&h.response?d(h.response):p()},h.onerror=p,h.send(null)});var v,k=o.print||console.log.bind(console),M=o.printErr||console.error.bind(console);Object.assign(o,l),l=null,o.arguments&&o.arguments,o.thisProgram&&(m=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(v=o.wasmBinary);var N,B;o.noExitRuntime,typeof WebAssembly!="object"&&Or("no native wasm support detected");var ee,me,oe,Xe,J,Ue,_o,ln,mn,pn=!1,Mr=[],us=[],wi=[],nr=0,te=null,Qr=null;function ls(a){nr++,o.monitorRunDependencies&&o.monitorRunDependencies(nr)}function To(a){if(nr--,o.monitorRunDependencies&&o.monitorRunDependencies(nr),nr==0&&(te!==null&&(clearInterval(te),te=null),Qr)){var d=Qr;Qr=null,d()}}function Or(a){o.onAbort&&o.onAbort(a),M(a="Aborted("+a+")"),pn=!0,a+=". Build with -sASSERTIONS for more info.";var d=new WebAssembly.RuntimeError(a);throw r(d),d}var Yr,hn,Ee,Ze;function Ot(a){return a.startsWith("data:application/octet-stream;base64,")}function j(a){if(a==Yr&&v)return new Uint8Array(v);if(c)return c(a);throw"both async and sync fetching of the wasm failed"}function xr(a,d,p){return function(h){return v||!f&&!E||typeof fetch!="function"?Promise.resolve().then(()=>j(h)):fetch(h,{credentials:"same-origin"}).then(I=>{if(!I.ok)throw"failed to load wasm binary file at '"+h+"'";return I.arrayBuffer()}).catch(()=>j(h))}(a).then(h=>WebAssembly.instantiate(h,d)).then(h=>h).then(p,h=>{M("failed to asynchronously prepare wasm: "+h),Or(h)})}Ot(Yr="videodec.wasm")||(hn=Yr,Yr=o.locateFile?o.locateFile(hn,_):_+hn);var Mi=a=>{for(;a.length>0;)a.shift()(o)};function Oi(a){this.excPtr=a,this.ptr=a-24,this.set_type=function(d){Ue[this.ptr+4>>2]=d},this.get_type=function(){return Ue[this.ptr+4>>2]},this.set_destructor=function(d){Ue[this.ptr+8>>2]=d},this.get_destructor=function(){return Ue[this.ptr+8>>2]},this.set_caught=function(d){d=d?1:0,ee[this.ptr+12|0]=d},this.get_caught=function(){return ee[this.ptr+12|0]!=0},this.set_rethrown=function(d){d=d?1:0,ee[this.ptr+13|0]=d},this.get_rethrown=function(){return ee[this.ptr+13|0]!=0},this.init=function(d,p){this.set_adjusted_ptr(0),this.set_type(d),this.set_destructor(p)},this.set_adjusted_ptr=function(d){Ue[this.ptr+16>>2]=d},this.get_adjusted_ptr=function(){return Ue[this.ptr+16>>2]},this.get_exception_ptr=function(){if(yn(this.get_type()))return Ue[this.excPtr>>2];var d=this.get_adjusted_ptr();return d!==0?d:this.excPtr}}var pe={isAbs:a=>a.charAt(0)==="/",splitPath:a=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1),normalizeArray:(a,d)=>{for(var p=0,h=a.length-1;h>=0;h--){var I=a[h];I==="."?a.splice(h,1):I===".."?(a.splice(h,1),p++):p&&(a.splice(h,1),p--)}if(d)for(;p;p--)a.unshift("..");return a},normalize:a=>{var d=pe.isAbs(a),p=a.substr(-1)==="/";return(a=pe.normalizeArray(a.split("/").filter(h=>!!h),!d).join("/"))||d||(a="."),a&&p&&(a+="/"),(d?"/":"")+a},dirname:a=>{var d=pe.splitPath(a),p=d[0],h=d[1];return p||h?(h&&(h=h.substr(0,h.length-1)),p+h):"."},basename:a=>{if(a==="/")return"/";var d=(a=(a=pe.normalize(a)).replace(/\/$/,"")).lastIndexOf("/");return d===-1?a:a.substr(d+1)},join:function(){var a=Array.prototype.slice.call(arguments);return pe.normalize(a.join("/"))},join2:(a,d)=>pe.normalize(a+"/"+d)},fn=a=>(fn=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return d=>crypto.getRandomValues(d);Or("initRandomDevice")})())(a),qt={resolve:function(){for(var a="",d=!1,p=arguments.length-1;p>=-1&&!d;p--){var h=p>=0?arguments[p]:g.cwd();if(typeof h!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!h)return"";a=h+"/"+a,d=pe.isAbs(h)}return(d?"/":"")+(a=pe.normalizeArray(a.split("/").filter(I=>!!I),!d).join("/"))||"."},relative:(a,d)=>{function p(x){for(var Y=0;Y<x.length&&x[Y]==="";Y++);for(var se=x.length-1;se>=0&&x[se]==="";se--);return Y>se?[]:x.slice(Y,se-Y+1)}a=qt.resolve(a).substr(1),d=qt.resolve(d).substr(1);for(var h=p(a.split("/")),I=p(d.split("/")),A=Math.min(h.length,I.length),b=A,R=0;R<A;R++)if(h[R]!==I[R]){b=R;break}var L=[];for(R=b;R<h.length;R++)L.push("..");return(L=L.concat(I.slice(b))).join("/")}},xi=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,xt=(a,d,p)=>{for(var h=d+p,I=d;a[I]&&!(I>=h);)++I;if(I-d>16&&a.buffer&&xi)return xi.decode(a.subarray(d,I));for(var A="";d<I;){var b=a[d++];if(128&b){var R=63&a[d++];if((224&b)!=192){var L=63&a[d++];if((b=(240&b)==224?(15&b)<<12|R<<6|L:(7&b)<<18|R<<12|L<<6|63&a[d++])<65536)A+=String.fromCharCode(b);else{var x=b-65536;A+=String.fromCharCode(55296|x>>10,56320|1023&x)}}else A+=String.fromCharCode((31&b)<<6|R)}else A+=String.fromCharCode(b)}return A},gn=[],Io=a=>{for(var d=0,p=0;p<a.length;++p){var h=a.charCodeAt(p);h<=127?d++:h<=2047?d+=2:h>=55296&&h<=57343?(d+=4,++p):d+=3}return d},So=(a,d,p,h)=>{if(!(h>0))return 0;for(var I=p,A=p+h-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>=A)break;d[p++]=R}else if(R<=2047){if(p+1>=A)break;d[p++]=192|R>>6,d[p++]=128|63&R}else if(R<=65535){if(p+2>=A)break;d[p++]=224|R>>12,d[p++]=128|R>>6&63,d[p++]=128|63&R}else{if(p+3>=A)break;d[p++]=240|R>>18,d[p++]=128|R>>12&63,d[p++]=128|R>>6&63,d[p++]=128|63&R}}return d[p]=0,p-I};function ms(a,d,p){var h=p>0?p:Io(a)+1,I=new Array(h),A=So(a,I,0,I.length);return d&&(I.length=A),I}var ce={ttys:[],init:function(){},shutdown:function(){},register:function(a,d){ce.ttys[a]={input:[],output:[],ops:d},g.registerDevice(a,ce.stream_ops)},stream_ops:{open:function(a){var d=ce.ttys[a.node.rdev];if(!d)throw new g.ErrnoError(43);a.tty=d,a.seekable=!1},close:function(a){a.tty.ops.fsync(a.tty)},fsync:function(a){a.tty.ops.fsync(a.tty)},read:function(a,d,p,h,I){if(!a.tty||!a.tty.ops.get_char)throw new g.ErrnoError(60);for(var A=0,b=0;b<h;b++){var R;try{R=a.tty.ops.get_char(a.tty)}catch(L){throw new g.ErrnoError(29)}if(R===void 0&&A===0)throw new g.ErrnoError(6);if(R==null)break;A++,d[p+b]=R}return A&&(a.node.timestamp=Date.now()),A},write:function(a,d,p,h,I){if(!a.tty||!a.tty.ops.put_char)throw new g.ErrnoError(60);try{for(var A=0;A<h;A++)a.tty.ops.put_char(a.tty,d[p+A])}catch(b){throw new g.ErrnoError(29)}return h&&(a.node.timestamp=Date.now()),A}},default_tty_ops:{get_char:function(a){return(()=>{if(!gn.length){var d=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(d=window.prompt("Input: "))!==null&&(d+=`
|
|
50
|
-
`):typeof readline=="function"&&(d=readline())!==null&&(d+=`
|
|
51
|
-
`),!d)return null;gn=ms(d,!0)}return gn.shift()})()},put_char:function(a,d){d===null||d===10?(k(xt(a.output,0)),a.output=[]):d!=0&&a.output.push(d)},fsync:function(a){a.output&&a.output.length>0&&(k(xt(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,d,p){return 0},ioctl_tiocgwinsz:function(a){return[24,80]}},default_tty1_ops:{put_char:function(a,d){d===null||d===10?(M(xt(a.output,0)),a.output=[]):d!=0&&a.output.push(d)},fsync:function(a){a.output&&a.output.length>0&&(M(xt(a.output,0)),a.output=[])}}},En=a=>{Or()},Ae={ops_table:null,mount:a=>Ae.createNode(null,"/",16895,0),createNode(a,d,p,h){if(g.isBlkdev(p)||g.isFIFO(p))throw new g.ErrnoError(63);Ae.ops_table||(Ae.ops_table={dir:{node:{getattr:Ae.node_ops.getattr,setattr:Ae.node_ops.setattr,lookup:Ae.node_ops.lookup,mknod:Ae.node_ops.mknod,rename:Ae.node_ops.rename,unlink:Ae.node_ops.unlink,rmdir:Ae.node_ops.rmdir,readdir:Ae.node_ops.readdir,symlink:Ae.node_ops.symlink},stream:{llseek:Ae.stream_ops.llseek}},file:{node:{getattr:Ae.node_ops.getattr,setattr:Ae.node_ops.setattr},stream:{llseek:Ae.stream_ops.llseek,read:Ae.stream_ops.read,write:Ae.stream_ops.write,allocate:Ae.stream_ops.allocate,mmap:Ae.stream_ops.mmap,msync:Ae.stream_ops.msync}},link:{node:{getattr:Ae.node_ops.getattr,setattr:Ae.node_ops.setattr,readlink:Ae.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Ae.node_ops.getattr,setattr:Ae.node_ops.setattr},stream:g.chrdev_stream_ops}});var I=g.createNode(a,d,p,h);return g.isDir(I.mode)?(I.node_ops=Ae.ops_table.dir.node,I.stream_ops=Ae.ops_table.dir.stream,I.contents={}):g.isFile(I.mode)?(I.node_ops=Ae.ops_table.file.node,I.stream_ops=Ae.ops_table.file.stream,I.usedBytes=0,I.contents=null):g.isLink(I.mode)?(I.node_ops=Ae.ops_table.link.node,I.stream_ops=Ae.ops_table.link.stream):g.isChrdev(I.mode)&&(I.node_ops=Ae.ops_table.chrdev.node,I.stream_ops=Ae.ops_table.chrdev.stream),I.timestamp=Date.now(),a&&(a.contents[d]=I,a.timestamp=I.timestamp),I},getFileDataAsTypedArray:a=>a.contents?a.contents.subarray?a.contents.subarray(0,a.usedBytes):new Uint8Array(a.contents):new Uint8Array(0),expandFileStorage(a,d){var p=a.contents?a.contents.length:0;if(!(p>=d)){d=Math.max(d,p*(p<1048576?2:1.125)>>>0),p!=0&&(d=Math.max(d,256));var h=a.contents;a.contents=new Uint8Array(d),a.usedBytes>0&&a.contents.set(h.subarray(0,a.usedBytes),0)}},resizeFileStorage(a,d){if(a.usedBytes!=d)if(d==0)a.contents=null,a.usedBytes=0;else{var p=a.contents;a.contents=new Uint8Array(d),p&&a.contents.set(p.subarray(0,Math.min(d,a.usedBytes))),a.usedBytes=d}},node_ops:{getattr(a){var d={};return d.dev=g.isChrdev(a.mode)?a.id:1,d.ino=a.id,d.mode=a.mode,d.nlink=1,d.uid=0,d.gid=0,d.rdev=a.rdev,g.isDir(a.mode)?d.size=4096:g.isFile(a.mode)?d.size=a.usedBytes:g.isLink(a.mode)?d.size=a.link.length:d.size=0,d.atime=new Date(a.timestamp),d.mtime=new Date(a.timestamp),d.ctime=new Date(a.timestamp),d.blksize=4096,d.blocks=Math.ceil(d.size/d.blksize),d},setattr(a,d){d.mode!==void 0&&(a.mode=d.mode),d.timestamp!==void 0&&(a.timestamp=d.timestamp),d.size!==void 0&&Ae.resizeFileStorage(a,d.size)},lookup(a,d){throw g.genericErrors[44]},mknod:(a,d,p,h)=>Ae.createNode(a,d,p,h),rename(a,d,p){if(g.isDir(a.mode)){var h;try{h=g.lookupNode(d,p)}catch(A){}if(h)for(var I in h.contents)throw new g.ErrnoError(55)}delete a.parent.contents[a.name],a.parent.timestamp=Date.now(),a.name=p,d.contents[p]=a,d.timestamp=a.parent.timestamp,a.parent=d},unlink(a,d){delete a.contents[d],a.timestamp=Date.now()},rmdir(a,d){var p=g.lookupNode(a,d);for(var h in p.contents)throw new g.ErrnoError(55);delete a.contents[d],a.timestamp=Date.now()},readdir(a){var d=[".",".."];for(var p in a.contents)a.contents.hasOwnProperty(p)&&d.push(p);return d},symlink(a,d,p){var h=Ae.createNode(a,d,41471,0);return h.link=p,h},readlink(a){if(!g.isLink(a.mode))throw new g.ErrnoError(28);return a.link}},stream_ops:{read(a,d,p,h,I){var A=a.node.contents;if(I>=a.node.usedBytes)return 0;var b=Math.min(a.node.usedBytes-I,h);if(b>8&&A.subarray)d.set(A.subarray(I,I+b),p);else for(var R=0;R<b;R++)d[p+R]=A[I+R];return b},write(a,d,p,h,I,A){if(!h)return 0;var b=a.node;if(b.timestamp=Date.now(),d.subarray&&(!b.contents||b.contents.subarray)){if(A)return b.contents=d.subarray(p,p+h),b.usedBytes=h,h;if(b.usedBytes===0&&I===0)return b.contents=d.slice(p,p+h),b.usedBytes=h,h;if(I+h<=b.usedBytes)return b.contents.set(d.subarray(p,p+h),I),h}if(Ae.expandFileStorage(b,I+h),b.contents.subarray&&d.subarray)b.contents.set(d.subarray(p,p+h),I);else for(var R=0;R<h;R++)b.contents[I+R]=d[p+R];return b.usedBytes=Math.max(b.usedBytes,I+h),h},llseek(a,d,p){var h=d;if(p===1?h+=a.position:p===2&&g.isFile(a.node.mode)&&(h+=a.node.usedBytes),h<0)throw new g.ErrnoError(28);return h},allocate(a,d,p){Ae.expandFileStorage(a.node,d+p),a.node.usedBytes=Math.max(a.node.usedBytes,d+p)},mmap(a,d,p,h,I){if(!g.isFile(a.node.mode))throw new g.ErrnoError(43);var A,b,R=a.node.contents;if(2&I||R.buffer!==ee.buffer){if((p>0||p+d<R.length)&&(R=R.subarray?R.subarray(p,p+d):Array.prototype.slice.call(R,p,p+d)),b=!0,!(A=En()))throw new g.ErrnoError(48);ee.set(R,A)}else b=!1,A=R.byteOffset;return{ptr:A,allocated:b}},msync:(a,d,p,h,I)=>(Ae.stream_ops.write(a,d,0,h,p,!1),0)}},Uu=(a,d,p,h)=>{var I=h?"":`al ${a}`;n(a,A=>{var b;b=`Loading data file "${a}" failed (no arrayBuffer).`,A||Or(b),d(new Uint8Array(A)),I&&To()},A=>{if(!p)throw`Loading data file "${a}" failed.`;p()}),I&&ls()},Vu=o.preloadPlugins||[];function Zr(a,d){var p=0;return a&&(p|=365),d&&(p|=146),p}var g={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(a,d={})=>{if(!(a=qt.resolve(a)))return{path:"",node:null};if((d=Object.assign({follow_mount:!0,recurse_count:0},d)).recurse_count>8)throw new g.ErrnoError(32);for(var p=a.split("/").filter(x=>!!x),h=g.root,I="/",A=0;A<p.length;A++){var b=A===p.length-1;if(b&&d.parent)break;if(h=g.lookupNode(h,p[A]),I=pe.join2(I,p[A]),g.isMountpoint(h)&&(!b||b&&d.follow_mount)&&(h=h.mounted.root),!b||d.follow)for(var R=0;g.isLink(h.mode);){var L=g.readlink(I);if(I=qt.resolve(pe.dirname(I),L),h=g.lookupPath(I,{recurse_count:d.recurse_count+1}).node,R++>40)throw new g.ErrnoError(32)}}return{path:I,node:h}},getPath:a=>{for(var d;;){if(g.isRoot(a)){var p=a.mount.mountpoint;return d?p[p.length-1]!=="/"?`${p}/${d}`:p+d:p}d=d?`${a.name}/${d}`:a.name,a=a.parent}},hashName:(a,d)=>{for(var p=0,h=0;h<d.length;h++)p=(p<<5)-p+d.charCodeAt(h)|0;return(a+p>>>0)%g.nameTable.length},hashAddNode:a=>{var d=g.hashName(a.parent.id,a.name);a.name_next=g.nameTable[d],g.nameTable[d]=a},hashRemoveNode:a=>{var d=g.hashName(a.parent.id,a.name);if(g.nameTable[d]===a)g.nameTable[d]=a.name_next;else for(var p=g.nameTable[d];p;){if(p.name_next===a){p.name_next=a.name_next;break}p=p.name_next}},lookupNode:(a,d)=>{var p=g.mayLookup(a);if(p)throw new g.ErrnoError(p,a);for(var h=g.hashName(a.id,d),I=g.nameTable[h];I;I=I.name_next){var A=I.name;if(I.parent.id===a.id&&A===d)return I}return g.lookup(a,d)},createNode:(a,d,p,h)=>{var I=new g.FSNode(a,d,p,h);return g.hashAddNode(I),I},destroyNode:a=>{g.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 d=["r","w","rw"][3&a];return 512&a&&(d+="w"),d},nodePermissions:(a,d)=>g.ignorePermissions||(!d.includes("r")||292&a.mode)&&(!d.includes("w")||146&a.mode)&&(!d.includes("x")||73&a.mode)?0:2,mayLookup:a=>{var d=g.nodePermissions(a,"x");return d||(a.node_ops.lookup?0:2)},mayCreate:(a,d)=>{try{return g.lookupNode(a,d),20}catch(p){}return g.nodePermissions(a,"wx")},mayDelete:(a,d,p)=>{var h;try{h=g.lookupNode(a,d)}catch(A){return A.errno}var I=g.nodePermissions(a,"wx");if(I)return I;if(p){if(!g.isDir(h.mode))return 54;if(g.isRoot(h)||g.getPath(h)===g.cwd())return 10}else if(g.isDir(h.mode))return 31;return 0},mayOpen:(a,d)=>a?g.isLink(a.mode)?32:g.isDir(a.mode)&&(g.flagsToPermissionString(d)!=="r"||512&d)?31:g.nodePermissions(a,g.flagsToPermissionString(d)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var a=0;a<=g.MAX_OPEN_FDS;a++)if(!g.streams[a])return a;throw new g.ErrnoError(33)},getStreamChecked:a=>{var d=g.getStream(a);if(!d)throw new g.ErrnoError(8);return d},getStream:a=>g.streams[a],createStream:(a,d=-1)=>(g.FSStream||(g.FSStream=function(){this.shared={}},g.FSStream.prototype={},Object.defineProperties(g.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 g.FSStream,a),d==-1&&(d=g.nextfd()),a.fd=d,g.streams[d]=a,a),closeStream:a=>{g.streams[a]=null},chrdev_stream_ops:{open:a=>{var d=g.getDevice(a.node.rdev);a.stream_ops=d.stream_ops,a.stream_ops.open&&a.stream_ops.open(a)},llseek:()=>{throw new g.ErrnoError(70)}},major:a=>a>>8,minor:a=>255&a,makedev:(a,d)=>a<<8|d,registerDevice:(a,d)=>{g.devices[a]={stream_ops:d}},getDevice:a=>g.devices[a],getMounts:a=>{for(var d=[],p=[a];p.length;){var h=p.pop();d.push(h),p.push.apply(p,h.mounts)}return d},syncfs:(a,d)=>{typeof a=="function"&&(d=a,a=!1),g.syncFSRequests++,g.syncFSRequests>1&&M(`warning: ${g.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var p=g.getMounts(g.root.mount),h=0;function I(b){return g.syncFSRequests--,d(b)}function A(b){if(b)return A.errored?void 0:(A.errored=!0,I(b));++h>=p.length&&I(null)}p.forEach(b=>{if(!b.type.syncfs)return A(null);b.type.syncfs(b,a,A)})},mount:(a,d,p)=>{var h,I=p==="/",A=!p;if(I&&g.root)throw new g.ErrnoError(10);if(!I&&!A){var b=g.lookupPath(p,{follow_mount:!1});if(p=b.path,h=b.node,g.isMountpoint(h))throw new g.ErrnoError(10);if(!g.isDir(h.mode))throw new g.ErrnoError(54)}var R={type:a,opts:d,mountpoint:p,mounts:[]},L=a.mount(R);return L.mount=R,R.root=L,I?g.root=L:h&&(h.mounted=R,h.mount&&h.mount.mounts.push(R)),L},unmount:a=>{var d=g.lookupPath(a,{follow_mount:!1});if(!g.isMountpoint(d.node))throw new g.ErrnoError(28);var p=d.node,h=p.mounted,I=g.getMounts(h);Object.keys(g.nameTable).forEach(b=>{for(var R=g.nameTable[b];R;){var L=R.name_next;I.includes(R.mount)&&g.destroyNode(R),R=L}}),p.mounted=null;var A=p.mount.mounts.indexOf(h);p.mount.mounts.splice(A,1)},lookup:(a,d)=>a.node_ops.lookup(a,d),mknod:(a,d,p)=>{var h=g.lookupPath(a,{parent:!0}).node,I=pe.basename(a);if(!I||I==="."||I==="..")throw new g.ErrnoError(28);var A=g.mayCreate(h,I);if(A)throw new g.ErrnoError(A);if(!h.node_ops.mknod)throw new g.ErrnoError(63);return h.node_ops.mknod(h,I,d,p)},create:(a,d)=>(d=d!==void 0?d:438,d&=4095,d|=32768,g.mknod(a,d,0)),mkdir:(a,d)=>(d=d!==void 0?d:511,d&=1023,d|=16384,g.mknod(a,d,0)),mkdirTree:(a,d)=>{for(var p=a.split("/"),h="",I=0;I<p.length;++I)if(p[I]){h+="/"+p[I];try{g.mkdir(h,d)}catch(A){if(A.errno!=20)throw A}}},mkdev:(a,d,p)=>(p===void 0&&(p=d,d=438),d|=8192,g.mknod(a,d,p)),symlink:(a,d)=>{if(!qt.resolve(a))throw new g.ErrnoError(44);var p=g.lookupPath(d,{parent:!0}).node;if(!p)throw new g.ErrnoError(44);var h=pe.basename(d),I=g.mayCreate(p,h);if(I)throw new g.ErrnoError(I);if(!p.node_ops.symlink)throw new g.ErrnoError(63);return p.node_ops.symlink(p,h,a)},rename:(a,d)=>{var p,h,I=pe.dirname(a),A=pe.dirname(d),b=pe.basename(a),R=pe.basename(d);if(p=g.lookupPath(a,{parent:!0}).node,h=g.lookupPath(d,{parent:!0}).node,!p||!h)throw new g.ErrnoError(44);if(p.mount!==h.mount)throw new g.ErrnoError(75);var L,x=g.lookupNode(p,b),Y=qt.relative(a,A);if(Y.charAt(0)!==".")throw new g.ErrnoError(28);if((Y=qt.relative(d,I)).charAt(0)!==".")throw new g.ErrnoError(55);try{L=g.lookupNode(h,R)}catch(ie){}if(x!==L){var se=g.isDir(x.mode),ne=g.mayDelete(p,b,se);if(ne)throw new g.ErrnoError(ne);if(ne=L?g.mayDelete(h,R,se):g.mayCreate(h,R))throw new g.ErrnoError(ne);if(!p.node_ops.rename)throw new g.ErrnoError(63);if(g.isMountpoint(x)||L&&g.isMountpoint(L))throw new g.ErrnoError(10);if(h!==p&&(ne=g.nodePermissions(p,"w")))throw new g.ErrnoError(ne);g.hashRemoveNode(x);try{p.node_ops.rename(x,h,R)}catch(ie){throw ie}finally{g.hashAddNode(x)}}},rmdir:a=>{var d=g.lookupPath(a,{parent:!0}).node,p=pe.basename(a),h=g.lookupNode(d,p),I=g.mayDelete(d,p,!0);if(I)throw new g.ErrnoError(I);if(!d.node_ops.rmdir)throw new g.ErrnoError(63);if(g.isMountpoint(h))throw new g.ErrnoError(10);d.node_ops.rmdir(d,p),g.destroyNode(h)},readdir:a=>{var d=g.lookupPath(a,{follow:!0}).node;if(!d.node_ops.readdir)throw new g.ErrnoError(54);return d.node_ops.readdir(d)},unlink:a=>{var d=g.lookupPath(a,{parent:!0}).node;if(!d)throw new g.ErrnoError(44);var p=pe.basename(a),h=g.lookupNode(d,p),I=g.mayDelete(d,p,!1);if(I)throw new g.ErrnoError(I);if(!d.node_ops.unlink)throw new g.ErrnoError(63);if(g.isMountpoint(h))throw new g.ErrnoError(10);d.node_ops.unlink(d,p),g.destroyNode(h)},readlink:a=>{var d=g.lookupPath(a).node;if(!d)throw new g.ErrnoError(44);if(!d.node_ops.readlink)throw new g.ErrnoError(28);return qt.resolve(g.getPath(d.parent),d.node_ops.readlink(d))},stat:(a,d)=>{var p=g.lookupPath(a,{follow:!d}).node;if(!p)throw new g.ErrnoError(44);if(!p.node_ops.getattr)throw new g.ErrnoError(63);return p.node_ops.getattr(p)},lstat:a=>g.stat(a,!0),chmod:(a,d,p)=>{var h;if(typeof a=="string"?h=g.lookupPath(a,{follow:!p}).node:h=a,!h.node_ops.setattr)throw new g.ErrnoError(63);h.node_ops.setattr(h,{mode:4095&d|-4096&h.mode,timestamp:Date.now()})},lchmod:(a,d)=>{g.chmod(a,d,!0)},fchmod:(a,d)=>{var p=g.getStreamChecked(a);g.chmod(p.node,d)},chown:(a,d,p,h)=>{var I;if(typeof a=="string"?I=g.lookupPath(a,{follow:!h}).node:I=a,!I.node_ops.setattr)throw new g.ErrnoError(63);I.node_ops.setattr(I,{timestamp:Date.now()})},lchown:(a,d,p)=>{g.chown(a,d,p,!0)},fchown:(a,d,p)=>{var h=g.getStreamChecked(a);g.chown(h.node,d,p)},truncate:(a,d)=>{if(d<0)throw new g.ErrnoError(28);var p;if(typeof a=="string"?p=g.lookupPath(a,{follow:!0}).node:p=a,!p.node_ops.setattr)throw new g.ErrnoError(63);if(g.isDir(p.mode))throw new g.ErrnoError(31);if(!g.isFile(p.mode))throw new g.ErrnoError(28);var h=g.nodePermissions(p,"w");if(h)throw new g.ErrnoError(h);p.node_ops.setattr(p,{size:d,timestamp:Date.now()})},ftruncate:(a,d)=>{var p=g.getStreamChecked(a);if(!(2097155&p.flags))throw new g.ErrnoError(28);g.truncate(p.node,d)},utime:(a,d,p)=>{var h=g.lookupPath(a,{follow:!0}).node;h.node_ops.setattr(h,{timestamp:Math.max(d,p)})},open:(a,d,p)=>{if(a==="")throw new g.ErrnoError(44);var h;if(p=p===void 0?438:p,p=64&(d=typeof d=="string"?function(R){var L={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[R];if(L===void 0)throw new Error(`Unknown file open mode: ${R}`);return L}(d):d)?4095&p|32768:0,typeof a=="object")h=a;else{a=pe.normalize(a);try{h=g.lookupPath(a,{follow:!(131072&d)}).node}catch(R){}}var I=!1;if(64&d)if(h){if(128&d)throw new g.ErrnoError(20)}else h=g.mknod(a,p,0),I=!0;if(!h)throw new g.ErrnoError(44);if(g.isChrdev(h.mode)&&(d&=-513),65536&d&&!g.isDir(h.mode))throw new g.ErrnoError(54);if(!I){var A=g.mayOpen(h,d);if(A)throw new g.ErrnoError(A)}512&d&&!I&&g.truncate(h,0),d&=-131713;var b=g.createStream({node:h,path:g.getPath(h),flags:d,seekable:!0,position:0,stream_ops:h.stream_ops,ungotten:[],error:!1});return b.stream_ops.open&&b.stream_ops.open(b),!o.logReadFiles||1&d||(g.readFiles||(g.readFiles={}),a in g.readFiles||(g.readFiles[a]=1)),b},close:a=>{if(g.isClosed(a))throw new g.ErrnoError(8);a.getdents&&(a.getdents=null);try{a.stream_ops.close&&a.stream_ops.close(a)}catch(d){throw d}finally{g.closeStream(a.fd)}a.fd=null},isClosed:a=>a.fd===null,llseek:(a,d,p)=>{if(g.isClosed(a))throw new g.ErrnoError(8);if(!a.seekable||!a.stream_ops.llseek)throw new g.ErrnoError(70);if(p!=0&&p!=1&&p!=2)throw new g.ErrnoError(28);return a.position=a.stream_ops.llseek(a,d,p),a.ungotten=[],a.position},read:(a,d,p,h,I)=>{if(h<0||I<0)throw new g.ErrnoError(28);if(g.isClosed(a))throw new g.ErrnoError(8);if((2097155&a.flags)==1)throw new g.ErrnoError(8);if(g.isDir(a.node.mode))throw new g.ErrnoError(31);if(!a.stream_ops.read)throw new g.ErrnoError(28);var A=I!==void 0;if(A){if(!a.seekable)throw new g.ErrnoError(70)}else I=a.position;var b=a.stream_ops.read(a,d,p,h,I);return A||(a.position+=b),b},write:(a,d,p,h,I,A)=>{if(h<0||I<0)throw new g.ErrnoError(28);if(g.isClosed(a))throw new g.ErrnoError(8);if(!(2097155&a.flags))throw new g.ErrnoError(8);if(g.isDir(a.node.mode))throw new g.ErrnoError(31);if(!a.stream_ops.write)throw new g.ErrnoError(28);a.seekable&&1024&a.flags&&g.llseek(a,0,2);var b=I!==void 0;if(b){if(!a.seekable)throw new g.ErrnoError(70)}else I=a.position;var R=a.stream_ops.write(a,d,p,h,I,A);return b||(a.position+=R),R},allocate:(a,d,p)=>{if(g.isClosed(a))throw new g.ErrnoError(8);if(d<0||p<=0)throw new g.ErrnoError(28);if(!(2097155&a.flags))throw new g.ErrnoError(8);if(!g.isFile(a.node.mode)&&!g.isDir(a.node.mode))throw new g.ErrnoError(43);if(!a.stream_ops.allocate)throw new g.ErrnoError(138);a.stream_ops.allocate(a,d,p)},mmap:(a,d,p,h,I)=>{if(2&h&&!(2&I)&&(2097155&a.flags)!=2)throw new g.ErrnoError(2);if((2097155&a.flags)==1)throw new g.ErrnoError(2);if(!a.stream_ops.mmap)throw new g.ErrnoError(43);return a.stream_ops.mmap(a,d,p,h,I)},msync:(a,d,p,h,I)=>a.stream_ops.msync?a.stream_ops.msync(a,d,p,h,I):0,munmap:a=>0,ioctl:(a,d,p)=>{if(!a.stream_ops.ioctl)throw new g.ErrnoError(59);return a.stream_ops.ioctl(a,d,p)},readFile:(a,d={})=>{if(d.flags=d.flags||0,d.encoding=d.encoding||"binary",d.encoding!=="utf8"&&d.encoding!=="binary")throw new Error(`Invalid encoding type "${d.encoding}"`);var p,h=g.open(a,d.flags),I=g.stat(a).size,A=new Uint8Array(I);return g.read(h,A,0,I,0),d.encoding==="utf8"?p=xt(A,0):d.encoding==="binary"&&(p=A),g.close(h),p},writeFile:(a,d,p={})=>{p.flags=p.flags||577;var h=g.open(a,p.flags,p.mode);if(typeof d=="string"){var I=new Uint8Array(Io(d)+1),A=So(d,I,0,I.length);g.write(h,I,0,A,void 0,p.canOwn)}else{if(!ArrayBuffer.isView(d))throw new Error("Unsupported data type");g.write(h,d,0,d.byteLength,void 0,p.canOwn)}g.close(h)},cwd:()=>g.currentPath,chdir:a=>{var d=g.lookupPath(a,{follow:!0});if(d.node===null)throw new g.ErrnoError(44);if(!g.isDir(d.node.mode))throw new g.ErrnoError(54);var p=g.nodePermissions(d.node,"x");if(p)throw new g.ErrnoError(p);g.currentPath=d.path},createDefaultDirectories:()=>{g.mkdir("/tmp"),g.mkdir("/home"),g.mkdir("/home/web_user")},createDefaultDevices:()=>{g.mkdir("/dev"),g.registerDevice(g.makedev(1,3),{read:()=>0,write:(h,I,A,b,R)=>b}),g.mkdev("/dev/null",g.makedev(1,3)),ce.register(g.makedev(5,0),ce.default_tty_ops),ce.register(g.makedev(6,0),ce.default_tty1_ops),g.mkdev("/dev/tty",g.makedev(5,0)),g.mkdev("/dev/tty1",g.makedev(6,0));var a=new Uint8Array(1024),d=0,p=()=>(d===0&&(d=fn(a).byteLength),a[--d]);g.createDevice("/dev","random",p),g.createDevice("/dev","urandom",p),g.mkdir("/dev/shm"),g.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{g.mkdir("/proc");var a=g.mkdir("/proc/self");g.mkdir("/proc/self/fd"),g.mount({mount:()=>{var d=g.createNode(a,"fd",16895,73);return d.node_ops={lookup:(p,h)=>{var I=+h,A=g.getStreamChecked(I),b={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>A.path}};return b.parent=b,b}},d}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?g.createDevice("/dev","stdin",o.stdin):g.symlink("/dev/tty","/dev/stdin"),o.stdout?g.createDevice("/dev","stdout",null,o.stdout):g.symlink("/dev/tty","/dev/stdout"),o.stderr?g.createDevice("/dev","stderr",null,o.stderr):g.symlink("/dev/tty1","/dev/stderr"),g.open("/dev/stdin",0),g.open("/dev/stdout",1),g.open("/dev/stderr",1)},ensureErrnoError:()=>{g.ErrnoError||(g.ErrnoError=function(a,d){this.name="ErrnoError",this.node=d,this.setErrno=function(p){this.errno=p},this.setErrno(a),this.message="FS error"},g.ErrnoError.prototype=new Error,g.ErrnoError.prototype.constructor=g.ErrnoError,[44].forEach(a=>{g.genericErrors[a]=new g.ErrnoError(a),g.genericErrors[a].stack="<generic error, no stack>"}))},staticInit:()=>{g.ensureErrnoError(),g.nameTable=new Array(4096),g.mount(Ae,{},"/"),g.createDefaultDirectories(),g.createDefaultDevices(),g.createSpecialDirectories(),g.filesystems={MEMFS:Ae}},init:(a,d,p)=>{g.init.initialized=!0,g.ensureErrnoError(),o.stdin=a||o.stdin,o.stdout=d||o.stdout,o.stderr=p||o.stderr,g.createStandardStreams()},quit:()=>{g.init.initialized=!1;for(var a=0;a<g.streams.length;a++){var d=g.streams[a];d&&g.close(d)}},findObject:(a,d)=>{var p=g.analyzePath(a,d);return p.exists?p.object:null},analyzePath:(a,d)=>{try{a=(h=g.lookupPath(a,{follow:!d})).path}catch(I){}var p={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var h=g.lookupPath(a,{parent:!0});p.parentExists=!0,p.parentPath=h.path,p.parentObject=h.node,p.name=pe.basename(a),h=g.lookupPath(a,{follow:!d}),p.exists=!0,p.path=h.path,p.object=h.node,p.name=h.node.name,p.isRoot=h.path==="/"}catch(I){p.error=I.errno}return p},createPath:(a,d,p,h)=>{a=typeof a=="string"?a:g.getPath(a);for(var I=d.split("/").reverse();I.length;){var A=I.pop();if(A){var b=pe.join2(a,A);try{g.mkdir(b)}catch(R){}a=b}}return b},createFile:(a,d,p,h,I)=>{var A=pe.join2(typeof a=="string"?a:g.getPath(a),d),b=Zr(h,I);return g.create(A,b)},createDataFile:(a,d,p,h,I,A)=>{var b=d;a&&(a=typeof a=="string"?a:g.getPath(a),b=d?pe.join2(a,d):a);var R=Zr(h,I),L=g.create(b,R);if(p){if(typeof p=="string"){for(var x=new Array(p.length),Y=0,se=p.length;Y<se;++Y)x[Y]=p.charCodeAt(Y);p=x}g.chmod(L,146|R);var ne=g.open(L,577);g.write(ne,p,0,p.length,0,A),g.close(ne),g.chmod(L,R)}return L},createDevice:(a,d,p,h)=>{var I=pe.join2(typeof a=="string"?a:g.getPath(a),d),A=Zr(!!p,!!h);g.createDevice.major||(g.createDevice.major=64);var b=g.makedev(g.createDevice.major++,0);return g.registerDevice(b,{open:R=>{R.seekable=!1},close:R=>{h&&h.buffer&&h.buffer.length&&h(10)},read:(R,L,x,Y,se)=>{for(var ne=0,ie=0;ie<Y;ie++){var ve;try{ve=p()}catch(Fe){throw new g.ErrnoError(29)}if(ve===void 0&&ne===0)throw new g.ErrnoError(6);if(ve==null)break;ne++,L[x+ie]=ve}return ne&&(R.node.timestamp=Date.now()),ne},write:(R,L,x,Y,se)=>{for(var ne=0;ne<Y;ne++)try{h(L[x+ne])}catch(ie){throw new g.ErrnoError(29)}return Y&&(R.node.timestamp=Date.now()),ne}}),g.mkdev(I,A,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=ms(s(a.url),!0),a.usedBytes=a.contents.length}catch(d){throw new g.ErrnoError(29)}},createLazyFile:(a,d,p,h,I)=>{function A(){this.lengthKnown=!1,this.chunks=[]}if(A.prototype.get=function(se){if(!(se>this.length-1||se<0)){var ne=se%this.chunkSize,ie=se/this.chunkSize|0;return this.getter(ie)[ne]}},A.prototype.setDataGetter=function(se){this.getter=se},A.prototype.cacheLength=function(){var se=new XMLHttpRequest;if(se.open("HEAD",p,!1),se.send(null),!(se.status>=200&&se.status<300||se.status===304))throw new Error("Couldn't load "+p+". Status: "+se.status);var ne,ie=Number(se.getResponseHeader("Content-length")),ve=(ne=se.getResponseHeader("Accept-Ranges"))&&ne==="bytes",Fe=(ne=se.getResponseHeader("Content-Encoding"))&&ne==="gzip",Me=1048576;ve||(Me=ie);var it=this;it.setDataGetter(Ke=>{var gt=Ke*Me,Wi=(Ke+1)*Me-1;if(Wi=Math.min(Wi,ie-1),it.chunks[Ke]===void 0&&(it.chunks[Ke]=((cr,Do)=>{if(cr>Do)throw new Error("invalid range ("+cr+", "+Do+") or no bytes requested!");if(Do>ie-1)throw new Error("only "+ie+" bytes available! programmer error!");var ut=new XMLHttpRequest;if(ut.open("GET",p,!1),ie!==Me&&ut.setRequestHeader("Range","bytes="+cr+"-"+Do),ut.responseType="arraybuffer",ut.overrideMimeType&&ut.overrideMimeType("text/plain; charset=x-user-defined"),ut.send(null),!(ut.status>=200&&ut.status<300||ut.status===304))throw new Error("Couldn't load "+p+". Status: "+ut.status);return ut.response!==void 0?new Uint8Array(ut.response||[]):ms(ut.responseText||"",!0)})(gt,Wi)),it.chunks[Ke]===void 0)throw new Error("doXHR failed!");return it.chunks[Ke]}),!Fe&&ie||(Me=ie=1,ie=this.getter(0).length,Me=ie,k("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=ie,this._chunkSize=Me,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!E)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var b=new A;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 L=g.createFile(a,d,R,h,I);R.contents?L.contents=R.contents:R.url&&(L.contents=null,L.url=R.url),Object.defineProperties(L,{usedBytes:{get:function(){return this.contents.length}}});var x={};function Y(se,ne,ie,ve,Fe){var Me=se.node.contents;if(Fe>=Me.length)return 0;var it=Math.min(Me.length-Fe,ve);if(Me.slice)for(var Ke=0;Ke<it;Ke++)ne[ie+Ke]=Me[Fe+Ke];else for(Ke=0;Ke<it;Ke++)ne[ie+Ke]=Me.get(Fe+Ke);return it}return Object.keys(L.stream_ops).forEach(se=>{var ne=L.stream_ops[se];x[se]=function(){return g.forceLoadFile(L),ne.apply(null,arguments)}}),x.read=(se,ne,ie,ve,Fe)=>(g.forceLoadFile(L),Y(se,ne,ie,ve,Fe)),x.mmap=(se,ne,ie,ve,Fe)=>{g.forceLoadFile(L);var Me=En();if(!Me)throw new g.ErrnoError(48);return Y(se,ee,Me,ne,ie),{ptr:Me,allocated:!0}},L.stream_ops=x,L}},Pi=(a,d)=>a?xt(me,a,d):"",O={DEFAULT_POLLMASK:5,calculateAt:function(a,d,p){if(pe.isAbs(d))return d;var h;if(a===-100?h=g.cwd():h=O.getStreamFromFD(a).path,d.length==0){if(!p)throw new g.ErrnoError(44);return h}return pe.join2(h,d)},doStat:function(a,d,p){try{var h=a(d)}catch(R){if(R&&R.node&&pe.normalize(d)!==pe.normalize(g.getPath(R.node)))return-54;throw R}J[p>>2]=h.dev,J[p+4>>2]=h.mode,Ue[p+8>>2]=h.nlink,J[p+12>>2]=h.uid,J[p+16>>2]=h.gid,J[p+20>>2]=h.rdev,Ze=[h.size>>>0,(Ee=h.size,+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[p+24>>2]=Ze[0],J[p+28>>2]=Ze[1],J[p+32>>2]=4096,J[p+36>>2]=h.blocks;var I=h.atime.getTime(),A=h.mtime.getTime(),b=h.ctime.getTime();return Ze=[Math.floor(I/1e3)>>>0,(Ee=Math.floor(I/1e3),+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[p+40>>2]=Ze[0],J[p+44>>2]=Ze[1],Ue[p+48>>2]=I%1e3*1e3,Ze=[Math.floor(A/1e3)>>>0,(Ee=Math.floor(A/1e3),+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[p+56>>2]=Ze[0],J[p+60>>2]=Ze[1],Ue[p+64>>2]=A%1e3*1e3,Ze=[Math.floor(b/1e3)>>>0,(Ee=Math.floor(b/1e3),+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[p+72>>2]=Ze[0],J[p+76>>2]=Ze[1],Ue[p+80>>2]=b%1e3*1e3,Ze=[h.ino>>>0,(Ee=h.ino,+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[p+88>>2]=Ze[0],J[p+92>>2]=Ze[1],0},doMsync:function(a,d,p,h,I){if(!g.isFile(d.node.mode))throw new g.ErrnoError(43);if(2&h)return 0;var A=me.slice(a,a+p);g.msync(d,A,I,p,h)},varargs:void 0,get:()=>(O.varargs+=4,J[O.varargs-4>>2]),getStr:a=>Pi(a),getStreamFromFD:function(a){return g.getStreamChecked(a)}};function Kr(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 Ja=void 0;function bt(a){for(var d="",p=a;me[p];)d+=Ja[me[p++]];return d}var ki={},ar={},ps={},Li=void 0;function Ve(a){throw new Li(a)}var za=void 0;function Yt(a){throw new za(a)}function Pr(a,d,p){function h(R){var L=p(R);L.length!==a.length&&Yt("Mismatched type converter count");for(var x=0;x<a.length;++x)Zt(a[x],L[x])}a.forEach(function(R){ps[R]=d});var I=new Array(d.length),A=[],b=0;d.forEach((R,L)=>{ar.hasOwnProperty(R)?I[L]=ar[R]:(A.push(R),ki.hasOwnProperty(R)||(ki[R]=[]),ki[R].push(()=>{I[L]=ar[R],++b===A.length&&h(I)}))}),A.length===0&&h(I)}function Zt(a,d,p={}){if(!("argPackAdvance"in d))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(h,I,A={}){var b=I.name;if(h||Ve(`type "${b}" must have a positive integer typeid pointer`),ar.hasOwnProperty(h)){if(A.ignoreDuplicateRegistrations)return;Ve(`Cannot register type '${b}' twice`)}if(ar[h]=I,delete ps[h],ki.hasOwnProperty(h)){var R=ki[h];delete ki[h],R.forEach(L=>L())}}(a,d,p)}function Xa(a){if(!(this instanceof fr)||!(a instanceof fr))return!1;for(var d=this.$$.ptrType.registeredClass,p=this.$$.ptr,h=a.$$.ptrType.registeredClass,I=a.$$.ptr;d.baseClass;)p=d.upcast(p),d=d.baseClass;for(;h.baseClass;)I=h.upcast(I),h=h.baseClass;return d===h&&p===I}function _n(a){Ve(a.$$.ptrType.registeredClass.name+" instance already deleted")}var yo=!1;function Qa(a){}function Ya(a){a.count.value-=1,a.count.value===0&&function(d){d.smartPtr?d.smartPtrType.rawDestructor(d.smartPtr):d.ptrType.registeredClass.rawDestructor(d.ptr)}(a)}function Za(a,d,p){if(d===p)return a;if(p.baseClass===void 0)return null;var h=Za(a,d,p.baseClass);return h===null?null:p.downcast(h)}var Ao={};function Fu(){return Object.keys(Ro).length}function $u(){var a=[];for(var d in Ro)Ro.hasOwnProperty(d)&&a.push(Ro[d]);return a}var bo=[];function Kt(){for(;bo.length;){var a=bo.pop();a.$$.deleteScheduled=!1,a.delete()}}var kr=void 0;function Ka(a){kr=a,bo.length&&kr&&kr(Kt)}var Ro={};function Ui(a,d){return d=function(p,h){for(h===void 0&&Ve("ptr should not be undefined");p.baseClass;)h=p.upcast(h),p=p.baseClass;return h}(a,d),Ro[d]}function vo(a,d){return d.ptrType&&d.ptr||Yt("makeClassHandle requires ptr and ptrType"),!!d.smartPtrType!=!!d.smartPtr&&Yt("Both smartPtrType and smartPtr must be specified"),d.count={value:1},Vi(Object.create(a,{$$:{value:d}}))}function ec(a){var d=this.getPointee(a);if(!d)return this.destructor(a),null;var p=Ui(this.registeredClass,d);if(p!==void 0){if(p.$$.count.value===0)return p.$$.ptr=d,p.$$.smartPtr=a,p.clone();var h=p.clone();return this.destructor(a),h}function I(){return this.isSmartPointer?vo(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:d,smartPtrType:this,smartPtr:a}):vo(this.registeredClass.instancePrototype,{ptrType:this,ptr:a})}var A,b=this.registeredClass.getActualType(d),R=Ao[b];if(!R)return I.call(this);A=this.isConst?R.constPointerType:R.pointerType;var L=Za(d,this.registeredClass,A.registeredClass);return L===null?I.call(this):this.isSmartPointer?vo(A.registeredClass.instancePrototype,{ptrType:A,ptr:L,smartPtrType:this,smartPtr:a}):vo(A.registeredClass.instancePrototype,{ptrType:A,ptr:L})}var Vi=function(a){return typeof FinalizationRegistry=="undefined"?(Vi=d=>d,a):(yo=new FinalizationRegistry(d=>{Ya(d.$$)}),Qa=d=>yo.unregister(d),(Vi=d=>{var p=d.$$;if(p.smartPtr){var h={$$:p};yo.register(d,h,d)}return d})(a))};function tc(){if(this.$$.ptr||_n(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var a,d=Vi(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 d.$$.count.value+=1,d.$$.deleteScheduled=!1,d}function Bu(){this.$$.ptr||_n(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ve("Object already scheduled for deletion"),Qa(this),Ya(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function rc(){return!this.$$.ptr}function ic(){return this.$$.ptr||_n(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ve("Object already scheduled for deletion"),bo.push(this),bo.length===1&&kr&&kr(Kt),this.$$.deleteScheduled=!0,this}function fr(){}function Pt(a){if(a===void 0)return"_unknown";var d=(a=a.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return d>=48&&d<=57?`_${a}`:a}function hs(a,d){return a=Pt(a),{[a]:function(){return d.apply(this,arguments)}}[a]}function oc(a,d,p){if(a[d].overloadTable===void 0){var h=a[d];a[d]=function(){return a[d].overloadTable.hasOwnProperty(arguments.length)||Ve(`Function '${p}' called with an invalid number of arguments (${arguments.length}) - expects one of (${a[d].overloadTable})!`),a[d].overloadTable[arguments.length].apply(this,arguments)},a[d].overloadTable=[],a[d].overloadTable[h.argCount]=h}}function fs(a,d,p,h,I,A,b,R){this.name=a,this.constructor=d,this.instancePrototype=p,this.rawDestructor=h,this.baseClass=I,this.getActualType=A,this.upcast=b,this.downcast=R,this.pureVirtualFunctions=[]}function Co(a,d,p){for(;d!==p;)d.upcast||Ve(`Expected null or instance of ${p.name}, got an instance of ${d.name}`),a=d.upcast(a),d=d.baseClass;return a}function Hu(a,d){if(d===null)return this.isReference&&Ve(`null is not a valid ${this.name}`),0;d.$$||Ve(`Cannot pass "${Ts(d)}" as a ${this.name}`),d.$$.ptr||Ve(`Cannot pass deleted object as a pointer of type ${this.name}`);var p=d.$$.ptrType.registeredClass;return Co(d.$$.ptr,p,this.registeredClass)}function Wu(a,d){var p;if(d===null)return this.isReference&&Ve(`null is not a valid ${this.name}`),this.isSmartPointer?(p=this.rawConstructor(),a!==null&&a.push(this.rawDestructor,p),p):0;d.$$||Ve(`Cannot pass "${Ts(d)}" as a ${this.name}`),d.$$.ptr||Ve(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&d.$$.ptrType.isConst&&Ve(`Cannot convert argument of type ${d.$$.smartPtrType?d.$$.smartPtrType.name:d.$$.ptrType.name} to parameter type ${this.name}`);var h=d.$$.ptrType.registeredClass;if(p=Co(d.$$.ptr,h,this.registeredClass),this.isSmartPointer)switch(d.$$.smartPtr===void 0&&Ve("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:d.$$.smartPtrType===this?p=d.$$.smartPtr:Ve(`Cannot convert argument of type ${d.$$.smartPtrType?d.$$.smartPtrType.name:d.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:p=d.$$.smartPtr;break;case 2:if(d.$$.smartPtrType===this)p=d.$$.smartPtr;else{var I=d.clone();p=this.rawShare(p,Bi.toHandle(function(){I.delete()})),a!==null&&a.push(this.rawDestructor,p)}break;default:Ve("Unsupporting sharing policy")}return p}function sc(a,d){if(d===null)return this.isReference&&Ve(`null is not a valid ${this.name}`),0;d.$$||Ve(`Cannot pass "${Ts(d)}" as a ${this.name}`),d.$$.ptr||Ve(`Cannot pass deleted object as a pointer of type ${this.name}`),d.$$.ptrType.isConst&&Ve(`Cannot convert argument of type ${d.$$.ptrType.name} to parameter type ${this.name}`);var p=d.$$.ptrType.registeredClass;return Co(d.$$.ptr,p,this.registeredClass)}function No(a){return this.fromWireType(J[a>>2])}function Gu(a){return this.rawGetPointee&&(a=this.rawGetPointee(a)),a}function nc(a){this.rawDestructor&&this.rawDestructor(a)}function ju(a){a!==null&&a.delete()}function gr(a,d,p,h,I,A,b,R,L,x,Y){this.name=a,this.registeredClass=d,this.isReference=p,this.isConst=h,this.isSmartPointer=I,this.pointeeType=A,this.sharingPolicy=b,this.rawGetPointee=R,this.rawConstructor=L,this.rawShare=x,this.rawDestructor=Y,I||d.baseClass!==void 0?this.toWireType=Wu:h?(this.toWireType=Hu,this.destructorFunction=null):(this.toWireType=sc,this.destructorFunction=null)}var gs=[],ac=a=>{var d=gs[a];return d||(a>=gs.length&&(gs.length=a+1),gs[a]=d=mn.get(a)),d},qu=(a,d,p)=>a.includes("j")?((h,I,A)=>{var b=o["dynCall_"+h];return A&&A.length?b.apply(null,[I].concat(A)):b.call(null,I)})(a,d,p):ac(d).apply(null,p);function Fi(a,d){var p,h,I,A=(a=bt(a)).includes("j")?(p=a,h=d,I=[],function(){return I.length=0,Object.assign(I,arguments),qu(p,h,I)}):ac(d);return typeof A!="function"&&Ve(`unknown function pointer with signature ${a}: ${d}`),A}var cc=void 0;function Es(a){var d=_r(a),p=bt(d);return Rt(d),p}function _s(a,d){var p=[],h={};throw d.forEach(function I(A){h[A]||ar[A]||(ps[A]?ps[A].forEach(I):(p.push(A),h[A]=!0))}),new cc(`${a}: `+p.map(Es).join([", "]))}function Tn(a,d){for(var p=[],h=0;h<a;h++)p.push(Ue[d+4*h>>2]);return p}function dc(a){for(;a.length;){var d=a.pop();a.pop()(d)}}function In(a,d){if(!(a instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof a} which is not a function`);var p=hs(a.name||"unknownFunctionName",function(){});p.prototype=a.prototype;var h=new p,I=a.apply(h,d);return I instanceof Object?I:h}function $i(a,d,p,h,I,A){var b=d.length;b<2&&Ve("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var R=d[1]!==null&&p!==null,L=!1,x=1;x<d.length;++x)if(d[x]!==null&&d[x].destructorFunction===void 0){L=!0;break}var Y=d[0].name!=="void",se="",ne="";for(x=0;x<b-2;++x)se+=(x!==0?", ":"")+"arg"+x,ne+=(x!==0?", ":"")+"arg"+x+"Wired";var ie=`
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
throwBindingError('function ${a} called with ${arguments.length} arguments, expected ${b-2} args!');
|
|
55
|
-
}`;L&&(ie+=`var destructors = [];
|
|
56
|
-
`);var ve=L?"destructors":"null",Fe=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],Me=[Ve,h,I,dc,d[0],d[1]];for(R&&(ie+="var thisWired = classParam.toWireType("+ve+`, this);
|
|
57
|
-
`),x=0;x<b-2;++x)ie+="var arg"+x+"Wired = argType"+x+".toWireType("+ve+", arg"+x+"); // "+d[x+2].name+`
|
|
58
|
-
`,Fe.push("argType"+x),Me.push(d[x+2]);if(R&&(ne="thisWired"+(ne.length>0?", ":"")+ne),ie+=(Y||A?"var rv = ":"")+"invoker(fn"+(ne.length>0?", ":"")+ne+`);
|
|
59
|
-
`,L)ie+=`runDestructors(destructors);
|
|
60
|
-
`;else for(x=R?1:2;x<d.length;++x){var it=x===1?"thisWired":"arg"+(x-2)+"Wired";d[x].destructorFunction!==null&&(ie+=it+"_dtor("+it+"); // "+d[x].name+`
|
|
61
|
-
`,Fe.push(it+"_dtor"),Me.push(d[x].destructorFunction))}return Y&&(ie+=`var ret = retType.fromWireType(rv);
|
|
62
|
-
return ret;
|
|
63
|
-
`),ie+=`}
|
|
64
|
-
`,Fe.push(ie),In(Function,Fe).apply(null,Me)}function uc(){this.allocated=[void 0],this.freelist=[]}var kt=new uc;function lc(a){a>=kt.reserved&&--kt.get(a).refcount==0&&kt.free(a)}function Er(){for(var a=0,d=kt.reserved;d<kt.allocated.length;++d)kt.allocated[d]!==void 0&&++a;return a}var Bi={toValue:a=>(a||Ve("Cannot use deleted val. handle = "+a),kt.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 kt.allocate({refcount:1,value:a})}}};function Ts(a){if(a===null)return"null";var d=typeof a;return d==="object"||d==="array"||d==="function"?a.toString():""+a}function mc(a,d){switch(d){case 2:return function(p){return this.fromWireType(_o[p>>2])};case 3:return function(p){return this.fromWireType(ln[p>>3])};default:throw new TypeError("Unknown float type: "+a)}}function pc(a,d,p){switch(d){case 0:return p?function(h){return ee[h]}:function(h){return me[h]};case 1:return p?function(h){return oe[h>>1]}:function(h){return Xe[h>>1]};case 2:return p?function(h){return J[h>>2]}:function(h){return Ue[h>>2]};default:throw new TypeError("Unknown integer type: "+a)}}var S=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,T=(a,d)=>{for(var p=a,h=p>>1,I=h+d/2;!(h>=I)&&Xe[h];)++h;if((p=h<<1)-a>32&&S)return S.decode(me.subarray(a,p));for(var A="",b=0;!(b>=d/2);++b){var R=oe[a+2*b>>1];if(R==0)break;A+=String.fromCharCode(R)}return A},C=(a,d,p)=>{if(p===void 0&&(p=2147483647),p<2)return 0;for(var h=d,I=(p-=2)<2*a.length?p/2:a.length,A=0;A<I;++A){var b=a.charCodeAt(A);oe[d>>1]=b,d+=2}return oe[d>>1]=0,d-h},w=a=>2*a.length,F=(a,d)=>{for(var p=0,h="";!(p>=d/4);){var I=J[a+4*p>>2];if(I==0)break;if(++p,I>=65536){var A=I-65536;h+=String.fromCharCode(55296|A>>10,56320|1023&A)}else h+=String.fromCharCode(I)}return h},H=(a,d,p)=>{if(p===void 0&&(p=2147483647),p<4)return 0;for(var h=d,I=h+p-4,A=0;A<a.length;++A){var b=a.charCodeAt(A);if(b>=55296&&b<=57343&&(b=65536+((1023&b)<<10)|1023&a.charCodeAt(++A)),J[d>>2]=b,(d+=4)+4>I)break}return J[d>>2]=0,d-h},G=a=>{for(var d=0,p=0;p<a.length;++p){var h=a.charCodeAt(p);h>=55296&&h<=57343&&++p,d+=4}return d},z={},K=[],W=[],he={},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",_:m||"./this.program"};for(var d in he)he[d]===void 0?delete a[d]:a[d]=he[d];var p=[];for(var d in a)p.push(`${d}=${a[d]}`);De.strings=p}return De.strings},Re,ge,we,rt=function(a,d,p,h){a||(a=this),this.parent=a,this.mount=a.mount,this.mounted=null,this.id=g.nextInode++,this.name=d,this.mode=p,this.node_ops={},this.stream_ops={},this.rdev=h},qe=365,pt=146;Object.defineProperties(rt.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&pt)===pt},set:function(a){a?this.mode|=pt:this.mode&=-147}},isFolder:{get:function(){return g.isDir(this.mode)}},isDevice:{get:function(){return g.isChrdev(this.mode)}}}),g.FSNode=rt,g.createPreloadedFile=function(a,d,p,h,I,A,b,R,L,x){var Y=d?qt.resolve(pe.join2(a,d)):a;function se(ne){function ie(ve){x&&x(),R||g.createDataFile(a,d,ve,h,I,L),A&&A(),To()}(function(ve,Fe,Me,it){typeof Browser!="undefined"&&Browser.init();var Ke=!1;return Vu.forEach(function(gt){Ke||gt.canHandle(Fe)&&(gt.handle(ve,Fe,Me,it),Ke=!0)}),Ke})(ne,Y,ie,()=>{b&&b(),To()})||ie(ne)}ls(),typeof p=="string"?Uu(p,ne=>se(ne),b):se(p)},g.staticInit(),function(){for(var a=new Array(256),d=0;d<256;++d)a[d]=String.fromCharCode(d);Ja=a}(),Li=o.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},za=o.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},fr.prototype.isAliasOf=Xa,fr.prototype.clone=tc,fr.prototype.delete=Bu,fr.prototype.isDeleted=rc,fr.prototype.deleteLater=ic,o.getInheritedInstanceCount=Fu,o.getLiveInheritedInstances=$u,o.flushPendingDeletes=Kt,o.setDelayFunction=Ka,gr.prototype.getPointee=Gu,gr.prototype.destructor=nc,gr.prototype.argPackAdvance=8,gr.prototype.readValueFromPointer=No,gr.prototype.deleteObject=ju,gr.prototype.fromWireType=ec,cc=o.UnboundTypeError=(Re=Error,(we=hs(ge="UnboundTypeError",function(a){this.name=ge,this.message=a;var d=new Error(a).stack;d!==void 0&&(this.stack=this.toString()+`
|
|
65
|
-
`+d.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Re.prototype),we.prototype.constructor=we,we.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},we),Object.assign(uc.prototype,{get(a){return this.allocated[a]},has(a){return this.allocated[a]!==void 0},allocate(a){var d=this.freelist.pop()||this.allocated.length;return this.allocated[d]=a,d},free(a){this.allocated[a]=void 0,this.freelist.push(a)}}),kt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),kt.reserved=kt.allocated.length,o.count_emval_handles=Er;var Je,Nt={p:function(a,d,p){throw new Oi(a).init(d,p),a},C:function(a,d,p){O.varargs=p;try{var h=O.getStreamFromFD(a);switch(d){case 0:return(I=O.get())<0?-28:g.createStream(h,I).fd;case 1:case 2:case 6:case 7:return 0;case 3:return h.flags;case 4:var I=O.get();return h.flags|=I,0;case 5:return I=O.get(),oe[I+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return A=28,J[Sn()>>2]=A,-1}}catch(b){if(g===void 0||b.name!=="ErrnoError")throw b;return-b.errno}var A},w:function(a,d,p,h){O.varargs=h;try{d=O.getStr(d),d=O.calculateAt(a,d);var I=h?O.get():0;return g.open(d,p,I).fd}catch(A){if(g===void 0||A.name!=="ErrnoError")throw A;return-A.errno}},t:function(a,d,p,h,I){},n:function(a,d,p,h,I){var A=Kr(p);Zt(a,{name:d=bt(d),fromWireType:function(b){return!!b},toWireType:function(b,R){return R?h:I},argPackAdvance:8,readValueFromPointer:function(b){var R;if(p===1)R=ee;else if(p===2)R=oe;else{if(p!==4)throw new TypeError("Unknown boolean type size: "+d);R=J}return this.fromWireType(R[b>>A])},destructorFunction:null})},r:function(a,d,p,h,I,A,b,R,L,x,Y,se,ne){Y=bt(Y),A=Fi(I,A),R&&(R=Fi(b,R)),x&&(x=Fi(L,x)),ne=Fi(se,ne);var ie=Pt(Y);(function(ve,Fe,Me){o.hasOwnProperty(ve)?((Me===void 0||o[ve].overloadTable!==void 0&&o[ve].overloadTable[Me]!==void 0)&&Ve(`Cannot register public name '${ve}' twice`),oc(o,ve,ve),o.hasOwnProperty(Me)&&Ve(`Cannot register multiple overloads of a function with the same number of arguments (${Me})!`),o[ve].overloadTable[Me]=Fe):(o[ve]=Fe,Me!==void 0&&(o[ve].numArguments=Me))})(ie,function(){_s(`Cannot construct ${Y} due to unbound types`,[h])}),Pr([a,d,p],h?[h]:[],function(ve){var Fe,Me;ve=ve[0],Me=h?(Fe=ve.registeredClass).instancePrototype:fr.prototype;var it=hs(ie,function(){if(Object.getPrototypeOf(this)!==Ke)throw new Li("Use 'new' to construct "+Y);if(gt.constructor_body===void 0)throw new Li(Y+" has no accessible constructor");var ut=gt.constructor_body[arguments.length];if(ut===void 0)throw new Li(`Tried to invoke ctor of ${Y} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(gt.constructor_body).toString()}) parameters instead!`);return ut.apply(this,arguments)}),Ke=Object.create(Me,{constructor:{value:it}});it.prototype=Ke;var gt=new fs(Y,it,Ke,ne,Fe,A,R,x);gt.baseClass&&(gt.baseClass.__derivedClasses===void 0&&(gt.baseClass.__derivedClasses=[]),gt.baseClass.__derivedClasses.push(gt));var Wi=new gr(Y,gt,!0,!1,!1),cr=new gr(Y+"*",gt,!1,!1,!1),Do=new gr(Y+" const*",gt,!1,!0,!1);return Ao[a]={pointerType:cr,constPointerType:Do},function(ut,qp,Ju){o.hasOwnProperty(ut)||Yt("Replacing nonexistant public symbol"),o[ut].overloadTable!==void 0&&Ju!==void 0?o[ut].overloadTable[Ju]=qp:(o[ut]=qp,o[ut].argCount=Ju)}(ie,it),[Wi,cr,Do]})},q:function(a,d,p,h,I,A){var b=Tn(d,p);I=Fi(h,I),Pr([],[a],function(R){var L=`constructor ${(R=R[0]).name}`;if(R.registeredClass.constructor_body===void 0&&(R.registeredClass.constructor_body=[]),R.registeredClass.constructor_body[d-1]!==void 0)throw new Li(`Cannot register multiple constructors with identical number of parameters (${d-1}) for class '${R.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return R.registeredClass.constructor_body[d-1]=()=>{_s(`Cannot construct ${R.name} due to unbound types`,b)},Pr([],b,function(x){return x.splice(1,0,null),R.registeredClass.constructor_body[d-1]=$i(L,x,null,I,A),[]}),[]})},d:function(a,d,p,h,I,A,b,R,L){var x=Tn(p,h);d=bt(d),A=Fi(I,A),Pr([],[a],function(Y){var se=`${(Y=Y[0]).name}.${d}`;function ne(){_s(`Cannot call ${se} due to unbound types`,x)}d.startsWith("@@")&&(d=Symbol[d.substring(2)]),R&&Y.registeredClass.pureVirtualFunctions.push(d);var ie=Y.registeredClass.instancePrototype,ve=ie[d];return ve===void 0||ve.overloadTable===void 0&&ve.className!==Y.name&&ve.argCount===p-2?(ne.argCount=p-2,ne.className=Y.name,ie[d]=ne):(oc(ie,d,se),ie[d].overloadTable[p-2]=ne),Pr([],x,function(Fe){var Me=$i(se,Fe,Y,A,b,L);return ie[d].overloadTable===void 0?(Me.argCount=p-2,ie[d]=Me):ie[d].overloadTable[p-2]=Me,[]}),[]})},D:function(a,d){Zt(a,{name:d=bt(d),fromWireType:function(p){var h=Bi.toValue(p);return lc(p),h},toWireType:function(p,h){return Bi.toHandle(h)},argPackAdvance:8,readValueFromPointer:No,destructorFunction:null})},k:function(a,d,p){var h=Kr(p);Zt(a,{name:d=bt(d),fromWireType:function(I){return I},toWireType:function(I,A){return A},argPackAdvance:8,readValueFromPointer:mc(d,h),destructorFunction:null})},c:function(a,d,p,h,I){d=bt(d),I===-1&&(I=4294967295);var A=Kr(p),b=x=>x;if(h===0){var R=32-8*p;b=x=>x<<R>>>R}var L=d.includes("unsigned");Zt(a,{name:d,fromWireType:b,toWireType:L?function(x,Y){return this.name,Y>>>0}:function(x,Y){return this.name,Y},argPackAdvance:8,readValueFromPointer:pc(d,A,h!==0),destructorFunction:null})},b:function(a,d,p){var h=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][d];function I(A){var b=Ue,R=b[A>>=2],L=b[A+1];return new h(b.buffer,L,R)}Zt(a,{name:p=bt(p),fromWireType:I,argPackAdvance:8,readValueFromPointer:I},{ignoreDuplicateRegistrations:!0})},j:function(a,d){var p=(d=bt(d))==="std::string";Zt(a,{name:d,fromWireType:function(h){var I,A=Ue[h>>2],b=h+4;if(p)for(var R=b,L=0;L<=A;++L){var x=b+L;if(L==A||me[x]==0){var Y=Pi(R,x-R);I===void 0?I=Y:(I+="\0",I+=Y),R=x+1}}else{var se=new Array(A);for(L=0;L<A;++L)se[L]=String.fromCharCode(me[b+L]);I=se.join("")}return Rt(h),I},toWireType:function(h,I){var A;I instanceof ArrayBuffer&&(I=new Uint8Array(I));var b=typeof I=="string";b||I instanceof Uint8Array||I instanceof Uint8ClampedArray||I instanceof Int8Array||Ve("Cannot pass non-string to std::string"),A=p&&b?Io(I):I.length;var R=Hi(4+A+1),L=R+4;if(Ue[R>>2]=A,p&&b)So(I,me,L,A+1);else if(b)for(var x=0;x<A;++x){var Y=I.charCodeAt(x);Y>255&&(Rt(L),Ve("String has UTF-16 code units that do not fit in 8 bits")),me[L+x]=Y}else for(x=0;x<A;++x)me[L+x]=I[x];return h!==null&&h.push(Rt,R),R},argPackAdvance:8,readValueFromPointer:No,destructorFunction:function(h){Rt(h)}})},f:function(a,d,p){var h,I,A,b,R;p=bt(p),d===2?(h=T,I=C,b=w,A=()=>Xe,R=1):d===4&&(h=F,I=H,b=G,A=()=>Ue,R=2),Zt(a,{name:p,fromWireType:function(L){for(var x,Y=Ue[L>>2],se=A(),ne=L+4,ie=0;ie<=Y;++ie){var ve=L+4+ie*d;if(ie==Y||se[ve>>R]==0){var Fe=h(ne,ve-ne);x===void 0?x=Fe:(x+="\0",x+=Fe),ne=ve+d}}return Rt(L),x},toWireType:function(L,x){typeof x!="string"&&Ve(`Cannot pass non-string to C++ string type ${p}`);var Y=b(x),se=Hi(4+Y+d);return Ue[se>>2]=Y>>R,I(x,se+4,Y+d),L!==null&&L.push(Rt,se),se},argPackAdvance:8,readValueFromPointer:No,destructorFunction:function(L){Rt(L)}})},o:function(a,d){Zt(a,{isVoid:!0,name:d=bt(d),argPackAdvance:0,fromWireType:function(){},toWireType:function(p,h){}})},g:function(a,d,p,h){var I,A;(a=K[a])(d=Bi.toValue(d),p=(A=z[I=p])===void 0?bt(I):A,null,h)},m:lc,l:function(a,d){var p=function(Fe,Me){for(var it,Ke,gt,Wi=new Array(Fe),cr=0;cr<Fe;++cr)Wi[cr]=(it=Ue[Me+4*cr>>2],Ke="parameter "+cr,gt=void 0,(gt=ar[it])===void 0&&Ve(Ke+" has unknown type "+Es(it)),gt);return Wi}(a,d),h=p[0],I=h.name+"_$"+p.slice(1).map(function(Fe){return Fe.name}).join("_")+"$",A=W[I];if(A!==void 0)return A;for(var b=["retType"],R=[h],L="",x=0;x<a-1;++x)L+=(x!==0?", ":"")+"arg"+x,b.push("argType"+x),R.push(p[1+x]);var Y="return function "+Pt("methodCaller_"+I)+`(handle, name, destructors, args) {
|
|
66
|
-
`,se=0;for(x=0;x<a-1;++x)Y+=" var arg"+x+" = argType"+x+".readValueFromPointer(args"+(se?"+"+se:"")+`);
|
|
67
|
-
`,se+=p[x+1].argPackAdvance;for(Y+=" var rv = handle[name]("+L+`);
|
|
68
|
-
`,x=0;x<a-1;++x)p[x+1].deleteObject&&(Y+=" argType"+x+".deleteObject(arg"+x+`);
|
|
69
|
-
`);h.isVoid||(Y+=` return retType.toWireType(destructors, rv);
|
|
70
|
-
`),Y+=`};
|
|
71
|
-
`,b.push(Y);var ne,ie,ve=In(Function,b).apply(null,R);return ne=ve,ie=K.length,K.push(ne),A=ie,W[I]=A,A},a:()=>{Or("")},e:function(){return Date.now()},v:()=>me.length,A:(a,d,p)=>me.copyWithin(a,d,d+p),u:a=>{me.length,Or("OOM")},y:(a,d)=>{var p=0;return De().forEach(function(h,I){var A=d+p;Ue[a+4*I>>2]=A,((b,R)=>{for(var L=0;L<b.length;++L)ee[0|R++]=b.charCodeAt(L);ee[0|R]=0})(h,A),p+=h.length+1}),0},z:(a,d)=>{var p=De();Ue[a>>2]=p.length;var h=0;return p.forEach(function(I){h+=I.length+1}),Ue[d>>2]=h,0},i:function(a){try{var d=O.getStreamFromFD(a);return g.close(d),0}catch(p){if(g===void 0||p.name!=="ErrnoError")throw p;return p.errno}},x:function(a,d){try{var p=O.getStreamFromFD(a),h=p.tty?2:g.isDir(p.mode)?3:g.isLink(p.mode)?7:4;return ee[d|0]=h,oe[d+2>>1]=0,Ze=[0,(Ee=0,+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[d+8>>2]=Ze[0],J[d+12>>2]=Ze[1],Ze=[0,(Ee=0,+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[d+16>>2]=Ze[0],J[d+20>>2]=Ze[1],0}catch(I){if(g===void 0||I.name!=="ErrnoError")throw I;return I.errno}},B:function(a,d,p,h){try{var I=((A,b,R,L)=>{for(var x=0,Y=0;Y<R;Y++){var se=Ue[b>>2],ne=Ue[b+4>>2];b+=8;var ie=g.read(A,ee,se,ne,L);if(ie<0)return-1;if(x+=ie,ie<ne)break;L!==void 0&&(L+=ie)}return x})(O.getStreamFromFD(a),d,p);return Ue[h>>2]=I,0}catch(A){if(g===void 0||A.name!=="ErrnoError")throw A;return A.errno}},s:function(a,d,p,h,I){var A,b,R=(b=p)+2097152>>>0<4194305-!!(A=d)?(A>>>0)+4294967296*b:NaN;try{if(isNaN(R))return 61;var L=O.getStreamFromFD(a);return g.llseek(L,R,h),Ze=[L.position>>>0,(Ee=L.position,+Math.abs(Ee)>=1?Ee>0?+Math.floor(Ee/4294967296)>>>0:~~+Math.ceil((Ee-+(~~Ee>>>0))/4294967296)>>>0:0)],J[I>>2]=Ze[0],J[I+4>>2]=Ze[1],L.getdents&&R===0&&h===0&&(L.getdents=null),0}catch(x){if(g===void 0||x.name!=="ErrnoError")throw x;return x.errno}},h:function(a,d,p,h){try{var I=((A,b,R,L)=>{for(var x=0,Y=0;Y<R;Y++){var se=Ue[b>>2],ne=Ue[b+4>>2];b+=8;var ie=g.write(A,ee,se,ne,L);if(ie<0)return-1;x+=ie,L!==void 0&&(L+=ie)}return x})(O.getStreamFromFD(a),d,p);return Ue[h>>2]=I,0}catch(A){if(g===void 0||A.name!=="ErrnoError")throw A;return A.errno}}},Hi=(function(){var a,d,p,h,I={a:Nt};function A(b,R){var L,x,Y=b.exports;return N=(B=Y).E,L=N.buffer,o.HEAP8=ee=new Int8Array(L),o.HEAP16=oe=new Int16Array(L),o.HEAP32=J=new Int32Array(L),o.HEAPU8=me=new Uint8Array(L),o.HEAPU16=Xe=new Uint16Array(L),o.HEAPU32=Ue=new Uint32Array(L),o.HEAPF32=_o=new Float32Array(L),o.HEAPF64=ln=new Float64Array(L),mn=B.H,x=B.F,us.unshift(x),To(),Y}if(ls(),o.instantiateWasm)try{return o.instantiateWasm(I,A)}catch(b){M("Module.instantiateWasm callback failed with error: "+b),r(b)}(a=v,d=Yr,p=I,h=function(b){A(b.instance)},a||typeof WebAssembly.instantiateStreaming!="function"||Ot(d)||typeof fetch!="function"?xr(d,p,h):fetch(d,{credentials:"same-origin"}).then(b=>WebAssembly.instantiateStreaming(b,p).then(h,function(R){return M("wasm streaming compile failed: "+R),M("falling back to ArrayBuffer instantiation"),xr(d,p,h)}))).catch(r)}(),a=>(Hi=B.G)(a)),Rt=a=>(Rt=B.I)(a),Sn=()=>(Sn=B.J)(),_r=a=>(_r=B.K)(a),yn=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=B.L)(),a=>(yn=B.M)(a));o.dynCall_jiji=(a,d,p,h,I)=>(o.dynCall_jiji=B.N)(a,d,p,h,I),o._ff_h264_cabac_tables=67061;function Is(){function a(){Je||(Je=!0,o.calledRun=!0,pn||(o.noFSInit||g.init.initialized||g.init(),g.ignorePermissions=!1,ce.init(),Mi(us),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)d=o.postRun.shift(),wi.unshift(d);var d;Mi(wi)}()))}nr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)d=o.preRun.shift(),Mr.unshift(d);var d;Mi(Mr)}(),nr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),a()},1)):a()))}if(Qr=function a(){Je||Is(),Je||(Qr=a)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Is(),t.ready}})(),rS=tS,iS=class extends Oa{constructor(i){super(rS,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)}},hO=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((S,T)=>{e=S,r=T});var s,n=Object.assign({},o),c=typeof window=="object",l=typeof importScripts=="function",m=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(c||l)&&(l?m=self.location.href:typeof document!="undefined"&&document.currentScript&&(m=document.currentScript.src),i&&(m=i),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",l&&(s=S=>{var T=new XMLHttpRequest;return T.open("GET",S,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}));var f,E=o.print||console.log.bind(console),_=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&&(f=o.wasmBinary);var v,k;o.noExitRuntime,typeof WebAssembly!="object"&&nr("no native wasm support detected");var M,N,B,ee,me,oe,Xe,J,Ue,_o=!1,ln=[],mn=[],pn=[],Mr=0,us=null,wi=null;function nr(S){o.onAbort&&o.onAbort(S),_(S="Aborted("+S+")"),_o=!0,S+=". Build with -sASSERTIONS for more info.";var T=new WebAssembly.RuntimeError(S);throw r(T),T}var te,Qr;function ls(S){return S.startsWith("data:application/octet-stream;base64,")}function To(S){if(S==te&&f)return new Uint8Array(f);if(s)return s(S);throw"both async and sync fetching of the wasm failed"}function Or(S,T,C){return function(w){return f||!c&&!l||typeof fetch!="function"?Promise.resolve().then(()=>To(w)):fetch(w,{credentials:"same-origin"}).then(F=>{if(!F.ok)throw"failed to load wasm binary file at '"+w+"'";return F.arrayBuffer()}).catch(()=>To(w))}(S).then(w=>WebAssembly.instantiate(w,T)).then(w=>w).then(C,w=>{_("failed to asynchronously prepare wasm: "+w),nr(w)})}ls(te="videodec_simd.wasm")||(Qr=te,te=o.locateFile?o.locateFile(Qr,m):m+Qr);var Yr=S=>{for(;S.length>0;)S.shift()(o)};function hn(S){this.excPtr=S,this.ptr=S-24,this.set_type=function(T){oe[this.ptr+4>>2]=T},this.get_type=function(){return oe[this.ptr+4>>2]},this.set_destructor=function(T){oe[this.ptr+8>>2]=T},this.get_destructor=function(){return oe[this.ptr+8>>2]},this.set_caught=function(T){T=T?1:0,M[this.ptr+12|0]=T},this.get_caught=function(){return M[this.ptr+12|0]!=0},this.set_rethrown=function(T){T=T?1:0,M[this.ptr+13|0]=T},this.get_rethrown=function(){return M[this.ptr+13|0]!=0},this.init=function(T,C){this.set_adjusted_ptr(0),this.set_type(T),this.set_destructor(C)},this.set_adjusted_ptr=function(T){oe[this.ptr+16>>2]=T},this.get_adjusted_ptr=function(){return oe[this.ptr+16>>2]},this.get_exception_ptr=function(){if(mc(this.get_type()))return oe[this.excPtr>>2];var T=this.get_adjusted_ptr();return T!==0?T:this.excPtr}}function Ee(S){switch(S){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${S}`)}}var Ze=void 0;function Ot(S){for(var T="",C=S;N[C];)T+=Ze[N[C++]];return T}var j={},xr={},Mi={},Oi=void 0;function pe(S){throw new Oi(S)}var fn=void 0;function qt(S){throw new fn(S)}function xi(S,T,C){function w(z){var K=C(z);K.length!==S.length&&qt("Mismatched type converter count");for(var W=0;W<S.length;++W)xt(S[W],K[W])}S.forEach(function(z){Mi[z]=T});var F=new Array(T.length),H=[],G=0;T.forEach((z,K)=>{xr.hasOwnProperty(z)?F[K]=xr[z]:(H.push(z),j.hasOwnProperty(z)||(j[z]=[]),j[z].push(()=>{F[K]=xr[z],++G===H.length&&w(F)}))}),H.length===0&&w(F)}function xt(S,T,C={}){if(!("argPackAdvance"in T))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(w,F,H={}){var G=F.name;if(w||pe(`type "${G}" must have a positive integer typeid pointer`),xr.hasOwnProperty(w)){if(H.ignoreDuplicateRegistrations)return;pe(`Cannot register type '${G}' twice`)}if(xr[w]=F,delete Mi[w],j.hasOwnProperty(w)){var z=j[w];delete j[w],z.forEach(K=>K())}}(S,T,C)}function gn(S){if(!(this instanceof Yt)||!(S instanceof Yt))return!1;for(var T=this.$$.ptrType.registeredClass,C=this.$$.ptr,w=S.$$.ptrType.registeredClass,F=S.$$.ptr;T.baseClass;)C=T.upcast(C),T=T.baseClass;for(;w.baseClass;)F=w.upcast(F),w=w.baseClass;return T===w&&C===F}function Io(S){pe(S.$$.ptrType.registeredClass.name+" instance already deleted")}var So=!1;function ms(S){}function ce(S){S.count.value-=1,S.count.value===0&&function(T){T.smartPtr?T.smartPtrType.rawDestructor(T.smartPtr):T.ptrType.registeredClass.rawDestructor(T.ptr)}(S)}function En(S,T,C){if(T===C)return S;if(C.baseClass===void 0)return null;var w=En(S,T,C.baseClass);return w===null?null:C.downcast(w)}var Ae={};function Uu(){return Object.keys(Kr).length}function Vu(){var S=[];for(var T in Kr)Kr.hasOwnProperty(T)&&S.push(Kr[T]);return S}var Zr=[];function g(){for(;Zr.length;){var S=Zr.pop();S.$$.deleteScheduled=!1,S.delete()}}var Pi=void 0;function O(S){Pi=S,Zr.length&&Pi&&Pi(g)}var Kr={};function Ja(S,T){return T=function(C,w){for(w===void 0&&pe("ptr should not be undefined");C.baseClass;)w=C.upcast(w),C=C.baseClass;return w}(S,T),Kr[T]}function bt(S,T){return T.ptrType&&T.ptr||qt("makeClassHandle requires ptr and ptrType"),!!T.smartPtrType!=!!T.smartPtr&&qt("Both smartPtrType and smartPtr must be specified"),T.count={value:1},ar(Object.create(S,{$$:{value:T}}))}function ki(S){var T=this.getPointee(S);if(!T)return this.destructor(S),null;var C=Ja(this.registeredClass,T);if(C!==void 0){if(C.$$.count.value===0)return C.$$.ptr=T,C.$$.smartPtr=S,C.clone();var w=C.clone();return this.destructor(S),w}function F(){return this.isSmartPointer?bt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:T,smartPtrType:this,smartPtr:S}):bt(this.registeredClass.instancePrototype,{ptrType:this,ptr:S})}var H,G=this.registeredClass.getActualType(T),z=Ae[G];if(!z)return F.call(this);H=this.isConst?z.constPointerType:z.pointerType;var K=En(T,this.registeredClass,H.registeredClass);return K===null?F.call(this):this.isSmartPointer?bt(H.registeredClass.instancePrototype,{ptrType:H,ptr:K,smartPtrType:this,smartPtr:S}):bt(H.registeredClass.instancePrototype,{ptrType:H,ptr:K})}var ar=function(S){return typeof FinalizationRegistry=="undefined"?(ar=T=>T,S):(So=new FinalizationRegistry(T=>{ce(T.$$)}),ms=T=>So.unregister(T),(ar=T=>{var C=T.$$;if(C.smartPtr){var w={$$:C};So.register(T,w,T)}return T})(S))};function ps(){if(this.$$.ptr||Io(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var S,T=ar(Object.create(Object.getPrototypeOf(this),{$$:{value:(S=this.$$,{count:S.count,deleteScheduled:S.deleteScheduled,preservePointerOnDelete:S.preservePointerOnDelete,ptr:S.ptr,ptrType:S.ptrType,smartPtr:S.smartPtr,smartPtrType:S.smartPtrType})}}));return T.$$.count.value+=1,T.$$.deleteScheduled=!1,T}function Li(){this.$$.ptr||Io(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pe("Object already scheduled for deletion"),ms(this),ce(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Ve(){return!this.$$.ptr}function za(){return this.$$.ptr||Io(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&pe("Object already scheduled for deletion"),Zr.push(this),Zr.length===1&&Pi&&Pi(g),this.$$.deleteScheduled=!0,this}function Yt(){}function Pr(S){if(S===void 0)return"_unknown";var T=(S=S.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return T>=48&&T<=57?`_${S}`:S}function Zt(S,T){return S=Pr(S),{[S]:function(){return T.apply(this,arguments)}}[S]}function Xa(S,T,C){if(S[T].overloadTable===void 0){var w=S[T];S[T]=function(){return S[T].overloadTable.hasOwnProperty(arguments.length)||pe(`Function '${C}' called with an invalid number of arguments (${arguments.length}) - expects one of (${S[T].overloadTable})!`),S[T].overloadTable[arguments.length].apply(this,arguments)},S[T].overloadTable=[],S[T].overloadTable[w.argCount]=w}}function _n(S,T,C,w,F,H,G,z){this.name=S,this.constructor=T,this.instancePrototype=C,this.rawDestructor=w,this.baseClass=F,this.getActualType=H,this.upcast=G,this.downcast=z,this.pureVirtualFunctions=[]}function yo(S,T,C){for(;T!==C;)T.upcast||pe(`Expected null or instance of ${C.name}, got an instance of ${T.name}`),S=T.upcast(S),T=T.baseClass;return S}function Qa(S,T){if(T===null)return this.isReference&&pe(`null is not a valid ${this.name}`),0;T.$$||pe(`Cannot pass "${Co(T)}" as a ${this.name}`),T.$$.ptr||pe(`Cannot pass deleted object as a pointer of type ${this.name}`);var C=T.$$.ptrType.registeredClass;return yo(T.$$.ptr,C,this.registeredClass)}function Ya(S,T){var C;if(T===null)return this.isReference&&pe(`null is not a valid ${this.name}`),this.isSmartPointer?(C=this.rawConstructor(),S!==null&&S.push(this.rawDestructor,C),C):0;T.$$||pe(`Cannot pass "${Co(T)}" as a ${this.name}`),T.$$.ptr||pe(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&T.$$.ptrType.isConst&&pe(`Cannot convert argument of type ${T.$$.smartPtrType?T.$$.smartPtrType.name:T.$$.ptrType.name} to parameter type ${this.name}`);var w=T.$$.ptrType.registeredClass;if(C=yo(T.$$.ptr,w,this.registeredClass),this.isSmartPointer)switch(T.$$.smartPtr===void 0&&pe("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:T.$$.smartPtrType===this?C=T.$$.smartPtr:pe(`Cannot convert argument of type ${T.$$.smartPtrType?T.$$.smartPtrType.name:T.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:C=T.$$.smartPtr;break;case 2:if(T.$$.smartPtrType===this)C=T.$$.smartPtr;else{var F=T.clone();C=this.rawShare(C,fs.toHandle(function(){F.delete()})),S!==null&&S.push(this.rawDestructor,C)}break;default:pe("Unsupporting sharing policy")}return C}function Za(S,T){if(T===null)return this.isReference&&pe(`null is not a valid ${this.name}`),0;T.$$||pe(`Cannot pass "${Co(T)}" as a ${this.name}`),T.$$.ptr||pe(`Cannot pass deleted object as a pointer of type ${this.name}`),T.$$.ptrType.isConst&&pe(`Cannot convert argument of type ${T.$$.ptrType.name} to parameter type ${this.name}`);var C=T.$$.ptrType.registeredClass;return yo(T.$$.ptr,C,this.registeredClass)}function Ao(S){return this.fromWireType(me[S>>2])}function Fu(S){return this.rawGetPointee&&(S=this.rawGetPointee(S)),S}function $u(S){this.rawDestructor&&this.rawDestructor(S)}function bo(S){S!==null&&S.delete()}function Kt(S,T,C,w,F,H,G,z,K,W,he){this.name=S,this.registeredClass=T,this.isReference=C,this.isConst=w,this.isSmartPointer=F,this.pointeeType=H,this.sharingPolicy=G,this.rawGetPointee=z,this.rawConstructor=K,this.rawShare=W,this.rawDestructor=he,F||T.baseClass!==void 0?this.toWireType=Ya:w?(this.toWireType=Qa,this.destructorFunction=null):(this.toWireType=Za,this.destructorFunction=null)}var kr=[],Ka=S=>{var T=kr[S];return T||(S>=kr.length&&(kr.length=S+1),kr[S]=T=Ue.get(S)),T},Ro=(S,T,C)=>S.includes("j")?((w,F,H)=>{var G=o["dynCall_"+w];return H&&H.length?G.apply(null,[F].concat(H)):G.call(null,F)})(S,T,C):Ka(T).apply(null,C);function Ui(S,T){var C,w,F,H=(S=Ot(S)).includes("j")?(C=S,w=T,F=[],function(){return F.length=0,Object.assign(F,arguments),Ro(C,w,F)}):Ka(T);return typeof H!="function"&&pe(`unknown function pointer with signature ${S}: ${T}`),H}var vo=void 0;function ec(S){var T=Ts(S),C=Ot(T);return Er(T),C}function Vi(S,T){var C=[],w={};throw T.forEach(function F(H){w[H]||xr[H]||(Mi[H]?Mi[H].forEach(F):(C.push(H),w[H]=!0))}),new vo(`${S}: `+C.map(ec).join([", "]))}function tc(S,T){for(var C=[],w=0;w<S;w++)C.push(oe[T+4*w>>2]);return C}function Bu(S){for(;S.length;){var T=S.pop();S.pop()(T)}}function rc(S,T){if(!(S instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof S} which is not a function`);var C=Zt(S.name||"unknownFunctionName",function(){});C.prototype=S.prototype;var w=new C,F=S.apply(w,T);return F instanceof Object?F:w}function ic(S,T,C,w,F,H){var G=T.length;G<2&&pe("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var z=T[1]!==null&&C!==null,K=!1,W=1;W<T.length;++W)if(T[W]!==null&&T[W].destructorFunction===void 0){K=!0;break}var he=T[0].name!=="void",De="",Re="";for(W=0;W<G-2;++W)De+=(W!==0?", ":"")+"arg"+W,Re+=(W!==0?", ":"")+"arg"+W+"Wired";var ge=`
|
|
72
|
-
return function ${Pr(S)}(${De}) {
|
|
73
|
-
if (arguments.length !== ${G-2}) {
|
|
74
|
-
throwBindingError('function ${S} called with ${arguments.length} arguments, expected ${G-2} args!');
|
|
75
|
-
}`;K&&(ge+=`var destructors = [];
|
|
76
|
-
`);var we=K?"destructors":"null",rt=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],qe=[pe,w,F,Bu,T[0],T[1]];for(z&&(ge+="var thisWired = classParam.toWireType("+we+`, this);
|
|
77
|
-
`),W=0;W<G-2;++W)ge+="var arg"+W+"Wired = argType"+W+".toWireType("+we+", arg"+W+"); // "+T[W+2].name+`
|
|
78
|
-
`,rt.push("argType"+W),qe.push(T[W+2]);if(z&&(Re="thisWired"+(Re.length>0?", ":"")+Re),ge+=(he||H?"var rv = ":"")+"invoker(fn"+(Re.length>0?", ":"")+Re+`);
|
|
79
|
-
`,K)ge+=`runDestructors(destructors);
|
|
80
|
-
`;else for(W=z?1:2;W<T.length;++W){var pt=W===1?"thisWired":"arg"+(W-2)+"Wired";T[W].destructorFunction!==null&&(ge+=pt+"_dtor("+pt+"); // "+T[W].name+`
|
|
81
|
-
`,rt.push(pt+"_dtor"),qe.push(T[W].destructorFunction))}return he&&(ge+=`var ret = retType.fromWireType(rv);
|
|
82
|
-
return ret;
|
|
83
|
-
`),ge+=`}
|
|
84
|
-
`,rt.push(ge),rc(Function,rt).apply(null,qe)}function fr(){this.allocated=[void 0],this.freelist=[]}var Pt=new fr;function hs(S){S>=Pt.reserved&&--Pt.get(S).refcount==0&&Pt.free(S)}function oc(){for(var S=0,T=Pt.reserved;T<Pt.allocated.length;++T)Pt.allocated[T]!==void 0&&++S;return S}var fs={toValue:S=>(S||pe("Cannot use deleted val. handle = "+S),Pt.get(S).value),toHandle:S=>{switch(S){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Pt.allocate({refcount:1,value:S})}}};function Co(S){if(S===null)return"null";var T=typeof S;return T==="object"||T==="array"||T==="function"?S.toString():""+S}function Hu(S,T){switch(T){case 2:return function(C){return this.fromWireType(Xe[C>>2])};case 3:return function(C){return this.fromWireType(J[C>>3])};default:throw new TypeError("Unknown float type: "+S)}}function Wu(S,T,C){switch(T){case 0:return C?function(w){return M[w]}:function(w){return N[w]};case 1:return C?function(w){return B[w>>1]}:function(w){return ee[w>>1]};case 2:return C?function(w){return me[w>>2]}:function(w){return oe[w>>2]};default:throw new TypeError("Unknown integer type: "+S)}}var sc=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,No=(S,T,C)=>{for(var w=T+C,F=T;S[F]&&!(F>=w);)++F;if(F-T>16&&S.buffer&&sc)return sc.decode(S.subarray(T,F));for(var H="";T<F;){var G=S[T++];if(128&G){var z=63&S[T++];if((224&G)!=192){var K=63&S[T++];if((G=(240&G)==224?(15&G)<<12|z<<6|K:(7&G)<<18|z<<12|K<<6|63&S[T++])<65536)H+=String.fromCharCode(G);else{var W=G-65536;H+=String.fromCharCode(55296|W>>10,56320|1023&W)}}else H+=String.fromCharCode((31&G)<<6|z)}else H+=String.fromCharCode(G)}return H},Gu=(S,T)=>S?No(N,S,T):"",nc=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,ju=(S,T)=>{for(var C=S,w=C>>1,F=w+T/2;!(w>=F)&&ee[w];)++w;if((C=w<<1)-S>32&&nc)return nc.decode(N.subarray(S,C));for(var H="",G=0;!(G>=T/2);++G){var z=B[S+2*G>>1];if(z==0)break;H+=String.fromCharCode(z)}return H},gr=(S,T,C)=>{if(C===void 0&&(C=2147483647),C<2)return 0;for(var w=T,F=(C-=2)<2*S.length?C/2:S.length,H=0;H<F;++H){var G=S.charCodeAt(H);B[T>>1]=G,T+=2}return B[T>>1]=0,T-w},gs=S=>2*S.length,ac=(S,T)=>{for(var C=0,w="";!(C>=T/4);){var F=me[S+4*C>>2];if(F==0)break;if(++C,F>=65536){var H=F-65536;w+=String.fromCharCode(55296|H>>10,56320|1023&H)}else w+=String.fromCharCode(F)}return w},qu=(S,T,C)=>{if(C===void 0&&(C=2147483647),C<4)return 0;for(var w=T,F=w+C-4,H=0;H<S.length;++H){var G=S.charCodeAt(H);if(G>=55296&&G<=57343&&(G=65536+((1023&G)<<10)|1023&S.charCodeAt(++H)),me[T>>2]=G,(T+=4)+4>F)break}return me[T>>2]=0,T-w},Fi=S=>{for(var T=0,C=0;C<S.length;++C){var w=S.charCodeAt(C);w>=55296&&w<=57343&&++C,T+=4}return T},cc={},Es=[],_s=[],Tn;Tn=()=>performance.now();var dc,In,$i,uc=[null,[],[]];(function(){for(var S=new Array(256),T=0;T<256;++T)S[T]=String.fromCharCode(T);Ze=S})(),Oi=o.BindingError=class extends Error{constructor(S){super(S),this.name="BindingError"}},fn=o.InternalError=class extends Error{constructor(S){super(S),this.name="InternalError"}},Yt.prototype.isAliasOf=gn,Yt.prototype.clone=ps,Yt.prototype.delete=Li,Yt.prototype.isDeleted=Ve,Yt.prototype.deleteLater=za,o.getInheritedInstanceCount=Uu,o.getLiveInheritedInstances=Vu,o.flushPendingDeletes=g,o.setDelayFunction=O,Kt.prototype.getPointee=Fu,Kt.prototype.destructor=$u,Kt.prototype.argPackAdvance=8,Kt.prototype.readValueFromPointer=Ao,Kt.prototype.deleteObject=bo,Kt.prototype.fromWireType=ki,vo=o.UnboundTypeError=(dc=Error,($i=Zt(In="UnboundTypeError",function(S){this.name=In,this.message=S;var T=new Error(S).stack;T!==void 0&&(this.stack=this.toString()+`
|
|
85
|
-
`+T.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(dc.prototype),$i.prototype.constructor=$i,$i.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},$i),Object.assign(fr.prototype,{get(S){return this.allocated[S]},has(S){return this.allocated[S]!==void 0},allocate(S){var T=this.freelist.pop()||this.allocated.length;return this.allocated[T]=S,T},free(S){this.allocated[S]=void 0,this.freelist.push(S)}}),Pt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Pt.reserved=Pt.allocated.length,o.count_emval_handles=oc;var kt,lc={o:function(S,T,C){throw new hn(S).init(T,C),S},r:function(S,T,C,w,F){},m:function(S,T,C,w,F){var H=Ee(C);xt(S,{name:T=Ot(T),fromWireType:function(G){return!!G},toWireType:function(G,z){return z?w:F},argPackAdvance:8,readValueFromPointer:function(G){var z;if(C===1)z=M;else if(C===2)z=B;else{if(C!==4)throw new TypeError("Unknown boolean type size: "+T);z=me}return this.fromWireType(z[G>>H])},destructorFunction:null})},q:function(S,T,C,w,F,H,G,z,K,W,he,De,Re){he=Ot(he),H=Ui(F,H),z&&(z=Ui(G,z)),W&&(W=Ui(K,W)),Re=Ui(De,Re);var ge=Pr(he);(function(we,rt,qe){o.hasOwnProperty(we)?((qe===void 0||o[we].overloadTable!==void 0&&o[we].overloadTable[qe]!==void 0)&&pe(`Cannot register public name '${we}' twice`),Xa(o,we,we),o.hasOwnProperty(qe)&&pe(`Cannot register multiple overloads of a function with the same number of arguments (${qe})!`),o[we].overloadTable[qe]=rt):(o[we]=rt,qe!==void 0&&(o[we].numArguments=qe))})(ge,function(){Vi(`Cannot construct ${he} due to unbound types`,[w])}),xi([S,T,C],w?[w]:[],function(we){var rt,qe;we=we[0],qe=w?(rt=we.registeredClass).instancePrototype:Yt.prototype;var pt=Zt(ge,function(){if(Object.getPrototypeOf(this)!==Je)throw new Oi("Use 'new' to construct "+he);if(Nt.constructor_body===void 0)throw new Oi(he+" has no accessible constructor");var _r=Nt.constructor_body[arguments.length];if(_r===void 0)throw new Oi(`Tried to invoke ctor of ${he} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Nt.constructor_body).toString()}) parameters instead!`);return _r.apply(this,arguments)}),Je=Object.create(qe,{constructor:{value:pt}});pt.prototype=Je;var Nt=new _n(he,pt,Je,Re,rt,H,z,W);Nt.baseClass&&(Nt.baseClass.__derivedClasses===void 0&&(Nt.baseClass.__derivedClasses=[]),Nt.baseClass.__derivedClasses.push(Nt));var Hi=new Kt(he,Nt,!0,!1,!1),Rt=new Kt(he+"*",Nt,!1,!1,!1),Sn=new Kt(he+" const*",Nt,!1,!0,!1);return Ae[S]={pointerType:Rt,constPointerType:Sn},function(_r,yn,Is){o.hasOwnProperty(_r)||qt("Replacing nonexistant public symbol"),o[_r].overloadTable!==void 0&&Is!==void 0?o[_r].overloadTable[Is]=yn:(o[_r]=yn,o[_r].argCount=Is)}(ge,pt),[Hi,Rt,Sn]})},p:function(S,T,C,w,F,H){var G=tc(T,C);F=Ui(w,F),xi([],[S],function(z){var K=`constructor ${(z=z[0]).name}`;if(z.registeredClass.constructor_body===void 0&&(z.registeredClass.constructor_body=[]),z.registeredClass.constructor_body[T-1]!==void 0)throw new Oi(`Cannot register multiple constructors with identical number of parameters (${T-1}) for class '${z.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return z.registeredClass.constructor_body[T-1]=()=>{Vi(`Cannot construct ${z.name} due to unbound types`,G)},xi([],G,function(W){return W.splice(1,0,null),z.registeredClass.constructor_body[T-1]=ic(K,W,null,F,H),[]}),[]})},d:function(S,T,C,w,F,H,G,z,K){var W=tc(C,w);T=Ot(T),H=Ui(F,H),xi([],[S],function(he){var De=`${(he=he[0]).name}.${T}`;function Re(){Vi(`Cannot call ${De} due to unbound types`,W)}T.startsWith("@@")&&(T=Symbol[T.substring(2)]),z&&he.registeredClass.pureVirtualFunctions.push(T);var ge=he.registeredClass.instancePrototype,we=ge[T];return we===void 0||we.overloadTable===void 0&&we.className!==he.name&&we.argCount===C-2?(Re.argCount=C-2,Re.className=he.name,ge[T]=Re):(Xa(ge,T,De),ge[T].overloadTable[C-2]=Re),xi([],W,function(rt){var qe=ic(De,rt,he,H,G,K);return ge[T].overloadTable===void 0?(qe.argCount=C-2,ge[T]=qe):ge[T].overloadTable[C-2]=qe,[]}),[]})},u:function(S,T){xt(S,{name:T=Ot(T),fromWireType:function(C){var w=fs.toValue(C);return hs(C),w},toWireType:function(C,w){return fs.toHandle(w)},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:null})},k:function(S,T,C){var w=Ee(C);xt(S,{name:T=Ot(T),fromWireType:function(F){return F},toWireType:function(F,H){return H},argPackAdvance:8,readValueFromPointer:Hu(T,w),destructorFunction:null})},b:function(S,T,C,w,F){T=Ot(T),F===-1&&(F=4294967295);var H=Ee(C),G=W=>W;if(w===0){var z=32-8*C;G=W=>W<<z>>>z}var K=T.includes("unsigned");xt(S,{name:T,fromWireType:G,toWireType:K?function(W,he){return this.name,he>>>0}:function(W,he){return this.name,he},argPackAdvance:8,readValueFromPointer:Wu(T,H,w!==0),destructorFunction:null})},a:function(S,T,C){var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][T];function F(H){var G=oe,z=G[H>>=2],K=G[H+1];return new w(G.buffer,K,z)}xt(S,{name:C=Ot(C),fromWireType:F,argPackAdvance:8,readValueFromPointer:F},{ignoreDuplicateRegistrations:!0})},j:function(S,T){var C=(T=Ot(T))==="std::string";xt(S,{name:T,fromWireType:function(w){var F,H=oe[w>>2],G=w+4;if(C)for(var z=G,K=0;K<=H;++K){var W=G+K;if(K==H||N[W]==0){var he=Gu(z,W-z);F===void 0?F=he:(F+="\0",F+=he),z=W+1}}else{var De=new Array(H);for(K=0;K<H;++K)De[K]=String.fromCharCode(N[G+K]);F=De.join("")}return Er(w),F},toWireType:function(w,F){var H;F instanceof ArrayBuffer&&(F=new Uint8Array(F));var G=typeof F=="string";G||F instanceof Uint8Array||F instanceof Uint8ClampedArray||F instanceof Int8Array||pe("Cannot pass non-string to std::string"),H=C&&G?(De=>{for(var Re=0,ge=0;ge<De.length;++ge){var we=De.charCodeAt(ge);we<=127?Re++:we<=2047?Re+=2:we>=55296&&we<=57343?(Re+=4,++ge):Re+=3}return Re})(F):F.length;var z=Bi(4+H+1),K=z+4;if(oe[z>>2]=H,C&&G)((De,Re,ge,we)=>{if(!(we>0))return 0;for(var rt=ge,qe=ge+we-1,pt=0;pt<De.length;++pt){var Je=De.charCodeAt(pt);if(Je>=55296&&Je<=57343&&(Je=65536+((1023&Je)<<10)|1023&De.charCodeAt(++pt)),Je<=127){if(ge>=qe)break;Re[ge++]=Je}else if(Je<=2047){if(ge+1>=qe)break;Re[ge++]=192|Je>>6,Re[ge++]=128|63&Je}else if(Je<=65535){if(ge+2>=qe)break;Re[ge++]=224|Je>>12,Re[ge++]=128|Je>>6&63,Re[ge++]=128|63&Je}else{if(ge+3>=qe)break;Re[ge++]=240|Je>>18,Re[ge++]=128|Je>>12&63,Re[ge++]=128|Je>>6&63,Re[ge++]=128|63&Je}}Re[ge]=0})(F,N,K,H+1);else if(G)for(var W=0;W<H;++W){var he=F.charCodeAt(W);he>255&&(Er(K),pe("String has UTF-16 code units that do not fit in 8 bits")),N[K+W]=he}else for(W=0;W<H;++W)N[K+W]=F[W];return w!==null&&w.push(Er,z),z},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:function(w){Er(w)}})},g:function(S,T,C){var w,F,H,G,z;C=Ot(C),T===2?(w=ju,F=gr,G=gs,H=()=>ee,z=1):T===4&&(w=ac,F=qu,G=Fi,H=()=>oe,z=2),xt(S,{name:C,fromWireType:function(K){for(var W,he=oe[K>>2],De=H(),Re=K+4,ge=0;ge<=he;++ge){var we=K+4+ge*T;if(ge==he||De[we>>z]==0){var rt=w(Re,we-Re);W===void 0?W=rt:(W+="\0",W+=rt),Re=we+T}}return Er(K),W},toWireType:function(K,W){typeof W!="string"&&pe(`Cannot pass non-string to C++ string type ${C}`);var he=G(W),De=Bi(4+he+T);return oe[De>>2]=he>>z,F(W,De+4,he+T),K!==null&&K.push(Er,De),De},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:function(K){Er(K)}})},n:function(S,T){xt(S,{isVoid:!0,name:T=Ot(T),argPackAdvance:0,fromWireType:function(){},toWireType:function(C,w){}})},e:function(S,T,C,w){var F,H;(S=Es[S])(T=fs.toValue(T),C=(H=cc[F=C])===void 0?Ot(F):H,null,w)},l:hs,h:function(S,T){var C=function(rt,qe){for(var pt,Je,Nt,Hi=new Array(rt),Rt=0;Rt<rt;++Rt)Hi[Rt]=(pt=oe[qe+4*Rt>>2],Je="parameter "+Rt,Nt=void 0,(Nt=xr[pt])===void 0&&pe(Je+" has unknown type "+ec(pt)),Nt);return Hi}(S,T),w=C[0],F=w.name+"_$"+C.slice(1).map(function(rt){return rt.name}).join("_")+"$",H=_s[F];if(H!==void 0)return H;for(var G=["retType"],z=[w],K="",W=0;W<S-1;++W)K+=(W!==0?", ":"")+"arg"+W,G.push("argType"+W),z.push(C[1+W]);var he="return function "+Pr("methodCaller_"+F)+`(handle, name, destructors, args) {
|
|
86
|
-
`,De=0;for(W=0;W<S-1;++W)he+=" var arg"+W+" = argType"+W+".readValueFromPointer(args"+(De?"+"+De:"")+`);
|
|
87
|
-
`,De+=C[W+1].argPackAdvance;for(he+=" var rv = handle[name]("+K+`);
|
|
88
|
-
`,W=0;W<S-1;++W)C[W+1].deleteObject&&(he+=" argType"+W+".deleteObject(arg"+W+`);
|
|
89
|
-
`);w.isVoid||(he+=` return retType.toWireType(destructors, rv);
|
|
90
|
-
`),he+=`};
|
|
91
|
-
`,G.push(he);var Re,ge,we=rc(Function,G).apply(null,z);return Re=we,ge=Es.length,Es.push(Re),H=ge,_s[F]=H,H},f:()=>{nr("")},c:Tn,t:(S,T,C)=>N.copyWithin(S,T,T+C),s:S=>{N.length,nr("OOM")},i:(S,T,C,w)=>{for(var F,H,G,z=0,K=0;K<C;K++){var W=oe[T>>2],he=oe[T+4>>2];T+=8;for(var De=0;De<he;De++)F=S,H=N[W+De],G=void 0,G=uc[F],H===0||H===10?((F===1?E:_)(No(G,0)),G.length=0):G.push(H);z+=he}return oe[w>>2]=z,0}},Er=(function(){var S,T,C,w,F={a:lc};function H(G,z){var K,W,he=G.exports;return v=(k=he).v,K=v.buffer,o.HEAP8=M=new Int8Array(K),o.HEAP16=B=new Int16Array(K),o.HEAP32=me=new Int32Array(K),o.HEAPU8=N=new Uint8Array(K),o.HEAPU16=ee=new Uint16Array(K),o.HEAPU32=oe=new Uint32Array(K),o.HEAPF32=Xe=new Float32Array(K),o.HEAPF64=J=new Float64Array(K),Ue=k.z,W=k.w,mn.unshift(W),function(){if(Mr--,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),Mr==0&&(us!==null&&(clearInterval(us),us=null),wi)){var De=wi;wi=null,De()}}(),he}if(Mr++,o.monitorRunDependencies&&o.monitorRunDependencies(Mr),o.instantiateWasm)try{return o.instantiateWasm(F,H)}catch(G){_("Module.instantiateWasm callback failed with error: "+G),r(G)}(S=f,T=te,C=F,w=function(G){H(G.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ls(T)||typeof fetch!="function"?Or(T,C,w):fetch(T,{credentials:"same-origin"}).then(G=>WebAssembly.instantiateStreaming(G,C).then(w,function(z){return _("wasm streaming compile failed: "+z),_("falling back to ArrayBuffer instantiation"),Or(T,C,w)}))).catch(r)}(),S=>(Er=k.x)(S)),Bi=S=>(Bi=k.y)(S),Ts=S=>(Ts=k.A)(S),mc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=k.B)(),S=>(mc=k.C)(S));o.dynCall_jiji=(S,T,C,w,F)=>(o.dynCall_jiji=k.D)(S,T,C,w,F);function pc(){function S(){kt||(kt=!0,o.calledRun=!0,_o||(Yr(mn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)T=o.postRun.shift(),pn.unshift(T);var T;Yr(pn)}()))}Mr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),ln.unshift(T);var T;Yr(ln)}(),Mr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(wi=function S(){kt||pc(),kt||(wi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return pc(),t.ready}})();var oS="web.sdk.qcloud.com",sS=`https://${oS}/trtc/webrtc/v5/doc`,fO=`${sS}/zh-cn/`,ng=(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))(ng||{});var ag={"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}},gO=ag["480p_2"],EO=ag["120p_2"],eu={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"},_O=eu.MAIN,TO=eu.AUXILIARY,IO=eu.BIG,SO=eu.SMALL;var yO=Object.keys(ng);var AO=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function rg(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:bO}=Object.prototype,cg=class dg{constructor(t){this.core=t,wr(this,"contextMap",new Map),wr(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 dg.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new iS(Yd(Qd({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new on;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 c=this.core.room.videoManager.createDecodeContext(Yd(Qd({},t),{createDecoder:this.createDecoder}));return e(c.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,c),c.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=rg()-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,max:100}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100})}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(Yd(Qd({},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:c,endTime:l})=>{c>e.startPerformanceTime&&(s+=l===0?rg()-c:l-c)});let n=0;return o&&o.durationItemList.forEach(c=>{c.startTime>e.startPerformanceTime&&(n+=c.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};wr(cg,"Name","TRTCVideoDecoder");var up=cg;var Vg=ji(Zi());function lp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return xe((r,o)=>{let s=new WeakMap;return V.on(U.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let c=s.get(this);if(c||(c={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,c)),c.timestamp===0?c.timestamp=Date.now():Date.now()-c.timestamp>1e3&&(c.timestamp=Date.now(),c.callCountInSecond=0,c.totalSizeInSecond=0),e&&(c.totalSizeInSecond+=e(...n)),c.timestamp!==0&&Date.now()-c.timestamp<1e3&&(c.callCountInSecond>=i||c.totalSizeInSecond>t))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.CALL_FREQUENCY_LIMIT,data:{isTimes:c.callCountInSecond>=i,isSize:c.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});c.callCountInSecond++,r.call(this,...n)}})}var nS="2025-07-11 16:32:30",ug=!0,lg=function(){var i;if(ug){ug=!1,$.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Lr}/en/index.html`),console.info(`* Changelog: ${Lr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),$.info("TRTC Web SDK Version:",at),vr||$.debug("Build Time:",nS);let t=`UA: ${navigator.userAgent}
|
|
92
|
-
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Nl()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),$.info(t),$.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),$o().then(r=>{r&&$.info(yr)})}};var pr={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 le={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},hr=(O=>(O[O.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",O[O.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",O[O.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",O[O.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",O[O.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",O[O.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",O[O.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",O[O.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",O[O.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",O[O.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",O[O.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",O[O.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",O[O.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",O[O.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",O[O.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",O[O.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",O[O.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",O[O.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",O[O.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",O[O.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",O[O.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",O[O.INVALID_OPERATION=5100]="INVALID_OPERATION",O[O.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",O[O.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",O[O.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",O[O.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",O[O.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",O[O.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",O[O.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",O[O.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",O[O.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",O[O.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",O[O.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",O[O.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",O[O.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",O[O.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",O[O.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",O[O.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",O[O.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",O[O.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",O[O.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",O[O.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",O[O.DEVICE_ERROR=5300]="DEVICE_ERROR",O[O.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",O[O.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",O[O.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",O[O.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",O[O.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",O[O.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",O[O.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",O[O.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",O[O.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",O[O.SERVER_ERROR=5400]="SERVER_ERROR",O[O.NEED_TO_BUY=5401]="NEED_TO_BUY",O[O.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",O[O.OPERATION_FAILED=5500]="OPERATION_FAILED",O[O.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",O[O.REJOIN_FAILED=5502]="REJOIN_FAILED",O[O.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",O[O.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",O[O.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",O[O.OPERATION_ABORT=5998]="OPERATION_ABORT",O[O.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",O))(hr||{});function pg({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=hr[i];try{o=mg[s]}catch(n){o=mg.UNKNOWN_ERROR}return We(o)?r=o(t):Oe(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var mg=Te(X({},Xt),{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: ${ct(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: ${ct(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_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:i}){return`The type of target roomId must match the current roomId. Current room is using '${i}', but received '${i==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:i}){return`the target '${i}' must not be the same as the current '${i}'.`},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 or screen share 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=ss(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=ss(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=ss(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=ss(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=ss(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=ss(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=ss(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 ss(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var mp=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:c}){var m;let l;o?l=o:l=pg({code:e===le.SERVER_ERROR?e:r||e,params:X({fnName:n,error:c},s)});super(l);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=hr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=c,this.message=l,this.extraCode===5302&&((m=this.originError)!=null&&m.message.includes("system"))&&(this.handler=()=>{let f={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},E={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Fo?_.href=`ms-settings:privacy-${E[this.functionName]}`:br&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${f[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ue){let{stack:n}=e,c={code:le.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:c.code=le.INVALID_PARAMETER,c.message=e.message;break;case q.INVALID_OPERATION:c.code=le.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:c.code=le.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(c.extraCode=e.message.includes(Xt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:c.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:case q.SWITCH_ROOM_FAILED:c.code=le.SERVER_ERROR,c.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:c.code=le.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:c.code=5300,e.name&&(c.extraCode=aS(e.name));break;case q.UNKNOWN:break;default:c.code=le.OPERATION_FAILED}s=new i(c),n&&(s.stack+=n.substr(n.indexOf(`
|
|
93
|
-
`)))}else{if(e instanceof i)return e;s=new i({code:le.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function aS(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 ae=mp;function uo(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function ka(i){return i===pr.QOS_PREFERENCE_CLEAR?"detail":i===pr.QOS_PREFERENCE_SMOOTH?"motion":""}function sn(i,t){let e=t?tl:Nn;return ll(i)?X(X({},e),i):Ir[i]?Ir[i]:e}var hg={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},fg={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}}},nn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Oe(i)&&!document.getElementById(i))throw new ae({code:le.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},gg={name:"userId",required:!0,type:"string"},Eg={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[pr.AUDIO_PROFILE_STANDARD,pr.AUDIO_PROFILE_STANDARD_STEREO,pr.AUDIO_PROFILE_HIGH,pr.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function an(i,t){if(!i)throw new ae({code:le.INVALID_OPERATION,extraCode:5101,fnName:t})}function _g(i,t,e){if(!i)throw new ae({code:le.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function Tg(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new ae({code:le.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function Ig(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new ae({code:le.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var j0={type:"number",notLessThanZero:!0},cS=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function Sg(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!dd()){$.warn("small stream is not supported"),delete i.option.small;return}let t=sn(i.option.profile),e=sn(i.option.small,!0);if(!cS(t,e)){$.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(t)}, Small: ${JSON.stringify(e)}`),delete i.option.small;return}}var dS={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 ae({code:le.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Oe(i.roomId))throw new ae({code:le.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});Tg(i.roomId,e,t)}else if(i.strRoomId)Ig(i.strRoomId,e,t);else throw new ae({code:le.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:nn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:hg},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&gi())throw new ae({code:le.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&Sg(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Te(X({},nn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:hg},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&Sg(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Eg},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&gi())throw new ae({code:le.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Eg}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:nn,publish:{type:"boolean"},option:fg},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(gi())throw new ae({code:le.ENV_NOT_SUPPORTED,extraCode:5201});if(!da())throw new ae({code:le.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:nn,publish:{type:"boolean"},option:fg}},muteRemoteAudio:[gg,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[gg,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:nn,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){an(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(_g(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:le.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Te(X({},nn),{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){an(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(_g(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new ae({code:le.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!=="*"&&P(i.streamType))throw new ae({code:le.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){an(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(!ma)throw new ae({code:le.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new ae({code:le.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new ae({code:le.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:le.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});an(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 ae({code:le.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 ae({code:le.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new ae({code:le.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(an(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new ae({code:le.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(an(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new ae({code:le.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId&&this._room.useStringRoomId||!i.roomId&&i.strRoomId&&!this._room.useStringRoomId)throw new ae({code:le.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)Tg(i.roomId,e,t);else if(i.strRoomId)Ig(i.strRoomId,e,t);else throw new ae({code:le.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},At={TRTC:dS};var $t=class extends Error{};function uS(i,t){let e=Po(i);for(let r=0;r<t.length;r++)ur(e[r],t[r]);return e}function lS(i){this._resolve=Promise.resolve(i)}function mS(i){this._reject=Promise.reject(i)}var lo=class lo{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",uS);let r=lo.instances.get(t);r?r.set(e,this):lo.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=lo.instances.get(t);return r&&r.get(e)||new lo(t,e)}static gets(t,e){let r=lo.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=c=>{var l;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(l=this.currentOp)==null||l.action(),c},s=c=>{var l,m;throw this.ops.shift(),t===0&&((l=this.currentOp)==null?void 0:l.type)===2&&this.ops.shift().reject(new $t("start failed")),(m=this.currentOp)==null||m.action(),c},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:lS,reject:mS};try{switch(this.state){case 1:if(t===0)throw new $t("already started");break;case 4:if(t===2)throw new $t("not started");break;default:return this.cacheOp(n)}}catch(c){return Promise.reject(c)}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 $t("already start");break;case 3:switch(t.type){case 2:throw new $t("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new $t("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new $t("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 $t("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new $t("start not allowed after update");case 0:throw new $t("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new $t("keep start")),new $t("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(lo,"instances",new WeakMap);var vi=lo;var tu=new WeakMap,ru=(i,t)=>{if(t instanceof $t){let{stack:e}=t;t=new ae({code:le.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
94
|
-
`)))}throw t};function mo(i,t){return xe((e,r)=>function(...o){let s=vi.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(ru.bind(null,r))):e.apply(this,o)})}function ns(i,t){let{merge:e,debounce:r}=t||{};return xe((o,s)=>function(...n){let c=vi.get(this,typeof i=="string"?i:i.call(this,...n));if(!c)return o.apply(this,n);if(e&&(c.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:l,getKey:m}=r;return new Promise((f,E)=>{var k,M;let _=(k=tu.get(this))==null?void 0:k.get(m(...n));if(_){let{timeoutId:N,resolve:B}=_;clearTimeout(N),B()}let v=setTimeout(()=>{if(c.state===3||c.state===4)return f();c.action(2,o.bind(this),n).catch(ru.bind(null,s)).then(f,E)},l);tu.has(this)?(M=tu.get(this))==null||M.set(m(...n),{timeoutId:v,resolve:f}):tu.set(this,new Map([[m(...n),{timeoutId:v,resolve:f}]]))})}return c.action(2,o.bind(this),n).catch(ru.bind(null,s))})}function po(i){return xe((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(vi.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=vi.get(this,o);return s?s.action(3,t.bind(this),r).catch(ru.bind(null,e)):t.apply(this,r)})}var re={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"},yg=new Set([re.ERROR,re.AUTOPLAY_FAILED,re.KICKED_OUT,re.REMOTE_USER_ENTER,re.REMOTE_USER_EXIT,re.REMOTE_AUDIO_AVAILABLE,re.REMOTE_AUDIO_UNAVAILABLE,re.REMOTE_VIDEO_AVAILABLE,re.REMOTE_VIDEO_UNAVAILABLE,re.CONNECTION_STATE_CHANGED,re.PUBLISH_STATE_CHANGED,re.SCREEN_SHARE_STOPPED,re.DEVICE_CHANGED,re.FIRST_VIDEO_FRAME]);var hp={};ei(hp,{bytes2ms:()=>ah,calculateScaleResolutionDownNumber:()=>Nc,convertObjectNumberToInt:()=>Vn,copyProperties:()=>nh,deepClone:()=>Po,deepMerge:()=>ur,delay:()=>Fn,fibonacci:()=>ko,formatedTime:()=>bc,getConstructorName:()=>vs,getContainerFromElement:()=>fh,getEnv:()=>ih,getInternalVersion:()=>ph,getLoggerUrl:()=>si,getMediaStreamTrackInfo:()=>Cc,getMuteStateFromFlag:()=>Ln,getNetworkType:()=>xn,getNumNetworkType:()=>Ac,getReconnectionTimeout:()=>dh,getStringByteLength:()=>gh,getTurnServer:()=>hh,getUint32Version:()=>Rc,getValueType:()=>ct,getViewListFromView:()=>Ds,glog:()=>Pn,ipv4ToUint32:()=>Ns,isArray:()=>ot,isAudioWorkletSupported:()=>mh,isBoolean:()=>st,isConstructor:()=>Lo,isEmpty:()=>Cs,isFunction:()=>We,isLangChinese:()=>Sr,isMediaStreamTrack:()=>uh,isNumber:()=>ke,isObject:()=>er,isOverseaSdkAppId:()=>oi,isPlainObject:()=>Lt,isPortrait:()=>cl,isPromise:()=>Ji,isRemoteTrack:()=>lh,isRotate90Or270:()=>ni,isString:()=>Oe,isUndefined:()=>P,loadImage:()=>ws,ms2bytes:()=>ch,ms2samples:()=>al,normalizeUrl:()=>Uo,performanceNow:()=>Ie,promiseAny:()=>kn,samples2ms:()=>nl,setNetworkType:()=>sh,stringify:()=>dr,stringifyIncludeValue:()=>Un,throttlePromise:()=>vc});var Ep={};ei(Ep,{ScheduleRequestType:()=>bg,getAbilityConfig:()=>hS,getScheduleDomain:()=>su,isNeedToSchedule:()=>iu,scheduleProxy:()=>zr,sendScheduleRequest:()=>gp,setIsNeedToSchedule:()=>as,setScheduleProxy:()=>ou});var fp=null,iu=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ii).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
95
|
-
`));function as(i){st(i)&&i!==iu&&(iu=i,$.info(`setIsNeedToSchedule ${i}`))}V.on("28",()=>as(!0));V.on("63",()=>as(!0));V.on("84",()=>as(!0));V.on("201",i=>{i.state==="RECONNECTING"&&as(!0)});V.on("202",i=>{i.state==="RECONNECTING"&&as(!0)});function pS(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=ho(i,"config",D.MAIN),n=ho(i,"config",D.BACKUP);for(let c of o)if(c.startTime>=e&&(c.name===s||c.name===n)&&c.transferSize>0){let l=c.name===s?D.MAIN:D.BACKUP,m=Math.round(c.duration),f=Math.round(c.domainLookupStart-c.startTime),E=c.redirectStart>0?Math.round(c.redirectEnd-c.redirectStart):0,_=c.fetchStart>0?Math.round(c.domainLookupStart-c.fetchStart):0,v=Math.round(c.domainLookupEnd-c.domainLookupStart),k=Math.round(c.requestStart-c.secureConnectionStart),M=Math.round(c.secureConnectionStart-c.connectStart),N=Math.round(c.responseStart-c.requestStart),B=Math.round(c.responseEnd-c.responseStart),ee=[v,k,M,N,B];je.uploadEvent({log:`stat-schedule-net:${m}(${f}(${E}->${_})->${ee.join("->")}) ${l}`,userId:t}),r=Te(X({},r),{totalCost:m,local:f,dns:v,tcp:M,tls:k,request:N,response:B});break}}catch(o){$.error("getScheduleDetailCost error",o)}return r}function gp(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:c,latencyLevel:l}){if(!iu&&fp)return{isCached:!0,result:fp};let f={delta:0,count:[1,1],msg:[],detail:[]};try{let E=new FormData;E.append("userId",String(i)),E.append("sdkAppId",String(t)),E.append("isStrGroupId",String(e)),E.append("groupId",String(r)),E.append("sdkVersion",s),E.append("userSig",String(o));let _=yield $o();_!=null&&_.model&&E.append("model",String(_==null?void 0:_.model)),c&&E.append("role",String(c)),l&&E.append("latencyLevel",String(l)),n&&E.append("frameWorkType",String(n));let v=Ie(),k=yield gS(E,f,t);k.config&&(k.config.loggerDomain&&wo(k.config.loggerDomain),st(k.config.scheduleCache)&&as(!k.config.scheduleCache)),f.delta=Ie()-v;let M=pS(Number(t),i,v);return fp=k,{isCached:!1,result:k,detailCost:M}}catch(E){let _=ot(E)?E[0]:E,v=ke(_.code)?_.code:0,k=`schedule failed${_.message?`: ${_.message}`:""}`,M=new ue({code:q.SCHEDULE_FAILED,extraCode:v,message:Be({key:$e.JOIN_ROOM_FAILED,data:{error:k,code:v}})});throw $.error(k,v),M}})}var zr={main:"",backup:""};function ou(i){ot(i)?(zr.main=i[0],zr.backup=i[1]):zr.main=i}var bg=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(bg||{});function ho(i,t,e=D.MAIN,r=!1){return`https://${zr[e]||su(i,e,r)}/api/v1/${t}`}function hS(i,t,e){let r=ho(i,t),o=ho(i,t,D.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(l=>l.json()),c=fetch(`${o}?${s}`).then(l=>l.json());return kn([n,c])}function su(i,t=D.MAIN,e=!1){let r;return oi(i)?e?r=t===D.MAIN?ii.MAIN_OVERSEA_BACKUP:ii.BACKUP_OVERSEA:r=t===D.MAIN?ii.MAIN_OVERSEA:ii.BACKUP_OVERSEA:r=t===D.MAIN?ii.MAIN:ii.BACKUP,r}function fS(i,t,e){return new Promise((r,o)=>{ai({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 Ag=(i,t)=>Xi({retryFunction:fS,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function gS(i,t,e){return new Promise((r,o)=>{let s=null;kn([Ag(n=>t.count[0]=n+1,({error:n,retry:c,retriedCount:l,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(l>=1&&(m[0]=ho(e,"config",D.MAIN,!0)),c())})(ho(e,"config",D.MAIN),i,{get timeout(){return ko(2+t.count[0])*1e3}}),Ag(n=>t.count[1]=n+1,({error:n,retry:c,retriedCount:l,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(l>=2&&(m[0]=ho(e,"config",D.BACKUP,!0)),c())})(ho(e,"config",D.BACKUP),i,{get timeout(){return ko(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var ES=i=>i.startsWith("data:application/octet-stream;base64,"),_S=i=>i.startsWith("file://"),La=class{constructor(){u(this,"_log");this._log=$.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=Uo(t);try{let o=Ie(),s;if(We(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Ie()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:Ie()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),Q.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return y(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok){let s=new Error(`network response was not ok: ${r.status}`);throw s.status=r.status,s}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=()=>{if(s.status===200||s.status===0&&s.response)r({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,o(n)}},s.onerror=o,s.send(null)})}loadWasm(t,e){return y(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Ie(),o=null,s=null;if(We(WebAssembly.instantiateStreaming)&&!ES(t)&&!_S(t)&&We(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=Ie()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),Q.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),Q.addFailedEvent({key:522701,error:s}),s})}loadScript(t){this._log.info(`loadScript ${t}`);let e=Ie();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Ie()-e}ms`),Q.addSuccessEvent({key:522702,cost:Ie()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${n}`),Q.addFailedEvent({key:522702}),o(n)},s.crossOrigin="anonymous",s.src=t,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};Z([zo({settings:{timeout:0,retries:3},onError(t,e,r){var o;(t==null?void 0:t.status)===404||(o=t==null?void 0:t.message)!=null&&o.includes("404")?(this._log.warn("download 404, stop retry"),r(t)):e()},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],La.prototype,"download",1),Z([zo({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],La.prototype,"loadScript",1);var _p=new La;function Rg({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:_p,innerEmitter:V,constants:sl,environment:Bs,utils:hp,eventLogger:je,log:this.room.getLogger(),loggerManager:$,errorModule:e,kvStatManager:Q,rtcDectection:eo,trtc:this,rx:np,enums:jl,schedule:Ep,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>y(this,null,function*(){try{window.VisionTaskRegistry||(yield _p.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}catch(n){throw new Error(`Virtual background assets not found. Please redeploy the assets of the npm package. ${n}`)}}),clearStarted:(o,s)=>{let n=o.getAlias(),c=vi.instances.get(this);if(c)if(s){let l=c.get(n+s);if(!l)return;l.started=!1}else c.forEach((l,m)=>{m.startsWith(n)&&(l.started=!1)})},startGetPCM:ba,createAudioNode:Ia}}var vg=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=Be({key:$e.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return $.warn(`${s}
|
|
52
|
+
} `;var Yr=class extends ${constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Dt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new zo(this,e)}createVideoImageSource(e,t){return new gn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Tn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new fc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Yr,"_ids",0);var lE={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Qo=class Qo extends Yr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._ids++}`),this.ctx=this._canvas.getContext("webgl2",lE),!this.ctx)throw new b({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,cE),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,dE),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,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(Qo,"UNAVAILABLE","unavailable"),D([Te($.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})}})],Qo.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Qo.UNAVAILABLE,e),this.removeAllListeners()}})],Qo.prototype,"destroy",1);var ke=Qo,Fe=class extends Yr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yr._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})}};D([Te($.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})}})],Fe.prototype,"create",1),D([Te("created",$.INIT,{ignoreError:!0,sync:!0})],Fe.prototype,"destroy",1);function uE(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ou=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},Yo=class extends Ye{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ou(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(A=>A.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:h,hidden:m}=t;if(!E(l)&&this.inputs.some(A=>A.layout.zIndex===l&&A.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];E(s)||(_.layout.x=s),E(n)||(_.layout.y=n),E(a)||(_.layout.width=a),E(c)||(_.layout.height=c),E(h)||(_.layout.rotation=h),E(m)||(_.layout.hidden=m),u&&(_.layout.fillMode=u),!E(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((A,g)=>A.layout.zIndex-g.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof ke&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){let t=this.inputs.reduce((r,s)=>s.node.requestFrame(e)||r,!1);if(this.ctx2d){if(t){this.drawBackGround2d(this.backgroundColor);for(let r=0;r<this.inputs.length;r++){let s=this.inputs[r];if(s.hidden)continue;let n=uE(s.node.width,s.node.height,s.width,s.height,s.fillMode,dt(s.rotation));this.draw2d(s.node.image,s.x+n.dx,s.y+n.dy,n.dWidth,n.dHeight,n.sx,n.sy,n.sWidth,n.sHeight)}}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},v({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof ke)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var hE=[1,0,0,0,1,1,0,1],Ot=class extends Ye{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof ke)try{this.setTexBuffer(hE)}catch(n){e.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var _c=class extends zt{constructor(e=4){super(e,ot);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.mixNode=new Yo(this.videoContext,this.log)}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Fe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n);for(let[n,a]of this.inputLocalScreenTracks)a.profile.frameRate>t&&(t=a.profile.frameRate,e=n,r=!1);if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return f(this,null,function*(){if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),ci&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack)})}addCameraSource(e,t,r){return f(this,null,function*(){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n;Je===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()})}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(Je===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Dt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Dt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(E(r)||(c.content=r),E(s)||(c.font=s),E(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Ot(this.videoContext,this.log,s,n);a=e.connect(a),dt(a.rotation)&&a.resize(e.height,e.width),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Ot&&(E(r)||(n.mirror=r),E(s)||(n.rotation=s),dt(n.rotation)?n.resize(e.height,e.width):n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.stop(),t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Ot&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.stop(),t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Ot&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Ot&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Ot&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Ot&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),re.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.stop(),t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear();for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var gc=Hs();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:gc,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var mE=function(o){return f(this,null,function*(){let i=null,e=_E(o);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Mo&<<74||xe||ae)&&y.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){y.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield pE(r,o.captureElement))}if(o.audio){let s=fE(o);y.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function pE(o,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ne(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===gc))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function fE(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return E(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function _E(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:xe?{max:o.width}:{ideal:o.width,max:o.width},height:xe?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gp=mE;var Ze=class extends Be{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return gc===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):(h=yield gp({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=h.getVideoTracks()[0]),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 f(this,null,function*(){throw new Error("Method not implemented.")})}};D([st(function(e){this.setContentHint(e.contentHint||"detail")})],Ze.prototype,"capture",1);var Ii=class extends Ct{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t,r){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(r),this.enableTrackAEC(!1)}removeAudioProcessor(i,e,t,r){this.pipeline.aec.node===r&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var gE='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}});',Mu;function En(o,i=48e3,e=1,t){return f(this,null,function*(){let r=Ee("dump");Mu||(Mu=ji(r,URL.createObjectURL(new Blob([gE],{type:"application/javascript"})))),yield Mu;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Tc=class extends $a{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",y.createLogger({id:"am"}));d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);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}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==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 s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<r.length;m++){let _=URL.createObjectURL(new Blob(n[m])),A=document.createElement("a");A.href=_,A.download=`${r[m]}.pcm`,A.style.display="none",document.body.appendChild(A),A.click(),URL.revokeObjectURL(_),A.remove()}clearTimeout(a),s.abort("download")},l=En(t).then(m=>m.pipeTo(new WritableStream({write(_){_.forEach((A,g)=>n[g]=n[g]?n[g].concat(A[0]):[A[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var O,K,G;if(E(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),h,m,_=0,A=new AbortController,g=t===""?(O=this._localAudioTrack)==null?void 0:O.mediaTrack:(G=(K=this.room)==null?void 0:K.remotePublishedUserMap.get(t))==null?void 0:G.remoteAudioTrack.mediaTrack;if(!g){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let T=Ee().createMediaStreamSource(new MediaStream([g]));return En([T],s,n,a).then(ee=>ee.pipeTo(new WritableStream({write(_e){_e[0][0]&&(_+_e[0][0].length>c?(l.set(_e[0][0].subarray(0,c-_),_),h=_e[0][0].subarray(c-_),_e[0][1]&&(u.set(_e[0][1].subarray(0,c-_),_),m=_e[0][1].subarray(c-_)),_+=c-_):(h&&(l.set(h,_),_+=h.length,h=void 0),m&&(u.set(m,_),m=void 0),l.set(_e[0][0],_),_e[0][1]&&u.set(_e[0][1],_),_+=_e[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),A).catch(_e=>this.log.warn(`stop getPCM reason:${_e}`))),A}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){if(e instanceof Ii)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Ct)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&this.audioProcessor&&(e.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((t,r)=>{e.mixAudioReference(t,r)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Qt)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Ii?delete this._localScreenAudioTrack:e instanceof Ct?delete this._localAudioTrack:e instanceof Qt}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor=[e,t,r,s],this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&(this._localAudioTrack.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(...this.audioProcessor),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}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()}removeAudioProcessor(e,t,r,s){var n;delete this.audioProcessor,(n=this._localAudioTrack)==null||n.removeAudioProcessor(e,t,r,s)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||E(s))return;this.setAudioReferenceVolume(r,s)}}};function Ec(o=30,i=2){return Y((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new b({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});y.warn(c),i===2?n(c):i===1&&s()},o*1e3);e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a)})})})}var Ai=class Ai extends Gr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",nt(me(this,Ai.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new $(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new $(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ue(zl(me(this,$.STATECHANGED),me(this.remotePublishState,$.STATECHANGED)),_n(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),be(c=>{this.availableState.state!==(c?$.ON:$.OFF)&&(this.availableState.state=c?$.ON:$.OFF),this.updatePlayingState(c)}));let s=ue(me(this.player,he.ERROR),Si(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=ue(pn(5e3),Si(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===p.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=ue(Ql(s,n),He(me(this,$.INIT)));ue(this._triggerCheckDecodeSubject,Si(()=>!this.ignoreDecodeError),zr(a),be(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ai.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===$.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){var s,n;let r=this.kind===p.AUDIO;if(N[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";N[e?"addSuccessEvent":"addFailedEvent"]({key:qs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(N.addEnum({key:r?504701:514703,value:Fs()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${Lr()||Hi()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===p.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?$.ON:$.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Ai,"STATE_SUBSCRIBE","subscribe"),D([Ec(5,1)],Ai.prototype,"waitHasMediaTrack",1),D([Te($.INIT,Ai.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),pt(521716,!1)],Ai.prototype,"subscribe",1),D([Te(Ai.STATE_SUBSCRIBE,$.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ai.prototype,"unsubscribe",1);var Zo=Ai;var Qt=class extends Zo{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return $r.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}};function EE(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Ci=class extends Zo{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,t){return(de(t==null?void 0:t.canvasRender)?t.canvasRender:Je===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 Fe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Qr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Hr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=EE(t);if(!q(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)}},Ko=class extends Ci{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var es=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ae(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ae(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ae(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ae(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?Ae(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ae(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ae(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ae(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ae(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ae(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ae(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ae(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ae(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===p.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ae(o.userId,e)}});function Ae(o,i){let e=w(v({},i),{timestamp:ps()});es.has(o)?es.get(o).push(e):es.set(o,[e])}function Tp(o){if(es.has(o)){let i=es.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return es.delete(o),i}return[]}function Ep(...o){return Y((i,e)=>function(...t){return SE.call(this,o,t,e,this._name),i.apply(this,t)})}function SE(o,i,e,t){try{if(Se(o))for(let r=0;r<o.length;r++)Sc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Sc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw y.error(r),r}}function Sc({rule:o,value:i,key:e,fnName:t,className:r}){if(E(i)){if(o.required)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(E(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),ne(o.type[c])&&i instanceof o.type[c]&&(a=!0),te(o.type[c])&&Re(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>Or(c)?po(c):te(c)?c:Re(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(o.type)&&Re(i)!==o.type)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=q(i)&&(i===0||Number.isNaN(i)),c=te(i)&&i.trim()==="";if(a||c)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&q(i)&&i<0)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.min)&&q(i)&&i<o.min)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.max)&&q(i)&&i>o.max)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new b({code:I.INVALID_PARAMETER,message:P({key:L.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;ze(s)&&ft(i)&&Object.keys(s).forEach(a=>{Sc.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;ze(n)&&Se(i)&&i.forEach((a,c)=>{Sc.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}var Sp=Ge(tt(),1);var Ic=class extends Sp.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;E(t)||(s+=`:${gd[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:s,userId:n,tinyId:a}=t,c=xi(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==s&&(h.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:xi(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function ku({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Y((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new b({code:I.INVALID_OPERATION,message:P({key:L.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var IE="2025-07-15 20:35:19",Ip=!0,Ap=function(){var o;if(Ip){Ip=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ti}/en/index.html`),console.info(`* Changelog: ${ti}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),y.info("TRTC Web SDK Version:",we),Gt||y.debug("Build Time:",IE);let i=`UA: ${navigator.userAgent}
|
|
53
|
+
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Yd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),y.info(i),y.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),xr().then(t=>{t&&y.info(Bt)})}};var Mt={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var U={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},kt=(R=>(R[R.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",R[R.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",R[R.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",R[R.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",R[R.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",R[R.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",R[R.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",R[R.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",R[R.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",R[R.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",R[R.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",R[R.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",R[R.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",R[R.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",R[R.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",R[R.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",R[R.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",R[R.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",R[R.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",R[R.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",R[R.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",R[R.INVALID_OPERATION=5100]="INVALID_OPERATION",R[R.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",R[R.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",R[R.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",R[R.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",R[R.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",R[R.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",R[R.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",R[R.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",R[R.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",R[R.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",R[R.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",R[R.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",R[R.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",R[R.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",R[R.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",R[R.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",R[R.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",R[R.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",R[R.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",R[R.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",R[R.DEVICE_ERROR=5300]="DEVICE_ERROR",R[R.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",R[R.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",R[R.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",R[R.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",R[R.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",R[R.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",R[R.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",R[R.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",R[R.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",R[R.SERVER_ERROR=5400]="SERVER_ERROR",R[R.NEED_TO_BUY=5401]="NEED_TO_BUY",R[R.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",R[R.OPERATION_FAILED=5500]="OPERATION_FAILED",R[R.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",R[R.REJOIN_FAILED=5502]="REJOIN_FAILED",R[R.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",R[R.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",R[R.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",R[R.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",R[R.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",R[R.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",R[R.OPERATION_ABORT=5998]="OPERATION_ABORT",R[R.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",R))(kt||{});function Rp({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=kt[o];try{r=Cp[s]}catch(n){r=Cp.UNKNOWN_ERROR}return ne(r)?t=r(i):te(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Cp=w(v({},Ve),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Re(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Zr(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Zr(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var wu=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a}){var l;let c;r?c=r:c=Rp({code:e===U.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},s)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=kt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");wr?m.href=`ms-settings:privacy-${h[this.functionName]}`:$t&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof b){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ve.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=U.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=AE(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=U.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
|
+
`)))}else{if(e instanceof o)return e;s=new o({code:U.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function AE(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var x=wu;function _r(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Sn(o){return o===Mt.QOS_PREFERENCE_CLEAR?"detail":o===Mt.QOS_PREFERENCE_SMOOTH?"motion":""}function ts(o,i){let e=i?dd:nr;return Ld(o)?v(v({},e),o):Lt[o]?Lt[o]:e}var yp={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},bp={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}}},is={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(te(o)&&!document.getElementById(o))throw new x({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Np={name:"userId",required:!0,type:"string"},vp={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Mt.AUDIO_PROFILE_STANDARD,Mt.AUDIO_PROFILE_STANDARD_STEREO,Mt.AUDIO_PROFILE_HIGH,Mt.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function rs(o,i){if(!o)throw new x({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function Dp(o,i,e){if(!o)throw new x({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Op(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new x({code:U.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function Mp(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new x({code:U.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var wk={type:"number",notLessThanZero:!0},CE=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function kp(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Pa()){y.warn("small stream is not supported"),delete o.option.small;return}let i=ts(o.option.profile),e=ts(o.option.small,!0);if(!CE(i,e)){y.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var RE={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new x({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(te(o.roomId))throw new x({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Op(o.roomId,e,i)}else if(o.strRoomId)Mp(o.strRoomId,e,i);else throw new x({code:U.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},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:is,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:yp},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&kp(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},is),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:yp},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&kp(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:vp},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:vp}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:is,publish:{type:"boolean"},option:bp},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Wi())throw new x({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!Xs())throw new x({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:is,publish:{type:"boolean"},option:bp}},muteRemoteAudio:[Np,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Np,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:is,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){rs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Dp(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},is),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){rs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Dp(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&E(o.streamType))throw new x({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){rs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!Ys)throw new x({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new x({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new x({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new x({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});rs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new x({code:U.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new x({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new x({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(rs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new x({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(rs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new x({code:U.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new x({code:U.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Op(o.roomId,e,i);else if(o.strRoomId)Mp(o.strRoomId,e,i);else throw new x({code:U.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Ue={TRTC:RE};var Ke=class extends Error{};function yE(o,i){let e=Nr(o);for(let t=0;t<i.length;t++)oi(e[t],i[t]);return e}function bE(o){this._resolve=Promise.resolve(o)}function NE(o){this._reject=Promise.reject(o)}var gr=class gr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",yE);let t=gr.instances.get(i);t?t.set(e,this):gr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=gr.instances.get(i);return t&&t.get(e)||new gr(i,e)}static gets(i,e){let t=gr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Ke("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:bE,reject:NE};try{switch(this.state){case 1:if(i===0)throw new Ke("already started");break;case 4:if(i===2)throw new Ke("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Ke("already start");break;case 3:switch(i.type){case 2:throw new Ke("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ke("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Ke("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 Ke("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ke("start not allowed after update");case 0:throw new Ke("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Ke("keep start")),new Ke("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(gr,"instances",new WeakMap);var Zi=gr;var Ac=new WeakMap,Cc=(o,i)=>{if(i instanceof Ke){let{stack:e}=i;i=new x({code:U.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
|
+
`)))}throw i};function Tr(o,i){return Y((e,t)=>function(...r){let s=Zi.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(Cc.bind(null,t))):e.apply(this,r)})}function Kr(o,i){let{merge:e,debounce:t}=i||{};return Y((r,s)=>function(...n){let a=Zi.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,h)=>{var A,g;let m=(A=Ac.get(this))==null?void 0:A.get(l(...n));if(m){let{timeoutId:T,resolve:O}=m;clearTimeout(T),O()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(Cc.bind(null,s)).then(u,h)},c);Ac.has(this)?(g=Ac.get(this))==null||g.set(l(...n),{timeoutId:_,resolve:u}):Ac.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(Cc.bind(null,s))})}function Er(o){return Y((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(Zi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=Zi.get(this,r);return s?s.action(3,i.bind(this),t).catch(Cc.bind(null,e)):i.apply(this,t)})}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"},wp=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]);var Uu={};vi(Uu,{ScheduleRequestType:()=>Lp,getAbilityConfig:()=>DE,getScheduleDomain:()=>bc,isNeedToSchedule:()=>Rc,scheduleProxy:()=>Ri,sendScheduleRequest:()=>Pu,setIsNeedToSchedule:()=>Yt,setScheduleProxy:()=>yc});var Lu=null,Rc=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Mi).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
56
|
+
`));function Yt(o){de(o)&&o!==Rc&&(Rc=o,y.info(`setIsNeedToSchedule ${o}`))}S.on("28",()=>Yt(!0));S.on("63",()=>Yt(!0));S.on("84",()=>Yt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Yt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Yt(!0)});function vE(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Sr(o,"config",p.MAIN),n=Sr(o,"config",p.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?p.MAIN:p.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),h=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),A=Math.round(a.requestStart-a.secureConnectionStart),g=Math.round(a.secureConnectionStart-a.connectStart),T=Math.round(a.responseStart-a.requestStart),O=Math.round(a.responseEnd-a.responseStart),K=[_,A,g,T,O];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${h}->${m})->${K.join("->")}) ${c}`,userId:i}),t=w(v({},t),{totalCost:l,local:u,dns:_,tcp:g,tls:A,request:T,response:O});break}}catch(r){y.error("getScheduleDetailCost error",r)}return t}function Pu(l){return f(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){if(!Rc&&Lu)return{isCached:!0,result:Lu};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(o)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",s),h.append("userSig",String(r));let m=yield xr();m!=null&&m.model&&h.append("model",String(m==null?void 0:m.model)),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let _=B(),A=yield ME(h,u,i);A.config&&(A.config.loggerDomain&&Ar(A.config.loggerDomain),de(A.config.scheduleCache)&&Yt(!A.config.scheduleCache)),u.delta=B()-_;let g=vE(Number(i),o,_);return Lu=A,{isCached:!1,result:A,detailCost:g}}catch(h){let m=Se(h)?h[0]:h,_=q(m.code)?m.code:0,A=`schedule failed${m.message?`: ${m.message}`:""}`,g=new b({code:I.SCHEDULE_FAILED,extraCode:_,message:P({key:L.JOIN_ROOM_FAILED,data:{error:A,code:_}})});throw y.error(A,_),g}})}var Ri={main:"",backup:""};function yc(o){Se(o)?(Ri.main=o[0],Ri.backup=o[1]):Ri.main=o}var Lp=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Lp||{});function Sr(o,i,e=p.MAIN,t=!1){return`https://${Ri[e]||bc(o,e,t)}/api/v1/${i}`}function DE(o,i,e){let t=Sr(o,i),r=Sr(o,i,p.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Mr([n,a])}function bc(o,i=p.MAIN,e=!1){let t;return ki(o)?e?t=i===p.MAIN?Mi.MAIN_OVERSEA_BACKUP:Mi.BACKUP_OVERSEA:t=i===p.MAIN?Mi.MAIN_OVERSEA:Mi.BACKUP_OVERSEA:t=i===p.MAIN?Mi.MAIN:Mi.BACKUP,t}function OE(o,i,e){return new Promise((t,r)=>{Ui({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var xp=(o,i)=>ni({retryFunction:OE,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function ME(o,i,e){return new Promise((t,r)=>{let s=null;Mr([xp(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Sr(e,"config",p.MAIN,!0)),a())})(Sr(e,"config",p.MAIN),o,{get timeout(){return Dr(2+i.count[0])*1e3}}),xp(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Sr(e,"config",p.BACKUP,!0)),a())})(Sr(e,"config",p.BACKUP),o,{get timeout(){return Dr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var kE=o=>o.startsWith("data:application/octet-stream;base64,"),wE=o=>o.startsWith("file://"),In=class{constructor(){d(this,"_log");this._log=y.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};i=ea(i);try{let r=B(),s;if(ne(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=B()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),N.addSuccessEvent({key:522700,cost:B()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),N.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=B(),r=null,s=null;if(ne(WebAssembly.instantiateStreaming)&&!kE(i)&&!wE(i)&&ne(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=B()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),N.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),N.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=B();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${B()-e}ms`),N.addSuccessEvent({key:522702,cost:B()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${n}`),N.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};D([St({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],In.prototype,"download",1),D([St({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],In.prototype,"loadScript",1);var Vu=new In;function Pp({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:_c,LocalVideoTrack:Be,LocalScreenTrack:Ze,room:i,assetsPath:t,fileDownloader:Vu,innerEmitter:S,constants:Td,environment:ko,utils:Gl,eventLogger:se,log:this.room.getLogger(),loggerManager:y,errorModule:e,kvStatManager:N,rtcDectection:pi,trtc:this,rx:Du,enums:ml,schedule:Uu,getDevices:Wo,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>f(this,null,function*(){try{window.VisionTaskRegistry||(yield Vu.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}catch(n){throw new Error(`Virtual background assets not found. Please redeploy the assets of the npm package. ${n}`)}}),clearStarted:(r,s)=>{let n=r.getAlias(),a=Zi.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:En,createAudioNode:an}}var Up=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=P({key:L.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return y.warn(`${s}
|
|
96
57
|
|
|
97
|
-
${o.stack}`),!1}},i};var cn=new WeakMap;function Cg(i){let t=cn.get(i);t&&(t.forEach(e=>clearTimeout(e)),cn.delete(i))}function Ng(i,t){return xe((e,r)=>function(...o){let s=cn.get(this);s||(s=new Map,cn.set(this,s));let n=t(...o),c=s.get(n);if(!c||c<=0){e.apply(this,o);let l=setTimeout(()=>{var m;(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}else{clearTimeout(c);let l=window.setTimeout(()=>{var m;e.apply(this,o),(m=cn.get(this))==null||m.delete(n)},i);s.set(n,l)}})}var wg="trtc-sdk-v5",Mg="5.11.2-wasm.3";function wt(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Tp(...i){return xe((t,e)=>function(...r){try{au.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function au(i,t,e,r){if(ot(i))for(let o=0;o<i.length;o++)nu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else nu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function nu({rule:i,value:t,key:e,fnName:r,className:o}){function s(l){return{code:le.INVALID_PARAMETER,extraCode:l,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(P(t)){if(i.required)throw new ae(s(5001));if(P(i.defaultValue)){We(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let l=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(l=!0),We(i.type[m])&&t instanceof i.type[m]&&(l=!0),Oe(i.type[m])&&ct(t)===i.type[m].toLowerCase()&&(l=!0);if(!l)throw new ae({code:le.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>Lo(m)?vs(m):Oe(m)?m:ct(m))},value:t}})}else if(!P(i.type)&&ct(t)!==i.type)throw new ae(s(5002));if(i.allowEmpty===!1){let l=ke(t)&&(t===0||Number.isNaN(t)),m=Oe(t)&&t.trim()==="";if(l||m)throw new ae(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new ae(s(5006));if(!P(i.min)&&ke(t)&&t<i.min)throw new ae(s(5007));if(!P(i.max)&&ke(t)&&t>i.max)throw new ae(s(5008));if(Oe(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae(s(5004))}else if(We(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new ae(s(5005));let{properties:n}=i;Lt(n)&&er(t)&&Object.keys(n).forEach(l=>{nu.call(this,{rule:n[l],value:t&&t[l],key:`${l}`,fnName:r,className:o})});let{arrayItem:c}=i;Lt(c)&&ot(t)&&t.forEach((l,m)=>{nu.call(this,{rule:c,value:l,key:`${e}[${m}]`,fnName:r,className:o})}),We(i.validate)&&i.validate.call(this,t,e,r,o,this)}function tt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return xe((n,c)=>function(...l){var v,k,M;function m(N,B,ee){if(ee&&ee.includes(N))return"hided";if(e){let me=e(...l);if(l[me.argIndex]===B)return me.value}if(B===l||N in l)return B;try{return B instanceof HTMLElement?`id: ${B.id} type:${ct(B)}`:B instanceof MediaStreamTrack?Cc(B):(JSON.stringify(B),B)}catch(me){return`type:${ct(B)}`}}let f=this._log||$;if(o!=null&&o(...l))return n.apply(this,l);l.length>0?f.info(`${c}() ${JSON.stringify(l,(N,B)=>m(N,B,["userSig","privateMapKey"]))}`):f.info(`${c}()`);let E=r?r(...l):id[c],_=(s==null?void 0:s(...l))||!1;try{let N=n.apply(this,l),B=Ie();if(Ji(N)){let ee=`${c.includes("Plugin")?`${((k=(v=l[0]).getName)==null?void 0:k.call(v))||""} `:" "}`;return N.then(me=>(f.info(`${c}() success ${ee}${t.call(this,...l)}`),Q.addSuccessEvent({key:E,cost:Ie()-B}),me)).catch(me=>{var J;me=ae.convertFrom.call(this,me,c,l.length===1?l[0]:l);let oe=me.extraCode||me.code,Xe=(J=me.message)!=null&&J.includes(oe)?"":` code:${oe}`;throw _||f.error(`${c}() failed ${ee}${t.call(this,...l)} ${me}${Xe} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:E,error:me}),me})}return Q.addSuccessEvent({key:E}),N}catch(N){N=ae.convertFrom.call(this,N,c);let B=N.extraCode||N.code,ee=(M=N.message)!=null&&M.includes(B)?"":` code:${B}`;throw _||f.error(`${c}() failed ${N}${ee} params: ${JSON.stringify(l,m)}`),Q.addFailedEvent({key:E,error:N}),N}})}var cu=i=>xe((t,e)=>function(r,o){return y(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new ae({code:le.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(We(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new ae({code:le.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return au.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var du=0,Ip,Ci=class Ci{constructor(t){this.core=t;u(this,"log");u(this,"customAudioReferenceMap",new Map);u(this,"audioRefId",0);u(this,"audioContext",ze());u(this,"localAudioWorkletNode");u(this,"screenAudioWorkletNode");u(this,"mixNode");u(this,"silentNode");du=du+1,this.log=t.log.createChild({id:`${this.getAlias()}${du}`}),this.log.info(`created id=${this.getAlias()}${du}`)}static getStartValidateRule(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&&!t.room.audioManager.hasScreenAudioTrack)throw new ae({code:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return Ip||(Ip=this.doPreload(t)),Ip}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Ti(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Ci.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Ci.getStartValidateRule(this.core);case"update":return Ci.updateValidateRule;case"stop":return Ci.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core,{sdkAppId:r,userId:o,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:m=!0,isScreenAudioNeedAudioProcess:f=!0}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=m,this.core.room.audioManager.isScreenAudioNeedAudioProcess=f,!s)throw new ae({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let E=String(Date.now()).slice(0,-3),{auth:_,sign:v,status:k,message:M}=yield IS(Te(X({},t),{timestamp:E}));if(!_)throw this.log.info(`audioProcessor: ${o} auth result: ${_}. Message: ${M}`),new ae({code:le.INVALID_PARAMETER,message:M});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,E,v,k,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,E,v,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),P(n)||n.forEach(E=>{this.customAudioReferenceMap.set(E,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:E,refId:`o-${this.audioRefId++}`})}),P(c)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),P(l)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:l}})})}update(t){return y(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:r,processLevel:o}=t;P(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),P(o)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),P(r)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:t}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(t,e,r,o,s,n,c,l){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:c}}),t.port.onmessage=m=>{var E;let{data:f}=m;switch(f.type){case"cost":let _=(f==null?void 0:f.value)>10?"info":"debug";this.log[_](`[${e}] avg cost: ${f.value} max: ${f==null?void 0:f.max}(${Ss(new Date(f==null?void 0:f.maxCostTimestamp))}) hist: ${(E=f==null?void 0:f.hist)==null?void 0:E.join(" ")}`);return;case"log":this.log[f.logLevel](`[${e}] ${f.value}`);return;case"dump":V.emit("265",{room:l,data:f.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};u(Ci,"updateValidateRule",{type:"object"}),u(Ci,"stopValidateRule",{type:"object"}),u(Ci,"Name","AudioProcessor");var uu=Ci;function TS(i,t=D.MAIN){return`https://${zr[t]||su(i,t)}/api/v1/audioAiAuth`}function IS(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${TS(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,c=yield fetch(n),{data:{errCode:l,errMsg:m,sign:f,status:E}}=yield c.json();if(E==="1")return{auth:!0,sign:f,status:E,message:m};let _=oi(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",v="Init RTCAudioProcessor failed.",k="";switch(l){case 1:k="Please check your params.";break;case 2:k=`You need to buy packages. Refer to: ${_}`;break;case 3:k="Server is invalid. Please contact our engineer. ";break;case 4:k=`Your packages is not active. Refer to: ${_}`;break;case 5:k=`Your packages is expired. Refer to: ${_}`;break;case 6:k="Your version is not supported.";break}return{auth:!1,status:E,message:m?`${v} Reason: ${m}. ${k}`:`${v}, ${k}`}})}var lu=0,Sp=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Xs(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&&(P(t.volume)||(this.volume=t.volume),P(t.loop)||(this.loop=t.loop),P(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 dn(i,t){if(t&&typeof t!="function")throw new ae({code:le.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var Xr=class Xr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);lu=lu+1,this.log=t.log.createChild({id:`${this.getAlias()}${lu}`}),this.log.info(`created id=${this.getAlias()}${lu}`)}getName(){return Xr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return Xr.startValidateRule;case"update":return Xr.updateValidateRule;case"stop":return Xr.stopValidateRule}}start(t){return y(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 Sp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${r}`}),this.log.info(`start mix audio track ${r} success.`),Q.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return y(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),P(r)||n.setOperation(r),P(o)||n.seek(o),this.kvUpload(t)})}stop(e){return y(this,arguments,function*({id:t}){if(this.mixedMusicMap.has(t)){this.log.info(`remove music source, music id: ${t}`);let r=this.mixedMusicMap.get(t);r!=null&&r.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:r.mixInput.source.node,refId:`ax-${t}`}),r==null||r.stop(),this.mixedMusicMap.delete(t)}t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:c,onTimeUpdate:l,onDurationChange:m,onEnded:f}=t;e&&Q.addCount({key:502711}),r&&Q.addCount({key:502703}),o&&Q.addCount({key:502704}),s&&Q.addCount({key:502705}),n&&Q.addCount({key:502706}),c&&Q.addCount({key:502707}),typeof l!="function"&&Q.addCount({key:502709}),typeof f!="function"&&Q.addCount({key:502710}),typeof m!="function"&&Q.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,e)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};u(Xr,"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(),c=s.indexOf(n)>=0,l=o.startsWith("blob"),m=o.startsWith("data");if(!(c||l||m))throw new ae({code:le.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new ae({code:le.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(Xr,"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){dn("onTimeUpdate",t.onTimeUpdate),dn("onEnded",t.onEnded),dn("onDurationChange",t.onDurationChange)}}),u(Xr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Xr,"Name","AudioMixer");var mu=Xr;var pu=0,yp,Ni=class Ni{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",ze("denoiser"));u(this,"workletNode");pu=pu+1,this.log=t.log.createChild({id:`${this.getAlias()}${pu}`}),this.log.info(`created id=${this.getAlias()}${pu}`)}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 ae({code:le.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return yp||(yp=this.doPreload(t)),yp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield Ti(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Ni.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Ni.startValidateRule(this.core);case"update":return Ni.updateValidateRule;case"stop":return Ni.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e,schedule:r}=this.core,{assetsPath:o=this.core.assetsPath}=t;if(!o)throw new ae({code:le.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${o}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:c,status:l,message:m}=yield yS(r,Te(X({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new ae({code:le.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:s,sign:c,status:l}}),this.workletNode.port.onmessage=f=>{var _;let{data:E}=f;if(E.type==="cost"){let v=(E==null?void 0:E.max)>20?"warn":(E==null?void 0:E.max)>10?"info":"debug";this.log[v](`avg cost: ${E.value} max: ${E==null?void 0:E.max}(${Ss(new Date(E==null?void 0:E.maxCostTimestamp))}) hist: ${(_=E==null?void 0:E.hist)==null?void 0:_.join(" ")}`)}else E.type==="log"&&this.log[E.logLevel](`${E.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return y(this,null,function*(){})}stop(){return y(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(Ni,"updateValidateRule",{type:"object"}),u(Ni,"stopValidateRule",{type:"object"}),u(Ni,"Name","AIDenoiser");var hu=Ni;function yS(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:c,errMsg:l,sign:m,status:f}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(f==="1")return{auth:!0,sign:m,status:f,message:l};let E=oi(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAIDenoiser failed.",v="";switch(c){case 1:v="Please check your params.";break;case 2:v=`You need to buy packages. Refer to: ${E}`;break;case 3:v="Server is invalid. Please contact our engineer. ";break;case 4:v=`Your packages is not active. Refer to: ${E}`;break;case 5:v=`Your packages is expired. Refer to: ${E}`;break;case 6:v="Your version is not supported.";break}return{auth:!1,status:f,message:l?`${_} Reason: ${l}. ${v}`:`${_}, ${v}`}}catch(c){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${c}`}}})}var xg=ji(Zi(),1);var Ap=class extends xg.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 y(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!mt&&(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)&&$.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})}}},AS=new Ap,bp=AS;function bS([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 c=0;c<r;c++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Yo(new DataView(new Uint8Array(s).buffer),!0)}function RS(i){return i.type==="empty"||i.data.byteLength===0}function vS(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function CS(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 Rp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-CS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(bS),s=o.reduce((f,E)=>f+E.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),c=new DataView(n),l=new DataView(i.data),m=0;for(let f=0;f<o.length;f++)for(let E=0;E<o[f].dataView.byteLength;E++)c.setInt8(m++,o[f].dataView.getInt8(E));for(let f=0;f<i.data.byteLength;f++)c.setInt8(m++,l.getInt8(f));return i.data=n,i}function vp({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(RS(i)||!vS(e))return i;let r=[],o=0,s=-1,n=-1;for(let c=0;c<i.data.byteLength;c++){let l=e.getUint8(c);if(l===0)o++;else if(l===1){if(o===2||o===3){let m=c-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Yo(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(c+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var Cp=0,Ua=class Ua{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);Cp++,this.log=t.log.createChild({id:`${this.getAlias()}${Cp}`}),this.log.info(`[sei] created id=${this.getAlias()}${Cp}`),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 Rp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return vp({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(re.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:la?this.encode:Rp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:la?this.decode:vp,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 Ua.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(Ua,"autoStart",!0),u(Ua,"Name","SEI");var fu=Ua;function Np({frame:i,onDump:t}){return t==null||t(),i}function Dp({frame:i,onDump:t}){return t==null||t(),i}var Pg={"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
|
+
${r.stack}`),!1}},o};var os=new WeakMap;function Vp(o){let i=os.get(o);i&&(i.forEach(e=>clearTimeout(e)),os.delete(o))}function Bp(o,i){return Y((e,t)=>function(...r){let s=os.get(this);s||(s=new Map,os.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=os.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=os.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Hp="trtc-sdk-v5",$p="5.12.0-beta.1";function qe(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Bu(...o){return Y((i,e)=>function(...t){try{vc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function vc(o,i,e,t){if(Se(o))for(let r=0;r<o.length;r++)Nc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Nc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function Nc({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(E(i)){if(o.required)throw new x(s(5001));if(E(o.defaultValue)){ne(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),ne(o.type[l])&&i instanceof o.type[l]&&(c=!0),te(o.type[l])&&Re(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new x({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>Or(l)?po(l):te(l)?l:Re(l))},value:i}})}else if(!E(o.type)&&Re(i)!==o.type)throw new x(s(5002));if(o.allowEmpty===!1){let c=q(i)&&(i===0||Number.isNaN(i)),l=te(i)&&i.trim()==="";if(c||l)throw new x(s(5003))}if(o.notLessThanZero&&q(i)&&i<0)throw new x(s(5006));if(!E(o.min)&&q(i)&&i<o.min)throw new x(s(5007));if(!E(o.max)&&q(i)&&i>o.max)throw new x(s(5008));if(te(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new x(s(5004))}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new x(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new x(s(5005));let{properties:n}=o;ze(n)&&ft(i)&&Object.keys(n).forEach(c=>{Nc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;ze(a)&&Se(i)&&i.forEach((c,l)=>{Nc.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),ne(o.validate)&&o.validate.call(this,i,e,t,r,this)}function fe(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Y((n,a)=>function(...c){var _,A,g;function l(T,O,K){if(K&&K.includes(T))return"hided";if(e){let G=e(...c);if(c[G.argIndex]===O)return G.value}if(O===c||T in c)return O;try{return O instanceof HTMLElement?`id: ${O.id} type:${Re(O)}`:O instanceof MediaStreamTrack?ta(O):(JSON.stringify(O),O)}catch(G){return`type:${Re(O)}`}}let u=this._log||y;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(T,O)=>l(T,O,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):Da[a],m=(s==null?void 0:s(...c))||!1;try{let T=n.apply(this,c),O=B();if(lr(T)){let K=`${a.includes("Plugin")?`${((A=(_=c[0]).getName)==null?void 0:A.call(_))||""} `:" "}`;return T.then(G=>(u.info(`${a}() success ${K}${i.call(this,...c)}`),N.addSuccessEvent({key:h,cost:B()-O}),G)).catch(G=>{var J;G=x.convertFrom.call(this,G,a,c.length===1?c[0]:c);let ee=G.extraCode||G.code,_e=(J=G.message)!=null&&J.includes(ee)?"":` code:${ee}`;throw m||u.error(`${a}() failed ${K}${i.call(this,...c)} ${G}${_e} params: ${JSON.stringify(c,l)}`),N.addFailedEvent({key:h,error:G}),G})}return N.addSuccessEvent({key:h}),T}catch(T){T=x.convertFrom.call(this,T,a);let O=T.extraCode||T.code,K=(g=T.message)!=null&&g.includes(O)?"":` code:${O}`;throw m||u.error(`${a}() failed ${T}${K} params: ${JSON.stringify(c,l)}`),N.addFailedEvent({key:h,error:T}),T}})}var Dc=o=>Y((i,e)=>function(t,r){return f(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new x({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ne(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new x({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return vc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var Oc=0,Fu,Ki=class Ki{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");Oc=Oc+1,this.log=i.log.createChild({id:`${this.getAlias()}${Oc}`}),this.log.info(`created id=${this.getAlias()}${Oc}`)}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Fu||(Fu=this.doPreload(i)),Fu}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return Ki.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return Ki.getStartValidateRule(this.core);case"update":return Ki.updateValidateRule;case"stop":return Ki.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core,{sdkAppId:t,userId:r,assetsPath:s=this.core.assetsPath,audioReference:n,processLevel:a,enableDump:c,isLocalAudioNeedAudioProcess:l=!0,isScreenAudioNeedAudioProcess:u=!0}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=l,this.core.room.audioManager.isScreenAudioNeedAudioProcess=u,!s)throw new x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${s}/audioProcessor-wasm.js`),!this.localAudioWorkletNode||!this.screenAudioWorkletNode){let h=String(Date.now()).slice(0,-3),{auth:m,sign:_,status:A,message:g}=yield LE(w(v({},i),{timestamp:h}));if(!m)throw this.log.info(`audioProcessor: ${r} auth result: ${m}. Message: ${g}`),new x({code:U.INVALID_PARAMETER,message:g});this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,h,_,A,e),this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,h,_,A,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),this.localAudioWorkletNode.port.postMessage({type:"enable"}),this.screenAudioWorkletNode.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode),E(n)||n.forEach(h=>{this.customAudioReferenceMap.set(h,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:h,refId:`o-${this.audioRefId++}`})}),E(a)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:a}}),E(c)||this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:c}})})}update(i){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.screenAudioWorkletNode)return;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((s,n)=>{this.customAudioReferenceMap.delete(n),this.core.room.audioManager.updateAudioReference({type:"remove",refId:s})}),e.forEach(s=>{this.customAudioReferenceMap.set(s,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s,refId:`o-${this.audioRefId++}`})})),E(r)||this.localAudioWorkletNode.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||(this.localAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}),this.screenAudioWorkletNode.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){if(!this.localAudioWorkletNode||!this.mixNode||!this.silentNode||!this.screenAudioWorkletNode)return;let{room:i}=this.core;this.localAudioWorkletNode.port.postMessage({type:"disable"}),this.screenAudioWorkletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.mixNode,this.silentNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null)}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var h;let{data:u}=l;switch(u.type){case"cost":let m=(u==null?void 0:u.value)>10?"info":"debug";this.log[m](`[${e}] avg cost: ${u.value} max: ${u==null?void 0:u.max}(${so(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`);return;case"log":this.log[u.logLevel](`[${e}] ${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}};d(Ki,"updateValidateRule",{type:"object"}),d(Ki,"stopValidateRule",{type:"object"}),d(Ki,"Name","AudioProcessor");var Mc=Ki;function xE(o,i=p.MAIN){return`https://${Ri[i]||bc(o,i)}/api/v1/audioAiAuth`}function LE(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${xE(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:h}}=yield a.json();if(h==="1")return{auth:!0,sign:u,status:h,message:l};let m=ki(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",A="";switch(c){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${m}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${m}`;break;case 5:A=`Your packages is expired. Refer to: ${m}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${_} Reason: ${l}. ${A}`:`${_}, ${A}`}})}var kc=0,Hu=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Go(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&&(E(i.volume)||(this.volume=i.volume),E(i.loop)||(this.loop=i.loop),E(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 ss(o,i){if(i&&typeof i!="function")throw new x({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var yi=class yi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);kc=kc+1,this.log=i.log.createChild({id:`${this.getAlias()}${kc}`}),this.log.info(`created id=${this.getAlias()}${kc}`)}getName(){return yi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return yi.startValidateRule;case"update":return yi.updateValidateRule;case"stop":return yi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Hu(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i),yield s.play(),this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),N.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),E(t)||n.setOperation(t),E(r)||n.seek(r),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),s&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="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)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(yi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new x({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new x({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ss("onTimeUpdate",i.onTimeUpdate),ss("onEnded",i.onEnded),ss("onDurationChange",i.onDurationChange)}}),d(yi,"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){ss("onTimeUpdate",i.onTimeUpdate),ss("onEnded",i.onEnded),ss("onDurationChange",i.onDurationChange)}}),d(yi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(yi,"Name","AudioMixer");var wc=yi;var xc=0,$u,er=class er{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");xc=xc+1,this.log=i.log.createChild({id:`${this.getAlias()}${xc}`}),this.log.info(`created id=${this.getAlias()}${xc}`)}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,s){if(!i.room.audioManager.hasAudioTrack)throw new x({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return $u||($u=this.doPreload(i)),$u}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield ji(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return er.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return er.startValidateRule(this.core);case"update":return er.updateValidateRule;case"stop":return er.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new x({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(yield this.preload(`${r}/denoiser-wasm.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield UE(t,w(v({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new x({code:U.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var m;let{data:h}=u;if(h.type==="cost"){let _=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[_](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${so(new Date(h==null?void 0:h.maxCostTimestamp))}) hist: ${(m=h==null?void 0:h.hist)==null?void 0:m.join(" ")}`)}else h.type==="log"&&this.log[h.logLevel](`${h.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(er,"updateValidateRule",{type:"object"}),d(er,"stopValidateRule",{type:"object"}),d(er,"Name","AIDenoiser");var Lc=er;function UE(s,n){return f(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let h=ki(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${h}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${h}`;break;case 5:_=`Your packages is expired. Refer to: ${h}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${_}`:`${m}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Wp=Ge(tt(),1);var Gu=class extends Wp.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&y.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},VE=new Gu,Wu=VE;function Ju([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new zi(new DataView(new Uint8Array(s).buffer),!0)}function qu(o){return o.type==="empty"||o.data.byteLength===0}function ju(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Xu(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function zu({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Xu(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ju),s=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Qu({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(qu(o)||!ju(e))return o;let t=[],r=0,s=-1,n=-1;for(let a=0;a<o.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(s===-1?s=l:n===-1&&(n=l,t.push(new zi(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(a+1)===6)){o.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return o}var Yu=0,An=class An{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Yu++,this.log=i.log.createChild({id:`${this.getAlias()}${Yu}`}),this.log.info(`[sei] created id=${this.getAlias()}${Yu}`),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 zu({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Qu({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(k.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:Ji?this.encode:zu,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ji?this.decode:Qu,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return An.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(An,"autoStart",!0),d(An,"Name","SEI");var Pc=An;function Zu({frame:o,onDump:i}){return i==null||i(),o}function Ku({frame:o,onDump:i}){return i==null||i(),o}var Jp={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
98
59
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
99
60
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
100
61
|
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.
|
|
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=>{Pg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var Ak=Object.keys(Pg);var NS=0,gu,Va=class Va{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()}${++NS}`}),this.log.info("created")}getName(){return Va.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 y(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return y(this,arguments,function*({forceOpen:t}){P(t)&&(t?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return y(this,null,function*(){var t;if(!this.dialog)try{if(gu)yield gu;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${wg}@${at}/assets/debug-dialog.js`;gu=this._core.fileDownloader.loadScript(e),yield gu}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):Np,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 Np({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())}})}};u(Va,"Name","Debug"),u(Va,"autoStart",!0);var Eu=Va;var kg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},_u=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=Ne(e,de.INIT),this.stopOB=yt(),this.startOB=yt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=yt(),c=l=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),be(m,Ye(this.stopOB),Le(()=>{},f=>{e.log.error(f),o.addFailedEvent({key:kg(this.type),error:f}),l>4?this.startOB.error(f):this.startOB.next(l+1)})),be(m,Dr(1),rp(Na))};be(this.startOB,va(0),no(c),Ye(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},l=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:kg(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 yi()(e=>y(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"}))}},DS={type:"object"},Fa=class Fa{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 Fa.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Fa.Name}getValidateRule(t){return DS}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 _u(this.core,r,t);return be(o.trackDoneOB,Dr(1),Le(()=>{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 _u(this.core,t.track,t))}}};u(Fa,"Name","TRTCAudioDecoder");var $a=Fa;var Tu=class{constructor(){u(this,"log");this.log=$.createLogger({id:"exp"})}call(t,e){return y(this,null,function*(){return We(this[t])?this[t](e):Promise.reject(new ue({code:q.INVALID_PARAMETER,message:Be({key:$e.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return y(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:c}=t,{audioManager:l}=e.room,{getPCMAbortCtrlMap:m,audioFrameEventConfigMap:f}=l;if(f.set(o,{enable:r,sampleRate:s,channelCount:n,port:c}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(E=>{if(E.remoteAudioTrack.isAvailable){if(m.get(E.userId))return;let _=l.getPCM(v=>{e.emit(re.AUDIO_FRAME,v)},E.userId);m.set(E.userId,_)}});else{if(m.get(o))return;let E=l.getPCM(_=>{e.emit(re.AUDIO_FRAME,_)},o);m.set(o,E)}else if(o==="*")e.room.remotePublishedUserMap.forEach(E=>{if(E.remoteAudioTrack.isSubscribed){let{userId:_}=E,v=m.get(_);v==null||v.abort("disable"),m.delete(_)}});else{let E=m.get(o);E==null||E.abort("disable"),m.delete(o)}})}};Z([Kf({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"}}})],Tu.prototype,"enableAudioFrameEvent",1);var Lg=new Tu;var Ug=0,Ba=new Set,Ct=null;Yu(Mg);Hs.checkStorage();var wS={RtcError:ae,ErrorCode:le,ErrorCodeDictionary:hr},Se=class Se extends Vg.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",$.createLogger({id:`t${++Ug}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");u(this,"enterRoomParams");this._room=new e(X({logger:this._log,frameWorkType:Se.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(mu,r.assetsPath),this._use(uu,r.assetsPath),this._use(hu,r.assetsPath),this._use($a,r.assetsPath),this._use(Eu),r.enableSEI&&ma&&this._use(fu),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100),floatVolume:this._localAudioTrack.getInternalAudioLevel()}),r.volumeType===1&&o.forEach(s=>{var c;let n=s.userId===""?this._localAudioTrack:(c=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:c.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(re.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new ae({code:le.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),vg(this,"trtc")}static create(e){}static _create(e,r){lg();let o=new Se(e,r||{});return Ba.add(o),o}get room(){return this._room}_listenEvents(){Vt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(re.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(re.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(re.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(re.ERROR,ae.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(re.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Te(X({},e),{uplinkRTT:Math.min(e.uplinkRTT,Mn),downlinkRTT:Math.min(e.downlinkRTT,Mn)});this.emit(re.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Vt(o,o).add("player-state-changed",s=>{let n=Te(X({},s),{userId:e.userId});o.kind===D.VIDEO&&(n.streamType=uo(o.streamType)),this.emit(o.kind===D.AUDIO?re.AUDIO_PLAY_STATE_CHANGED:re.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(re.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{ht(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:c,videoAvailable:l}=r;c||this._remoteAudioConfigMap.delete(o),l||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==l&&(l?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(l?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==c&&(c?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(c?re.REMOTE_AUDIO_AVAILABLE:re.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?re.REMOTE_VIDEO_AVAILABLE:re.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(re.SEI_MESSAGE,Te(X({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(re.ERROR,new ae({code:le.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,c,l,m,f,E;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)||((c=this._networkQuality)==null?void 0:c.downlinkRTT)||0,Mn),upLoss:((l=this._networkQuality)==null?void 0:l.uplinkLoss)||0,downLoss:((m=this._networkQuality)==null?void 0:m.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((f=e.msg_up_stream_info.msg_audio_status)==null?void 0:f.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((E=e.msg_up_stream_info.msg_audio_status)==null?void 0:E.uint32_audio_level)||0)/pi},video:e.msg_up_stream_info.msg_video_status.filter(_=>r[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:r[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/pi,point2pointDelay:(_.msg_audio_status.uint32_audio_p2p_delay||0)+(_.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:_.msg_audio_status.uint32_audio_cache_ms||0},video:_.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(re.STATISTICS,o)}).add("custom-message",e=>{this.emit(re.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(re.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(re.FIRST_VIDEO_FRAME,Te(X({},e),{streamType:uo(e.streamType)}))}).add("audio-frame",e=>{this.emit(re.AUDIO_FRAME,e)}),Vt(this,St).add("audioInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>y(this,null,function*(){if(this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ct&&Ct.deviceId===wn){let r=(yield to()).find(o=>o.deviceId===wn);r&&Ct.groupId!==r.groupId&&(Ct=r,this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield to())[0];if(!r||!Ct||Ct.groupId===r.groupId)return;let o=Ct.deviceId===e.deviceId,s=Ct.deviceId===wn&&Ct.deviceId===r.deviceId;(o||s)&&(Ct=r,this.emit(re.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)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(Rg.call(this,{TRTC:Se,room:this._room,errorModule:wS,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return y(this,null,function*(){var l,m;this.enterRoomParams=e;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Oe(e.proxy)&&e.proxy.turnServer&&((m=(l=this._room).setTurnServer)==null||m.call(l,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,st(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let c={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(c,r,Se.frameWorkType),this._checkTrackToPublish(),bp.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return y(this,null,function*(){if(this.room.isSwitchRoomSupported())yield this._room.switchRoom(e);else{yield this.exitRoom();let r=X(X({},this.enterRoomParams),e);yield this.enterRoom(r)}})}switchRole(e,r){return y(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(){ht(this),this.removeAllListeners(),this._room.destroy(),Ba.delete(this),Ba.size===0&&bp.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(),V.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return y(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 qr(this._room.audioManager),c={},l={muted:!0};s&&(P(s.microphoneId)?P(s.audioTrack)||(c.customSource=s.audioTrack):c.deviceId=s.microphoneId,s&&ke(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),P(s.profile)||(Oe(s.profile)?gc[s.profile]&&n.setProfile(gc[s.profile]):n.setProfile(s.profile)),ke(s.earMonitorVolume)&&(l.muted=!(s.earMonitorVolume>0),l.volume=s.earMonitorVolume),P(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),P(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),P(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",m=>{this.emit(re.ERROR,new ae({code:le.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(re.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let f;m.error&&(f=ae.convertFrom(m.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(X({},m),{error:f}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(c),P(o)||n.setMute(o),Vt(n,n).add("player-state-changed",m=>{this.emit(re.AUDIO_PLAY_STATE_CHANGED,Te(X({},m),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Te(X({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:l,track:n}),V.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return y(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):P(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),P(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),P(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!P(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),P(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ur(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),V.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ht(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var E;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:c}=e,l=new Nr(this._room.videoManager),m={},f={};st(c==null?void 0:c.avoidCropping)&&(l.avoidCropping=c.avoidCropping),c&&(c.cameraId?m.deviceId=c.cameraId:P(c.useFrontCamera)?P(c.videoTrack)||(m.customSource=c.videoTrack):m.facingMode=c.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,P(c.retryWhenExactFailed)||(m.retryWhenExactFailed=c.retryWhenExactFailed),c.qosPreference&&(m.contentHint=ka(c.qosPreference)),P(c.profile)||(Oe(c.profile)?Ir[c.profile]&&l.setProfile(Ir[c.profile]):l.setProfile(c.profile)),P(c.fillMode)||(f.objectFit=c.fillMode),P(c.mirror)||(f.mirror=c.mirror),P(c.small)||(P(c.smallMode)||(this._room.smallMode=c.smallMode),st(c.small)&&c.small===!1?l.stopSmall():l.updateSmallConfig(sn(c.small,!0))),P(c.rotation)||l.setRotation(c.rotation)),l.once("first-video-frame",_=>{this.emit(re.FIRST_VIDEO_FRAME,Te(X({},_),{streamType:uo(_.streamType)}))}),l.on("5",_=>{this.emit(re.ERROR,new ae({code:le.DEVICE_ERROR,extraCode:5308,messageParams:{error:_}}))}),l.on("2",_=>{this.emit(re.DEVICE_CHANGED,{type:"camera",action:"active",device:_})}),l.on("4",_=>{let v;_.error&&(v=ae.convertFrom(_.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(X({},_),{error:v}))}),this._listenOutputTrackChanged(l),s?yield l.capture(m):(E=l.manager)==null||E.changeInput(l),P(n)||(yield l.setMute(n)),Vt(l,l).add("player-state-changed",_=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(X({},_),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(l).catch(()=>{}),this._localVideoTrack=l,this._localVideoConfig=Te(X({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:f,track:l})})}updateLocalVideo(e){return y(this,null,function*(){var m,f,E;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:c}=e,l={};if(this._localVideoConfig.capture)n!==!1?c!=null&&c.cameraId?yield this._localVideoTrack.switchDevice(c==null?void 0:c.cameraId):P(c==null?void 0:c.useFrontCamera)?P(c==null?void 0:c.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(c==null?void 0:c.videoTrack)):yield this._localVideoTrack.switchDevice(c!=null&&c.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let _={};_.deviceId=(c==null?void 0:c.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),_.facingMode=c!=null&&c.useFrontCamera||(f=this._localVideoConfig.option)!=null&&f.useFrontCamera?D.FACING_MODE_USER:D.FACING_MODE_ENVIRONMENT,_.customSource=(c==null?void 0:c.videoTrack)||((E=this._localVideoConfig.option)==null?void 0:E.videoTrack),yield this._localVideoTrack.capture(_)}c&&(P(c.profile)||(Oe(c.profile)?Ir[c.profile]&&this._localVideoTrack.setProfile(Ir[c.profile]):this._localVideoTrack.setProfile(c.profile),(!c.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(c.cameraId))&&P(c.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),P(c.fillMode)||(l.objectFit=c.fillMode),P(c.mirror)||(l.mirror=c.mirror),P(c.rotation)||this._localVideoTrack.setRotation(c.rotation),c.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(ka(c.qosPreference)),P(c.small)||(st(c.small)&&!c.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(sn(c.small,!0)))),this._room.isJoined&&P(o)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((o!=null?o:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),P(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:l,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ur(this._localVideoConfig,e)})}stopLocalVideo(){return y(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ht(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(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 io(this._room.videoManager);n.on("4",E=>{let _;E.error&&(_=ae.convertFrom(E.error)),this.emit(re.PUBLISH_STATE_CHANGED,Te(X({},E),{error:_}))}),n.once("first-video-frame",E=>{this.emit(re.FIRST_VIDEO_FRAME,Te(X({},E),{streamType:uo(E.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let c=null,l={},m={};s&&(P(s.profile)||(Oe(s.profile)?Ec[s.profile]&&n.setProfile(Ec[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(l.systemAudio=!0,l.echoCancellation=s.echoCancellation,l.noiseSuppression=s.noiseSuppression,l.autoGainControl=s.autoGainControl),P(s.fillMode)||(m.objectFit=s.fillMode),s.videoTrack&&(l.videoTrack=s.videoTrack),s.audioTrack&&(l.audioTrack=s.audioTrack),s.captureElement&&(l.captureElement=s.captureElement),s.preferDisplaySurface&&(l.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(l.contentHint=ka(s.qosPreference)));let f=yield n.capture(l);if(n.mediaTrack.addEventListener(D.ENDED,()=>{this._stopScreenShare(),this.emit(re.SCREEN_SHARE_STOPPED)}),f.getAudioTracks()[0]&&(c=new Ko(this._room.audioManager),yield c.setInputMediaStreamTrack(f.getAudioTracks()[0]),this._speakerId&&c.setAudioOutput(this._speakerId)),Vt(n,n).add("player-state-changed",E=>{this.emit(re.VIDEO_PLAY_STATE_CHANGED,Te(X({},E),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let E=[n];c&&(E.push(c),this._checkScreenAudioEchoCancellation(n,c)),this._room.publish(...E).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=c,this._localScreenConfig=Te(X({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:m,track:n})})}updateScreenShare(e){return y(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(P(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let c=ka(s.qosPreference);this._localScreenTrack.setContentHint(c)}this._room.isJoined&&!P(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}),ur(this._localScreenConfig,e)})}stopScreenShare(){return y(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return y(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`;if(this._remoteVideoConfigMap.has(c)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let l=this._room.remotePublishedUserMap.get(o);if(!l)return;let m={},f=s==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack;this._listenOutputTrackChanged(f),n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror),P(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!P(n.small)&&(!l.remoteVideoTrack.isSubscribing&&!l.remoteVideoTrack.isSubscribed&&l.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,f.user))),yield this._room.subscribe(f),yield this._enableVideoDecodeFallback(f,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:f}),this._emitTrackEvent(f),this._remoteVideoConfigMap.set(c,{config:e}),n&&!P(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:f,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var N,B;let{view:r,userId:o,streamType:s,option:n}=e,c=`${o}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(P(n.fillMode)||(m.objectFit=n.fillMode),P(n.mirror)||(m.mirror=n.mirror));let f=null,E=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(E!=null&&E.muteState.hasVideo)&&(f=E.remoteVideoTrack),s==="sub"&&(E!=null&&E.muteState.hasAuxiliary)&&(f=E.remoteAuxiliaryTrack),!f)return;let{config:_}=l;s==="main"&&n&&!P(n.small)&&this._room.changeType(n.small,f.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:f,prevConfig:_}),ur(_,e);let v=P(n==null?void 0:n.receiveWhenViewVisible)?(N=_.option)==null?void 0:N.receiveWhenViewVisible:n.receiveWhenViewVisible,k=P(r)?_.view:r,M=P(n==null?void 0:n.viewRoot)?(B=_.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:f,view:k,receiveWhenViewVisible:v,viewRoot:M})})}stopRemoteVideo(e){return y(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return y(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:c,remoteAuxiliaryTrack:l}=s;e.streamType==="main"&&(c.stop(),n.hasVideo&&o.push(c)),e.streamType==="sub"&&(l.stop(),n.hasAuxiliary&&o.push(l))}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 y(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 y(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return y(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return y(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(re.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{yg.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===Se.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Se.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(Oe(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let c=this._room.remotePublishedUserMap.get(r);c&&(o=c.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 c=this._room.remotePublishedUserMap.get(r);c&&(n=o==="main"?c.remoteVideoTrack:c.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 y(this,null,function*(){(yield to()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ct=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 y(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 c=this._remoteAudioVolumeMap.get(r),l=ke(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),be(Ne(n,"decode-failed"),Ye(Ne(n,de.INIT)),Le(()=>{this.startPlugin($a.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),V.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}catch(c){throw this._remoteAudioConfigMap.delete(r),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return y(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}`),V.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_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;be(Ne(e,"decode-failed"),Ye(Ne(e,de.INIT)),Da(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),Ai(Ne(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(re.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Te(X({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return y(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),P(e)&&s&&s.view&&!Cs(r)){let c=Ds(s.view);c.length>0&&(yield o.play(c,r))}if(!P(e)){let c=Ds(e);c.length>0?yield o.play(c,r):o.stop()}})}_updateAudioPlayOption(s){return y(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}if(P(e.muted)||r.setPlayerMute(e.muted),P(e.volume)||r.setAudioVolume(e.volume/100),r instanceof qr&&r.mediaTrack){let n=e.muted===!1&&!P(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof Si){let n=e.muted?0:e.volume;if(P(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${r.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,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(re.TRACK,{userId:o,streamType:uo(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),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(P(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let c=n.observer||void 0;if(r===null||ot(r)&&r.length===0||!o){c==null||c.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,f=-1;(!c||c.root!==s)&&(c==null||c.disconnect(),m.clear(),c=new IntersectionObserver(_=>{_.forEach(v=>{m.set(v.target,v.isIntersecting),e.log.info(`view ${v.target.id} is${v.isIntersecting?"":" not"} visible`)}),clearTimeout(f),f=window.setTimeout(()=>{[...m.values()].find(k=>k)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let E=new Set(Ds(r));m.forEach((_,v)=>{E.has(v)||(c.unobserve(v),m.delete(v))}),E.forEach(_=>{m.set(_,!0),c.observe(_)}),c.takeRecords().forEach(_=>{m.set(_.target,_.isIntersecting)}),n.visibleViewMap=m,n.observer=c}_exitRoom(){return y(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(),Cg(this),this._room.remotePublishedUserMap.forEach(e=>{ht(e.remoteAudioTrack),ht(e.remoteVideoTrack),ht(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return y(this,null,function*(){var e,r;if(this._localScreenTrack){if(this._room.isJoined){let o=[this._localScreenTrack];this._localScreenAudioTrack&&o.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...o).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((r=this._localScreenAudioTrack.trackSettings)==null?void 0:r.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ht(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,r){return y(this,null,function*(){var s,n;if(!e||!r)return;let o=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=r.trackSettings)==null?void 0:n.echoCancellation)===!1&&(o==="monitor"||o==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(c){this._log.warn("start audioProcessor plugin failed: ",c)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ct||Qs(Ct))&&(this._initActiveSpeaker(),V.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Ct&&!Qs(Ct))this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ct});else{let e=yield to();e[0]&&!Qs(e[0])?(Ct=e[0],this.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):V.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:Te(X({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),Q.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),Q.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return y(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),Lg.call(e,X({trtcInstance:this},r))})}static setLogLevel(e,r){$.setLogLevel(e),P(r)||(r?$.enableUploadLog():$.disableUploadLog())}static isSupported(){return cd(Se.frameWorkType)}static getCameraList(e=!0){return or(e)}static getMicrophoneList(e=!0){return Qt(e)}static getSpeakerList(e=!0){return to(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(mt&&(e===pr.SPEAKER||e===pr.HEADSET)){let o=yield Se.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Ba.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield to()).forEach(o=>{o.deviceId===e&&(Ba.forEach(s=>{s._setCurrentSpeaker(e),s.emit(re.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ct=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:c,max:l}){switch(c&&(qo.version=c),e){case"count":qo.addCount({key:r,useUV:n});break;case"enum":qo.addEnum({key:r,value:o,useUV:n});break;case"number":qo.addNumber({key:r,value:o,split:s,max:l});break}}};u(Se,"_loggerManager",$),u(Se,"EVENT",re),u(Se,"ERROR_CODE",le),u(Se,"TYPE",pr),u(Se,"frameWorkType",30),Z([tt({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"}})})],Se.prototype,"use",1),Z([wt(At.TRTC.enterRoom),mo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),xe(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),tt()],Se.prototype,"enterRoom",1),Z([tt()],Se.prototype,"exitRoom",1),Z([wt(At.TRTC.switchRoom),tt(),Rd()],Se.prototype,"switchRoom",1),Z([wt(At.TRTC.switchRole),ns("room",{merge:(e,r)=>r}),tt()],Se.prototype,"switchRole",1),Z([tt()],Se.prototype,"destroy",1),Z([wt(At.TRTC.startLocalAudio),mo("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)}),tt()],Se.prototype,"startLocalAudio",1),Z([wt(At.TRTC.updateLocalAudio),ns("audio",{debounce:{delay:200,getKey:()=>`${Ug}-localAudio`,isNeedToDebounce:e=>{var r;return!P((r=e.option)==null?void 0:r.captureVolume)}}}),tt()],Se.prototype,"updateLocalAudio",1),Z([po("audio"),tt()],Se.prototype,"stopLocalAudio",1),Z([wt(At.TRTC.startLocalVideo),mo("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)}),tt()],Se.prototype,"startLocalVideo",1),Z([wt(At.TRTC.updateLocalVideo),ns("video"),tt()],Se.prototype,"updateLocalVideo",1),Z([po("video"),tt()],Se.prototype,"stopLocalVideo",1),Z([wt(At.TRTC.startScreenShare),mo("screen",()=>!0),tt()],Se.prototype,"startScreenShare",1),Z([wt(At.TRTC.updateScreenShare),ns("screen"),tt()],Se.prototype,"updateScreenShare",1),Z([tt()],Se.prototype,"stopScreenShare",1),Z([wt(At.TRTC.startRemoteVideo),mo(e=>`v${e.userId}${e.streamType}`,()=>!0),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"startRemoteVideo",1),Z([wt(At.TRTC.updateRemoteVideo),ns(e=>`v${e.userId}${e.streamType}`),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"updateRemoteVideo",1),Z([wt(At.TRTC.stopRemoteVideo),xe(e=>function(r){return y(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)})}),tt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Se.prototype,"stopRemoteVideo",1),Z([po(e=>`v${e.userId}${e.streamType}`)],Se.prototype,"_stopRemoteVideo",1),Z([wt(...At.TRTC.muteRemoteAudio),tt({getRemoteId:e=>e})],Se.prototype,"muteRemoteAudio",1),Z([Tp(...At.TRTC.setRemoteAudioVolume),Ng(200,e=>e),tt({getRemoteId:e=>e})],Se.prototype,"setRemoteAudioVolume",1),Z([cu("start"),ro(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),mo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Jl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Se.prototype,"startPlugin",1),Z([cu("update"),ns((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>zl[e.getName()]})],Se.prototype,"updatePlugin",1),Z([cu("stop"),po((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),tt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Xl[e.getName()]})],Se.prototype,"stopPlugin",1),Z([Tp(...At.TRTC.enableAudioVolumeEvaluation)],Se.prototype,"enableAudioVolumeEvaluation",1),Z([tt()],Se.prototype,"getVideoSnapshot",1),Z([tt()],Se.prototype,"_setCurrentSpeaker",1),Z([mo(e=>`a${e.userId}`,()=>!0)],Se.prototype,"_startRemoteAudio",1),Z([xe(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Te(X({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),po(e=>`a${e.userId}`)],Se.prototype,"_stopRemoteAudio",1),Z([po("room")],Se.prototype,"_exitRoom",1),Z([po("screen")],Se.prototype,"_stopScreenShare",1),Z([wt(...At.TRTC.sendSEIMessage),lp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Se.prototype,"sendSEIMessage",1),Z([wt(At.TRTC.sendCustomMessage),lp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Se.prototype,"sendCustomMessage",1),Z([wt(At.TRTC.create)],Se,"_create",1);var wp=Se,un=wp;var Iu=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 Si(t,this),this.remoteVideoTrack=new ao(t,this),this.remoteAuxiliaryTrack=new Jd(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 Ln(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 Mp=class{constructor(){u(this,"_set",new Set);V.on(U.LEAVE_SUCCESS,this.delete,this),V.on(U.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,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))}handleSwitchRoomSuccess({room:t,currentRoomId:e,targetRoomId:r}){t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,e,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,r,t.sdkAppId,t.useStringRoomId)))}};function MS(){return y(this,null,function*(){let i,t;try{let E=yield Qt();i=E&&E.length}catch(E){}try{let E=yield or();t=E&&E.length}catch(E){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,c=eo.basis(),l={webRTC:c.isWebRTCSupported,getUserMedia:c.isGetUserMediaSupported,webSocket:c.isWebSocketsSupported,screenShare:c.isScreenShareSupported,webAudio:c.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},m={browser:c.browser,os:c.os,trtc:l,devices:e},f={isWebCodecSupported:c.isWebCodecSupported,isMediaSessionSupported:c.isMediaSessionSupported,isWebTransportSupported:c.isWebTransportSupported};je.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),je.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(f)}`,userId:this.userId})})}function Fg(){return xe(i=>{let t=new Mp;return function(e,r,o){return y(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 ue({code:q.INVALID_OPERATION,message:Be({key:$e.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ue({code:q.INVALID_OPERATION,message:Be({key:$e.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}`),V.emit(U.JOIN_START,{room:this,roomId:s,params:e});let n=Vr.getEnv();n||(n=ti.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(_c.OLD_CLOUD_LADDER)?n=ti.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(_c.WEBRTC)&&(n=ti.WEBRTC))),je.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),eo.checkSystemRequirementsInternal(o).then(c=>{this.checkSystemResult=c,MS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Vr.getEnv()&&(yield this.schedule(e,o));let c=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Vr.performanceNow(),V.emit(U.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&je.uploadEvent({log:`stat-conv-${Number(vr)}-${location.hostname}`,userId:this.userId}),c}catch(c){throw t.delete({room:this,roomId:s}),V.emit(U.JOIN_FAILED,{room:this,error:c}),c}})}})}var $g=()=>xe(i=>function(...t){return y(this,null,function*(){V.emit(U.LEAVE_START,{room:this}),yield i.call(this,...t),V.emit(U.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Bg(){return xe(i=>function(...t){return y(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="ready"),!t.length))return;V.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function Hg(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function Wg(){return xe(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function OS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Ji(r)?r.catch(o=>$.error(`${i.name}() error observed ${o}`)):r}catch(r){$.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=$.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&We(this[e])&&(this[e]=OS({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:at,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,$o().then(t=>{this._basicInfo.string_os_version=Bo(),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),V.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===D.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(U.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(U.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(U.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).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,c=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&c&&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)=>V.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),vt.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&&(P(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),P(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),P(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:c,request:l,response:m}=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=c,this._pathJoinRoom.int32_schedule_request=l,this._pathJoinRoom.int32_schedule_response=m}}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 ue?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())}handleSwitchRoomStart(t){if(this.hitTest(t.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:t}){if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:t,error:e}){if(this.hitTest(t)){let r=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=r,this._pathJoinRoom.uint64_end_time=r,e&&(this._pathJoinRoom.int32_end_ret=e instanceof ue?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN)}}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:Te(X({},xS),{msg_user_info:new Ha({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:c}=e,l=new Ha({userId:s,tinyId:n,role:c==="anchor"?20:21}),m=Date.now(),f=`${s}_${r}`,E=this._remoteStreamStatMap.get(f);E&&E.subscribeStartTime===0&&(E.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(f)&&this._pathMainVideoMap.set(f,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:m}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(f)&&this._pathMainAudioMap.set(f,{statsToReport:{msg_user_info:l,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:m})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(f)&&this._pathAuxiliaryMap.set(f,{sendSubscribeCMDTime:m})}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 c=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=c,Q.addNumber({key:516820,value:c})}}(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 c=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(c)c.totalRTT+=e,c.totalLoss+=r,s&&(c.totalVideoDelay=(c.totalVideoDelay||0)+s,c.videoDelayCount=(c.videoDelayCount||0)+1),n&&(c.totalAudioDelay=(c.totalAudioDelay||0)+n,c.audioDelayCount=(c.audioDelayCount||0)+1),c.count++;else{let l,m,f,E;s&&(m=s,f=1),n&&(l=n,E=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:l,totalVideoDelay:m,audioDelayCount:E,videoDelayCount:f})}}))}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:c,uint32_video_height:l}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=c,this._localStreamStat.totalVideoHeight+=l,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/pi*100)>0&&(this._localStreamStat.totalAudioLevel+=s/pi,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:c,msg_video_status:l}=s,m=n.str_identifier,f=this._room.remotePublishedUserMap.get(m);if(l.forEach(E=>{let _=E.uint32_video_stream_type===2,v=E.uint32_video_stream_type===7,k=`${m}_${_?"main":"auxiliary"}`,M=this._remoteStreamStatMap.get(k);if(M&&(_&&(f!=null&&f.remoteVideoTrack.isSubscribed)||v&&(f!=null&&f.remoteAuxiliaryTrack))){M.totalVideoFPS+=E.uint32_video_receive_fps,M.totalVideoBitrate+=E.uint32_video_codec_bitrate,M.videoCount++,M.statsToReport.uint32_video_width===0&&(M.statsToReport.uint32_video_width=E.uint32_video_width),M.statsToReport.uint32_video_height===0&&(M.statsToReport.uint32_video_height=E.uint32_video_height);let N=_?f.remoteVideoTrack:f.remoteAuxiliaryTrack;N.stat.jitterBufferDelay&&(M.videoJitterBufferDelay=N.stat.jitterBufferDelay),N.stat.framesReceived&&(M.statsToReport.uint32_video_consume_render_rate=Math.floor(N.stat.framesDecoded/N.stat.framesReceived*Gi(10,6)))}}),!Cs(c)){let E=`${m}_main`,_=this._remoteStreamStatMap.get(E);this._remoteStreamStatMap.has(E)&&_&&f!=null&&f.remoteAudioTrack.isSubscribed&&(_.totalAudioBitrate+=c.uint32_audio_codec_bitrate,_.audioCount++,f.remoteAudioTrack.stat.jitterBufferDelay&&(_.audioJitterBufferDelay=f.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(c.uint32_audio_level/pi*100)>0&&(_.totalAudioLevel+=c.uint32_audio_level/pi,_.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 ue?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&As)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&bs)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Dn)>=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:f,count:E,audioDelayCount:_,videoDelayCount:v,totalAudioDelay:k,totalVideoDelay:M}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(f/E),_&&k&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(k/_),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),v&&M&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(M/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,D.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,D.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,cs));let{badCaseDetector:n}=this._room,{dataFreeze:c,count:l}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=l,t.statsToReport.uint32_video_block_time=Math.min(c,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(m,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>cs&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),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>cs&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+cs)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>cs&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+cs)}getReportData(){this._basicInfo.uint32_networkType=Ac();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Ha({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ns(this._signalInfo.relayIp),uint32_client_ip:Ns(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Gi(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:Ns(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Vn(t),t}report(){return y(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 y(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield dl(t),o=r instanceof ArrayBuffer,s=`${si(e,qi.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let c=[this.uploadKVStat(Q),this.uploadKVStat(qo)];n||c.push(ai({url:s,body:r,priority:"low"})),yield Promise.all(c)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Te(X({},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 dl(e),o=`${si(+this._room.sdkAppId,qi.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||ai({url:o,body:r})})}};Z([zo({settings:{timeout:500,retries:3}})],Su.prototype,"upload",1);var cs=5e3,xS={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},Ha=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}},Gg=Su;var Op=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Ie())}stop(){this._endTime===0&&(this._endTime=Ie())}getDuration(){return this._endTime===0?Ie()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},yu=Op;var xp=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`,D.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,D.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,D.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,D.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,D.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 yu,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===D.AUDIO?[s]:[],video:e===D.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()}},jg=xp;var Pp=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!==D.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===D.MUTE?this.onVideoTrackMuted(t):r===D.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(U.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>V.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>V.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 yu;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let c=this.durationItemList[this.durationItemList.length-1];return c&&c.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(c=>{c.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.uint32_video_dec_fps,type:"main"}),c.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:c.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>Sc?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 y(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let c=Ie();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:c,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:c,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let c=n.freezeTimeline.pop();if(c){c.endTime=Ie();let l=c.endTime-c.startTime;n.freezeTimeline.push(c),n.renderFreezeTotal+=Math.min(5e3,l)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==D.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()<Sc&&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=Ie(),n=e.freezeTimeline[e.freezeTimeline.length-1],c=s-n.startTime;r=e.renderFreezeTotal+Math.min(c,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()}},qg=Pp;var zg=ji(Zi(),1);var PS=[1,0,0,0,1,1,0,1],Au=class extends Gt{constructor(e,r,o,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:r});u(this,"mirror",!1);u(this,"rotation",0);if(o&&(this.mirror=o),s&&(this.rotation=s),e instanceof Tt)try{this.setTexBuffer(PS)}catch(n){e.destroy(new ue({code:q.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,r,o,s,n){if(this.ctx2d){this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let c=super.draw2d(e,r,o,s,n);return this.ctx2d.restore(),c}return!1}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var kp=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}},Wa=class extends Gt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,matchInputSize:!1,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new kp(e,r);this.inputs[r.zIndex]=o}changeInputLayout(e,r){let o=this.inputs.findIndex(s=>s?s.node===e:!1);o<0||Object.entries(r).forEach(([s,n])=>{P(n)||(this.inputs[o].layout[s]=n)})}resize(e,r){if(!this.matchInputSize){super.resize(e,r);return}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 Tt&&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.matchInputSize&&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==null?void 0:n.node.requestFrame(e))||s,!1)&&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==null?void 0:s.node.requestFrame(e))||o,!1)&&this.ctx2d){this.ctx2d.fillStyle="black",this.ctx2d.fillRect(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:c}=this,l=Date.now(),m=(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:m,name:c},X({parent:this.inputs.filter(f=>f).map(f=>f.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 Tt))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var bu=class{constructor(t,e,r,o,s=4/3){this.vbMode=t;this.faceDetectorHash=e;this.visionTaskRegistry=r;this.logger=o;u(this,"animationState");u(this,"originalAspect");u(this,"totalOffsetX",0);u(this,"totalOffsetY",0);u(this,"defaultScaleRatio",.1);u(this,"isRecovering",!1);u(this,"boundaryY",280);u(this,"lastActionTime",0);u(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=s||4/3}addEvent(t,e,r){let s=[{key:570704,error:r!=null?r:e?void 0:11},{key:570705,error:r!=null?r:e?void 0:22}][t-1];s&&(e?Q.addSuccessEvent({key:s.key}):Q.addFailedEvent({key:s.key,error:s.error}))}actionCentering(t){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:r,videoHeight:o}=t;this.animationState.debounceThreshold=r/30,this.animationState.movementThreshold=r/20,this.boundaryY=o*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(r,o);return}let n=s.detections[0].boundingBox,c=n.originX,l=n.originY,m=n.width,f=n.height;this.vbMode===1?this.dualStageCropping(r,o,c,l,m,f):this.vbMode===2&&this.movingPortrait(r,o,c,l,m,f)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(t,e,r,o){let s,n;return t>e/2?(s=e-r-o,n=r-s):(s=r,n=0),{min:s,offset:n}}calculateTargetPosition(t,e,r,o,s,n,c=.4){let l=t+r/2,m=e+o/2,f,E,{min:_,offset:v}=this.calculateBoundary(l,s,t,r),{min:k,offset:M}=this.calculateBoundary(m,n,e,o);return f=2*_+r,E=2*k+o,f/E>this.originalAspect?(f=E*this.originalAspect,v=l-f/2):(E=f/this.originalAspect,M=m-E/2),r/s>c&&(v=0,M=0,f=s,E=n),v=Math.max(0,Math.min(v,s-f)),M=Math.max(0,Math.min(M,n-E)),{sx:v,sy:M,cropWidth:f,cropHeight:E,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let c={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=c,this.animationState.target=c;return}let o=this.positionDistance(this.animationState.target,t),s=this.positionDistance(this.animationState.current,t),n=this.animationState.current.cropWidth/e;o>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(t){if(!this.animationState.current||!this.animationState.target){this.animationState.current=X({},t),this.animationState.target=X({},t);return}let e=this.positionDistance(this.animationState.current,t),r=this.positionDistance(this.animationState.target,t);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&r>this.animationState.movementThreshold&&(this.animationState.current=t,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let t=Date.now()-this.animationState.startTime,e=Math.min(t/this.animationState.duration,1),r=o=>o<.5?2*o*o:-1+(4-2*o)*o;if(this.animationState.current&&this.animationState.target){let o=(this.animationState.target.sx-this.animationState.current.sx)*r(e);this.animationState.current.sx+=o,this.totalOffsetX+=o;let s=(this.animationState.target.sy-this.animationState.current.sy)*r(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*r(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*r(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*r(e)),ke(this.animationState.current.scaleOffsetX)&&ke(this.animationState.target.scaleOffsetX)&&ke(this.animationState.current.scaleOffsetY)&&ke(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*r(e);this.animationState.current.scaleOffsetX+=n;let c=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=c}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(Gi(t.sx-e.sx,2)+Gi(t.sy-e.sy,2))}recoverOriginal(t,e){this.animationState.target={sx:0,sy:0,cropWidth:t,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(t,e,r,o,s,n,c=.3){if(this.isRecovering)return;let l=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(l,t,e),s*n/l.cropWidth/l.cropHeight>c&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var l,m,f,E,_,v,k,M,N,B,ee,me;let c={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(m=(l=this.animationState.current)==null?void 0:l.scaleRatio)!=null?m:1,scaleOffsetX:(E=(f=this.animationState.current)==null?void 0:f.scaleOffsetX)!=null?E:0,scaleOffsetY:(v=(_=this.animationState.current)==null?void 0:_.scaleOffsetY)!=null?v:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(M=(k=this.animationState.target)==null?void 0:k.scaleRatio)!=null?M:1,scaleOffsetX:(B=(N=this.animationState.target)==null?void 0:N.scaleOffsetX)!=null?B:0,scaleOffsetY:(me=(ee=this.animationState.target)==null?void 0:ee.scaleOffsetY)!=null?me:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/t/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(c)}set aspectRatio(t){this.originalAspect=t}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var kS=`#version 300 es
|
|
62
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{Jp[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var uL=Object.keys(Jp);var BE=0,Uc,Cn=class Cn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++BE}`}),this.log.info("created")}getName(){return Cn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return f(this,arguments,function*({forceOpen:i}){E(i)&&(i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor()))})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){var i;if(!this.dialog)try{if(Uc)yield Uc;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Hp}@${we}/assets/debug-dialog.js`;Uc=this._core.fileDownloader.loadScript(e),yield Uc}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):Zu,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Ku,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return Zu({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 Ku({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(Cn,"Name","Debug"),d(Cn,"autoStart",!0);var Vc=Cn;var qp=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Bc=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=me(e,$.INIT),this.stopOB=nt(),this.startOB=nt(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=nt(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ue(l,He(this.stopOB),be(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:qp(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),ue(l,Yi(1),yu(fn))};ue(this.startOB,mn(0),Xo(a),He(this.stopOB),be(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:qp(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 Qi()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},FE={type:"object"},Rn=class Rn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Rn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Rn.Name}getValidateRule(i){return FE}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 Bc(this.core,t,i);return ue(r.trackDoneOB,Yi(1),be(()=>{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 Bc(this.core,i.track,i))}}};d(Rn,"Name","TRTCAudioDecoder");var yn=Rn;var Fc=class{constructor(){d(this,"log");this.log=y.createLogger({id:"exp"})}call(i,e){return f(this,null,function*(){return ne(this[i])?this[i](e):Promise.reject(new b({code:I.INVALID_PARAMETER,message:P({key:L.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return f(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isAvailable){if(l.get(h.userId))return;let m=c.getPCM(_=>{e.emit(k.AUDIO_FRAME,_)},h.userId);l.set(h.userId,m)}});else{if(l.get(r))return;let h=c.getPCM(m=>{e.emit(k.AUDIO_FRAME,m)},r);l.set(r,h)}else if(r==="*")e.room.remotePublishedUserMap.forEach(h=>{if(h.remoteAudioTrack.isSubscribed){let{userId:m}=h,_=l.get(m);_==null||_.abort("disable"),l.delete(m)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}};D([Ep({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"}}})],Fc.prototype,"enableAudioFrameEvent",1);var jp=new Fc;var Xp=0,bn=new Set,$e=null;sd($p);wo.checkStorage();var HE={RtcError:x,ErrorCode:U,ErrorCodeDictionary:kt},X=class X extends zp.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",y.createLogger({id:`t${++Xp}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(v({logger:this._log,frameWorkType:X.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,de(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(wc,t.assetsPath),this._use(Mc,t.assetsPath),this._use(Lc,t.assetsPath),this._use(yn,t.assetsPath),this._use(Vc),t.enableSEI&&Ys&&this._use(Pc),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(k.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new x({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Up(this,"trtc")}static create(e){}static _create(e,t){Ap();let r=new X(e,t||{});return bn.add(r),r}get room(){return this._room}_listenEvents(){Qe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(k.REMOTE_USER_ENTER,{userId:t})}).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,x.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(k.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=w(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,As),downlinkRTT:Math.min(e.downlinkRTT,As)});this.emit(k.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Qe(r,r).add("player-state-changed",s=>{let n=w(v({},s),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=_r(r.streamType)),this.emit(r.kind===p.AUDIO?k.AUDIO_PLAY_STATE_CHANGED:k.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(k.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{ve(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?k.REMOTE_AUDIO_AVAILABLE:k.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?k.REMOTE_VIDEO_AVAILABLE:k.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(k.SEI_MESSAGE,w(v({},e),{streamType:_r(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(k.ERROR,new x({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,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||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,As),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((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(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/Et,point2pointDelay:(m.msg_audio_status.uint32_audio_p2p_delay||0)+(m.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:m.msg_audio_status.uint32_audio_cache_ms||0},video:m.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(k.STATISTICS,r)}).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,w(v({},e),{streamType:_r(e.streamType)}))}).add("audio-frame",e=>{this.emit(k.AUDIO_FRAME,e)}),Qe(this,Pe).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=>f(this,null,function*(){if(this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),$e&&$e.deviceId===Is){let t=(yield pr()).find(r=>r.deviceId===Is);t&&$e.groupId!==t.groupId&&($e=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield pr())[0];if(!t||!$e||$e.groupId===t.groupId)return;let r=$e.deviceId===e.deviceId,s=$e.deviceId===Is&&$e.deviceId===t.deviceId;(r||s)&&($e=t,this.emit(k.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)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(Pp.call(this,{TRTC:X,room:this._room,errorModule:HE,assetsPath:t}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!te(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,de(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,X.frameWorkType),this._checkTrackToPublish(),Wu.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())yield this._room.switchRoom(e);else{yield this.exitRoom();let t=v(v({},this.enterRoomParams),e);yield this.enterRoom(t)}})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){ve(this),this.removeAllListeners(),this._room.destroy(),bn.delete(this),bn.size===0&&Wu.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 f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new Ct(this._room.audioManager),a={},c={muted:!0};s&&(E(s.microphoneId)?E(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&q(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),E(s.profile)||(te(s.profile)?Fn[s.profile]&&n.setProfile(Fn[s.profile]):n.setProfile(s.profile)),q(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),E(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),E(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),E(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),de(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(k.ERROR,new x({code:U.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 u;l.error&&(u=x.convertFrom(l.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},l),{error:u}))}),n.on("6",()=>{this.emit(k.ERROR,new x({code:U.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),E(r)||n.setMute(r),Qe(n,n).add("player-state-changed",l=>{this.emit(k.AUDIO_PLAY_STATE_CHANGED,w(v({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):E(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),E(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),E(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!E(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),E(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),oi(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),ve(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var h;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new Be(this._room.videoManager),l={},u={};de(a==null?void 0:a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a&&(a.cameraId?l.deviceId=a.cameraId:E(a.useFrontCamera)?E(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,E(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=Sn(a.qosPreference)),E(a.profile)||(te(a.profile)?Lt[a.profile]&&c.setProfile(Lt[a.profile]):c.setProfile(a.profile)),E(a.fillMode)||(u.objectFit=a.fillMode),E(a.mirror)||(u.mirror=a.mirror),E(a.small)||(E(a.smallMode)||(this._room.smallMode=a.smallMode),de(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(ts(a.small,!0))),E(a.rotation)||c.setRotation(a.rotation),de(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",m=>{this.emit(k.FIRST_VIDEO_FRAME,w(v({},m),{streamType:_r(m.streamType)}))}),c.on("5",m=>{this.emit(k.ERROR,new x({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:m}}))}),c.on("2",m=>{this.emit(k.DEVICE_CHANGED,{type:"camera",action:"active",device:m})}),c.on("4",m=>{let _;m.error&&(_=x.convertFrom(m.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},m),{error:_}))}),c.on("6",()=>{this.emit(k.ERROR,new x({code:U.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(h=c.manager)==null||h.changeInput(c),E(n)||(yield c.setMute(n)),Qe(c,c).add("player-state-changed",m=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,w(v({},m),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=w(v({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return f(this,null,function*(){var l,u,h;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):E(a==null?void 0:a.useFrontCamera)?E(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let m={};m.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),m.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?p.FACING_MODE_USER:p.FACING_MODE_ENVIRONMENT,m.customSource=(a==null?void 0:a.videoTrack)||((h=this._localVideoConfig.option)==null?void 0:h.videoTrack),yield this._localVideoTrack.capture(m)}a&&(E(a.profile)||(te(a.profile)?Lt[a.profile]&&this._localVideoTrack.setProfile(Lt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&E(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),E(a.fillMode)||(c.objectFit=a.fillMode),E(a.mirror)||(c.mirror=a.mirror),E(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Sn(a.qosPreference)),E(a.small)||(de(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(ts(a.small,!0)))),this._room.isJoined&&E(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),E(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),oi(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),ve(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Ze(this._room.videoManager);a.on("4",m=>{let _;m.error&&(_=x.convertFrom(m.error)),this.emit(k.PUBLISH_STATE_CHANGED,w(v({},m),{error:_}))}),a.once("first-video-frame",m=>{this.emit(k.FIRST_VIDEO_FRAME,w(v({},m),{streamType:_r(m.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(E(n.profile)||(te(n.profile)?Hn[n.profile]&&a.setProfile(Hn[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),E(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=Sn(n.qosPreference)));let h=yield a.capture(l);if(a.mediaTrack.addEventListener(p.ENDED,()=>{this._stopScreenShare(),this.emit(k.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(c=new Ii(this._room.audioManager),yield c.setInputMediaStreamTrack(h.getAudioTracks()[0]),de(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)),Qe(a,a).add("player-state-changed",m=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,w(v({},m),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let m=[a];c&&(m.push(c),this._checkScreenAudioEchoCancellation(a,c)),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=w(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return f(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(E(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=Sn(n.qosPreference);this._localScreenTrack.setContentHint(l)}this._room.isJoined&&!E(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(()=>{}))),(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&de(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),oi(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",h=>{this.emit(k.ERROR,new x({code:U.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),this._listenOutputTrackChanged(u),n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror),E(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!E(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!E(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var T,O;let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(E(n.fillMode)||(l.objectFit=n.fillMode),E(n.mirror)||(l.mirror=n.mirror));let u=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(u=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:m}=c;s==="main"&&n&&!E(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:m}),oi(m,e);let _=E(n==null?void 0:n.receiveWhenViewVisible)?(T=m.option)==null?void 0:T.receiveWhenViewVisible:n.receiveWhenViewVisible,A=E(t)?m.view:t,g=E(n==null?void 0:n.viewRoot)?(O=m.option)==null?void 0:O.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:A,receiveWhenViewVisible:_,viewRoot:g})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(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,...t){try{wp.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===X.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(X.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(te(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield pr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),$e=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",a=>{this.emit(k.ERROR,new x({code:U.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let a=this._remoteAudioVolumeMap.get(t),c=q(a)?a:100;s.volume=c,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),ue(me(n,"decode-failed"),He(me(n,$.INIT)),be(()=>{this.startPlugin(yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ue(me(e,"decode-failed"),He(me(e,$.INIT)),vu(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),zr(me(e,"decode-downgrade-state-changed")),be(n=>{s=n.state,this.emit(k.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,w(v({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),E(e)&&s&&s.view&&!fo(t)){let a=go(s.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=go(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(E(e.muted)||t.setPlayerMute(e.muted),E(e.volume)||t.setAudioVolume(e.volume/100),t instanceof Ct&&t.mediaTrack){let n=e.muted===!1&&!E(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof Qt){let n=e.muted?0:e.volume;if(E(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(k.TRACK,{userId:r,streamType:_r(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:s}){if(E(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${_r(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Se(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!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(m=>{m.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(A=>A)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(go(t));l.forEach((m,_)=>{h.has(_)||(a.unobserve(_),l.delete(_))}),h.forEach(m=>{l.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{l.set(m.target,m.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),Vp(this),this._room.remotePublishedUserMap.forEach(e=>{ve(e.remoteAudioTrack),ve(e.remoteVideoTrack),ve(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e,t;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&&(((t=this._localScreenAudioTrack.trackSettings)==null?void 0:t.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),ve(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return f(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!$e||Jo($e))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if($e&&!Jo($e))this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:$e});else{let e=yield pr();e[0]&&!Jo(e[0])?($e=e[0],this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:w(v({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.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})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),jp.call(e,v({trtcInstance:this},t))})}static setLogLevel(e,t){y.setLogLevel(e),E(t)||(t?y.enableUploadLog():y.disableUploadLog())}static isSupported(){return xa(X.frameWorkType)}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return mt(e)}static getSpeakerList(e=!0){return pr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(pe&&(e===Mt.SPEAKER||e===Mt.HEADSET)){let r=yield X.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;bn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield pr()).forEach(r=>{r.deviceId===e&&(bn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),$e=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(Br.version=a),e){case"count":Br.addCount({key:t,useUV:n});break;case"enum":Br.addEnum({key:t,value:r,useUV:n});break;case"number":Br.addNumber({key:t,value:r,split:s,max:c});break}}};d(X,"_loggerManager",y),d(X,"EVENT",k),d(X,"ERROR_CODE",U),d(X,"TYPE",Mt),d(X,"frameWorkType",30),D([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"}})})],X.prototype,"use",1),D([qe(Ue.TRTC.enterRoom),Tr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Y(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),fe()],X.prototype,"enterRoom",1),D([fe()],X.prototype,"exitRoom",1),D([qe(Ue.TRTC.switchRoom),fe(),Nt()],X.prototype,"switchRoom",1),D([qe(Ue.TRTC.switchRole),Kr("room",{merge:(e,t)=>t}),fe()],X.prototype,"switchRole",1),D([fe()],X.prototype,"destroy",1),D([qe(Ue.TRTC.startLocalAudio),Tr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),fe()],X.prototype,"startLocalAudio",1),D([qe(Ue.TRTC.updateLocalAudio),Kr("audio",{debounce:{delay:200,getKey:()=>`${Xp}-localAudio`,isNeedToDebounce:e=>{var t;return!E((t=e.option)==null?void 0:t.captureVolume)}}}),fe()],X.prototype,"updateLocalAudio",1),D([Er("audio"),fe()],X.prototype,"stopLocalAudio",1),D([qe(Ue.TRTC.startLocalVideo),Tr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),fe()],X.prototype,"startLocalVideo",1),D([qe(Ue.TRTC.updateLocalVideo),Kr("video"),fe()],X.prototype,"updateLocalVideo",1),D([Er("video"),fe()],X.prototype,"stopLocalVideo",1),D([qe(Ue.TRTC.startScreenShare),Tr("screen",()=>!0),fe()],X.prototype,"startScreenShare",1),D([qe(Ue.TRTC.updateScreenShare),Kr("screen"),fe()],X.prototype,"updateScreenShare",1),D([fe()],X.prototype,"stopScreenShare",1),D([qe(Ue.TRTC.startRemoteVideo),Tr(e=>`v${e.userId}${e.streamType}`,()=>!0),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],X.prototype,"startRemoteVideo",1),D([qe(Ue.TRTC.updateRemoteVideo),Kr(e=>`v${e.userId}${e.streamType}`),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],X.prototype,"updateRemoteVideo",1),D([qe(Ue.TRTC.stopRemoteVideo),Y(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],X.prototype,"stopRemoteVideo",1),D([Er(e=>`v${e.userId}${e.streamType}`)],X.prototype,"_stopRemoteVideo",1),D([qe(...Ue.TRTC.muteRemoteAudio),fe({getRemoteId:e=>e})],X.prototype,"muteRemoteAudio",1),D([Bu(...Ue.TRTC.setRemoteAudioVolume),Bp(200,e=>e),fe({getRemoteId:e=>e})],X.prototype,"setRemoteAudioVolume",1),D([Dc("start"),st(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Tr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>fl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],X.prototype,"startPlugin",1),D([Dc("update"),Kr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>_l[e.getName()]})],X.prototype,"updatePlugin",1),D([Dc("stop"),Er((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>gl[e.getName()]})],X.prototype,"stopPlugin",1),D([Bu(...Ue.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),D([fe()],X.prototype,"getVideoSnapshot",1),D([fe()],X.prototype,"_setCurrentSpeaker",1),D([Tr(e=>`a${e.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),D([Y(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(w(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Er(e=>`a${e.userId}`)],X.prototype,"_stopRemoteAudio",1),D([Er("room")],X.prototype,"_exitRoom",1),D([Er("screen")],X.prototype,"_stopScreenShare",1),D([qe(...Ue.TRTC.sendSEIMessage),ku({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],X.prototype,"sendSEIMessage",1),D([qe(Ue.TRTC.sendCustomMessage),ku({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],X.prototype,"sendCustomMessage",1),D([qe(Ue.TRTC.create)],X,"_create",1);var eh=X,Nn=eh;var th=class{constructor(){d(this,"_set",new Set);S.on(C.LEAVE_SUCCESS,this.delete,this),S.on(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function $E(){return f(this,null,function*(){let o,i;try{let _=yield mt();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=pi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},h={browser:l.browser,os:l.os,trtc:u,devices:e},m={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(m)}`,userId:this.userId})})}function Qp(){return Y(o=>{let i=new th;return function(e,t,r){return f(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:I.INVALID_OPERATION,message:P({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new b({code:I.INVALID_OPERATION,message:P({key:L.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=_t.getEnv();n||(n=Di.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith($n.OLD_CLOUD_LADDER)?n=Di.OLD_CLOUD_LADDER:this.proxy_ws.startsWith($n.WEBRTC)&&(n=Di.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),pi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,$E.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!_t.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=_t.performanceNow(),S.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(Gt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var Yp=()=>Y(o=>function(...i){return f(this,null,function*(){S.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Zp(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ef=Ge(tt());var Ne={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Zt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161},Kp=[Zt.UPDATE_REMOTE_MUTE_STAT,Zt.UPLINK_NETWORK_STATS,Zt.USER_LIST_RES,Zt.MUTE_RESULT,Zt.SERVER_FIRST_PACKAGE_RECEIVED,Zt.RECEIVE_CUSTOM_MSG],F={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res"},z={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room"};var Hc=new Set;function tf(o){let i=[...Hc.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var ns=class extends ef.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-Hc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Hc.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=y.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 f(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=B();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 Mr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?p.BACKUP:p.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?p.MAIN:p.BACKUP),c(new b({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===p.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(Ne.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(p.MAIN),this.unbindAndCloseSocket(p.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ne.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+=bs(e.data);let t=JSON.parse(e.data),{cmd:r,data:s}=t,n=Object.values(Zt),c=Object.keys(Zt)[n.indexOf(r)],l=F[c]||r;switch(Kp.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Zt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=s.clientIp,this._signalInfo.signalIp=s.signalInnerIp,s.svrTime&&Dh(s.svrTime),this._log.info(`ChannelSetup Success ${B()-this._connectStartTime}`),N.addSuccessEvent({key:521701,cost:B()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ne.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new b({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:P({key:L.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(Ne.SETUP_FAILED,u)}break}case Zt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=s.relayOuterIp,this._signalInfo.relayInnerIp=s.relayInnerIp,this._signalInfo.bakRelayIps=s.bakRelayIps,this._signalInfo.relayPort=s.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=s.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Yt(!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?p.MAIN:p.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:z.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:F.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:B()-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},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=bs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let h=setTimeout(()=>{this.off(s,_);let g=new b({code:I.API_CALL_TIMEOUT,message:P({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(g),u(g)},r),m=Date.now(),_=g=>{g.data.seq===A&&(clearTimeout(h),this.off(s,_),c&&(g.data.receiveTime=Date.now()),l(g))};this.on(s,_);let A=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return ni({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ne.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),Hc.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(p.MAIN),this.unbindAndCloseSocket(p.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(F.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(F.JOIN_ROOM_RESULT,t))};this.on(F.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ne.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ne.CONNECTED):e==="DISCONNECTED"&&this.emit(Ne.DISCONNECTED))}};D([St({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())}})],ns.prototype,"connect",1);var rf=Ge(tt());var ih=0,rh=!1,$c=new Set,WE=o=>ih>2&&!rh&&$c.size===0&&o,oh=!1,at=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new rf.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=y.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=B())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(B()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:B()-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(),$c.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 Pt;let i=null;if(this._isUplink){if(!mr()||this._peerConnection.getSenders().length===0)return Pt;i=this._peerConnection.getSenders()[0].transport}else{if(!Fr()||this._peerConnection.getReceivers().length===0)return Pt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Pt}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===ge.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ge.FAILED||i.target.connectionState===ge.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new b({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===ge.CONNECTED||i.target.connectionState===ge.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:ct.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(ih=0,rh=!1,oh=!0,$c.add(this)):$c.delete(this),S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(hr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new b({code:I.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new b({code:I.API_CALL_TIMEOUT,message:"connection timeout"});ih+=1,WE(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),rh=!0,this._emitter.emit("firewall-restriction")),e(a)},Ss);S.on(C.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ne.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Oi()){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:P({key:this._isUplink?L.UPLINK_RECONNECTION_FAILED:L.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(Ne.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)}};D([pt(521712,!1)],at.prototype,"setOffer",1),D([pt(521713,!1)],at.prototype,"setAnswer",1);var ch=Ge(ah());var Ce=function(o){return ch.default.parse(o)},wt=function(o){return ch.default.write(o)},uf=function(o){let i=Ce(o);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),wt(i)};function hf(o){let i=Ce(o);return i.media.forEach(e=>{var t,r;if(e.type===p.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),wt(i)}function Gc(o){return Object.keys(o).filter(i=>o[i])}var cs=class cs extends at{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Qt(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Ci(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Ko(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return xi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Es?p.MAIN:p.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=p.AUDIO;r.kind===p.VIDEO&&(n=s===p.MAIN?p.VIDEO:p.AUXILIARY);let a=this.remoteAudioTrack;n===p.VIDEO?a=this.remoteVideoTrack:n===p.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
63
|
+
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,c]=s[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
64
|
+
`)}addSPSDescription(e){let t=Ce(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),wt(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=Ce(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),wt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===ge.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===ge.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 f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Gc(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=z.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=z.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:P({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:z.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:F.SUBSCRIBE_RESULT,timeout:_d});if(!this._peerConnection){let a=new b({code:I.INVALID_OPERATION,message:P({key:L.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};ht()&&this._sdpSemantics===dr?(this._peerConnection.addTransceiver(p.AUDIO,{direction:ie.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:ie.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:ie.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield wa();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=hf(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=uf(t.sdp),this._sdpSemantics===dr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Rr)throw new b({code:I.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:P({key:L.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{Ce(e).media.forEach(r=>{if(r.ssrcs)if(r.type===p.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Es)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Es)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ud)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(We(cs.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=Vt(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}};D([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new b({code:I.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],cs.prototype,"subscribe",1),D([pt(521717,!1)],cs.prototype,"unsubscribe",1),D([st(at.prototype.afterConnect),Xa(at.prototype.beforeConnect)],cs.prototype,"connect",1);var dh=cs,lh=dh;var pf={voiceActivityDetection:!1},ds=class ds extends at{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,s,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(hi()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),ht()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||p.AUDIO,{direction:ie.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?p.VIDEO:c||p.VIDEO,{direction:ie.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:ie.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||p.VIDEO:p.VIDEO,{direction:ie.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:p.AUDIO})),c){let m=s?3:1;yield u[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:p.VIDEO,videoType:s?p.AUXILIARY:p.BIG}),h.push(m),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:p.VIDEO,videoType:p.SMALL}),h.push(2))}yield this.setTransceiverDirection(ie.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(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ie.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ie.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!hi()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ie.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:z.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:z.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),mi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),ht()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ie.INACTIVE&&(yield this.setTransceiverDirection(ie.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;hi()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===p.VIDEO&&e instanceof Be&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===ao||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Ce(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===p.VIDEO)return!0;return!1}removeSender(e){let t=null;hi()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ne(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),ht()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ie.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
65
|
+
`).map(l=>{if(l.match(new RegExp(`a=(${ie.INACTIVE}|${ie.RECVONLY}|${ie.SENDONLY})`))&&a++,t.includes(a)){if(e===ie.INACTIVE&&l.includes(`a=${ie.RECVONLY}`))return s=!0,`a=${e}`;if(e===ie.SENDONLY&&l.includes(`a=${ie.INACTIVE}`))return s=!0,`a=${ie.RECVONLY}`}return l}).join(`\r
|
|
66
|
+
`);s&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===p.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===p.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===p.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return f(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(ht()?r=e.kind===p.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${s?p.AUXILIARY:p.MAIN} stream`),e.kind===p.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===p.VIDEO&&(s?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let r=yield this._peerConnection.createOffer(pf);ae&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let s=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===p.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,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:z.PUBLISH_CHANGE,data:n,responseCommand:F.UPDATE_OFFER_RESULT,timeout:fd,commandDesc:"update offer"}),{code:c,message:l}=a.data;c!==0&&this.checkPublishResultCode(c,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:s}){if(!Qs())return s?t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(ht()){let l=0;t===p.VIDEO&&(r===p.SMALL?l=2:r===p.AUXILIARY?l=3:l=1),a=c[l]}else a=c.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`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,t,r){let s="AS";ae&&(s="TIAS",t=t*1e3);let n=0,a=-1;return r===p.SMALL?n=1:r===p.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${s}:${t}\r
|
|
67
|
+
`:c)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return ae&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
68
|
+
c=IN $2\r
|
|
69
|
+
b=${r}:${t}\r
|
|
70
|
+
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(pf);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:z.PUBLISH,responseCommand:F.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Ze||this.localAuxVideoTrack instanceof Ze,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:s,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,s)})}setSDPDirection(e,t,r="all"){let s=Ce(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),wt(s)}acceptAnswer(e){return f(this,null,function*(){var t,r,s,n,a;try{let c;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),m=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let _=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:h,type:p.VIDEO,sdp:c,videoType:_})}m&&(c=yield this.setBandwidth({bandwidth:m,type:p.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:p.VIDEO,videoType:p.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this.setAnswer(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var s,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((s=this.localMainAudioTrack)!=null&&s.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(z.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(We(ds.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:z.UNPUBLISH,responseCommand:F.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=Vt(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(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ce(e).media.forEach((r,s)=>{if(r.type===p.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===ao&&r.ssrcGroups){r.ssrcGroups.forEach((a,c)=>{let l=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=l:c===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(s){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=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Rr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new b({code:I.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new b({code:I.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}};D([Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new b({code:I.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],ds.prototype,"publish",1),D([pt(521715,!1)],ds.prototype,"unpublish",1),D([st(at.prototype.afterConnect),Xa(at.prototype.beforeConnect)],ds.prototype,"connect",1);var uh=ds,Dn=uh;var On=class{constructor(i,e){this.room=i;d(this,"_log");d(this,"_prevReportTime",0);d(this,"_prevReport",{});d(this,"_prevStats",null);d(this,"_prevEncoderImplementation","");d(this,"_prevAuxEncoderImpl","");d(this,"_prevQualityLimitationReason","");d(this,"_prevAuxQualityLimitationReason","");d(this,"_prevDecoderImplementationMap",new Map);d(this,"_decodeMap",new Map);d(this,"totalBytesSent",0);d(this,"totalBytesReceived",0);d(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return f(this,null,function*(){var s;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,m;let c,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===p.VIDEO){if(a.ssrc===r.video?(c=p.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?c=p.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,c=p.AUXILIARY),!c)return;if(e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded,E(a.keyFramesEncoded)||(e[c].keyFramesEncoded=a.keyFramesEncoded),E(a.nackCount)||(e[c].nackCount=a.nackCount),E(a.pliCount)||(e[c].pliCount=a.pliCount),E(a.retransmittedPacketsSent)||(e[c].retransmittedPacketsSent=a.retransmittedPacketsSent),E(a.totalEncodeTime)||(e[c].totalEncodeTime=a.totalEncodeTime),E(a.totalPacketSendDelay)||(e[c].totalPacketSendDelay=a.totalPacketSendDelay),!E(a.encoderImplementation)&&(c===p.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||c===p.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let A=2,g=this._prevEncoderImplementation;c===p.AUXILIARY&&(A=7,g=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:A,prevImplementation:g,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[c===p.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${c===p.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!E(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&&!E(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"?hr(a)&&(this.totalBytesSent=a.bytesSent,q(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===p.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===p.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(p.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!E(a.audioLevel)&&((m=i.localMainAudioTrack)!=null&&m.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!E(a.frameWidth)){let _=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?_=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(_=p.AUXILIARY),e[_].frameWidth=a.frameWidth,e[_].frameHeight=a.frameHeight,e[_].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel(),c=i.localMainAudioTrack.getInternalAudioLevelAfter3A();e.audio.audioCaptureEnergyAfter3a=c,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===p.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===p.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===p.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=((s=this.room.networkQuality)==null?void 0:s.uplinkRTT)||0),e})}getReceiverStats(i){return f(this,null,function*(){var r,s,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,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:c,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{var m,_;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let A=(h.mediaType||h.kind)===p.AUDIO;if(A){if(h.ssrc!==a.audio||!c.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),h.silentConcealedSamples&&(e.audio.silentConcealedSamples=h.silentConcealedSamples);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(ae&&h.bytesReceived===0)return;let g;h.ssrc===a.video&&c.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,i.videoCodec=qt[(m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,g=i.remoteVideoTrack,c.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}(${i.videoCodec}) 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&&c.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.auxiliary.p2pDelay=g.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((_=this._decodeMap.get(h.codecId))==null?void 0:_.mimeType.split("/")[1].toLowerCase())||"h264"),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)),e.video.p2pDelay=g.stat.end2EndDelay)}h.jitterBufferDelay&&(A?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&c.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&c.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&hr(h)&&(this.totalBytesReceived=h.bytesReceived,q(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));E(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)),!E(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),E((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),E((s=i.remoteAuxiliaryTrack.player.stat)==null?void 0:s.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 f(this,null,function*(){let t={},r=[];if(this.room.singlePC){let s=this.room.singlePC.getPeerConnection();if(!s)return{senderStats:t,receiverStats:r};let n=B(),a=yield s.getStats(),c=B();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let l=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec"]);a.forEach(h=>u.has(h.type)&&l.push(h)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[s,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(Ti(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m,_,A;if(!Ti(i.senderStats)){let g={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&&(g.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Et),i.senderStats.audio.audioCaptureEnergyAfter3a&&(g.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Et),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let T=[];if(i.senderStats.video.bytesSent){let K={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};T.push(K)}if(i.senderStats.small.bytesSent){let K={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};T.push(K)}if(i.senderStats.auxiliary.bytesSent){let K={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};T.push(K)}let O={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:g,msg_video_status:T,msg_network_status:O}}let r=(m=Ee())==null?void 0:m.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(g=>{let T={msg_user_info:{str_identifier:g.userId,uint64_tinyid:g.tinyId},msg_network_status:{uint32_rtt:g.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(g.hasAudio){let O={uint32_audio_p2p_delay:g.audio.p2pDelay,uint32_audio_cache_ms:g.audio.totalJitter,uint32_audio_cache_ms_count:g.audio.totalJitterCount,uint32_audio_codec_bitrate:g.audio.bytesReceived,uint32_audio_total_bitrate:g.audio.bytesReceived,uint32_audio_level:g.audio.audioLevel*1e8,uint32_audio_energy:g.audio.totalAudioEnergy*1e6,uint32_audio_receive:g.audio.packetsReceived,uint32_audio_origin_lost:g.audio.packetsLost};T.msg_audio_status=O}if(g.hasVideo){let O=t.get(`${g.userId}_${hd}`),K=O?O.duration:0,G={uint32_video_stream_type:g.isSmallSubscribed?3:2,uint32_video_receive_fps:g.video.framesReceived,uint32_video_width:g.video.frameWidth,uint32_video_height:g.video.frameHeight,uint32_video_codec_bitrate:g.video.bytesReceived,uint32_video_receive:g.video.packetsReceived,uint32_video_origin_lost:g.video.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:g.video.framesDecoded,uint32_video_codec_fps:g.video.fpsRender,uint32_video_cache_ms:g.video.totalJitter,uint32_video_cache_ms_count:g.video.totalJitterCount,uint32_video_p2p_delay:g.video.p2pDelay,uint32_video_codec:g.video.codec};T.msg_video_status.push(G)}if(g.hasAuxiliary){let O=t.get(`${g.userId}_${md}`),K=O?O.duration:0,G={uint32_video_stream_type:7,uint32_video_receive_fps:g.auxiliary.framesReceived,uint32_video_width:g.auxiliary.frameWidth,uint32_video_height:g.auxiliary.frameHeight,uint32_video_codec_bitrate:g.auxiliary.bytesReceived,uint32_video_receive:g.auxiliary.packetsReceived+g.auxiliary.packetsLost,uint32_video_origin_lost:g.auxiliary.packetsLost,uint32_video_block_time:K,uint32_video_dec_fps:g.auxiliary.framesDecoded,uint32_video_codec_fps:g.video.fpsRender,uint32_video_cache_ms:g.auxiliary.totalJitter,uint32_video_cache_ms_count:g.auxiliary.totalJitterCount,uint32_video_p2p_delay:g.auxiliary.p2pDelay,uint32_video_codec:g.video.codec};T.msg_video_status.push(G)}e.msg_down_stream_info.push(T)});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 g=n.msg_up_stream_info.msg_audio_status,T=e.msg_up_stream_info.msg_audio_status;if(g.uint32_audio_codec_bitrate===0)T.uint32_audio_codec_bitrate=0;else{let O=this.getDifferenceValue(g.uint32_audio_codec_bitrate,T.uint32_audio_codec_bitrate);T.uint32_audio_codec_bitrate=Math.round(O*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=T.uint32_audio_codec_bitrate}(_=n.msg_device_info)!=null&&_.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s):delete e.msg_device_info.uint32_audio_capture_cost}let c=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(g=>{let T=c.find(_e=>_e.uint32_video_stream_type===g.uint32_video_stream_type);if(!T||T.uint32_video_codec_bitrate===0){g.uint32_video_codec_bitrate=0,g.uint32_video_enc_fps=0,g.uint32_video_codec_fps=0;return}let O=0,K=0,G=0;T&&g.uint32_video_codec_bitrate>=T.uint32_video_codec_bitrate&&(O=T.uint32_video_codec_bitrate,K=T.uint32_video_enc_fps,G=T.uint32_video_codec_fps);let ee=this.getDifferenceValue(O,g.uint32_video_codec_bitrate);g.uint32_video_codec_bitrate=Math.round(ee*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=g.uint32_video_codec_bitrate,g.uint32_video_enc_fps=Math.round(this.getDifferenceValue(K,g.uint32_video_enc_fps)/s),g.uint32_video_codec_fps=Math.round(this.getDifferenceValue(G,g.uint32_video_codec_fps)/s),T.uint32_video_width===0&&T.uint32_video_height===0&&T.uint32_video_codec_fps===0&&(g.uint32_video_codec_fps=g.uint32_video_enc_fps),E(T.uint32_key_frame_count)||(g.uint32_key_frame_count=Math.round(this.getDifferenceValue(T.uint32_key_frame_count,g.uint32_key_frame_count))),E(T.uint32_nack_count)||(g.uint32_nack_count=Math.round(this.getDifferenceValue(T.uint32_nack_count,g.uint32_nack_count))),E(T.uint32_pli_count)||(g.uint32_pli_count=Math.round(this.getDifferenceValue(T.uint32_pli_count,g.uint32_pli_count))),E(T.uint32_video_arq_packets)||(g.uint32_video_arq_packets=Math.round(this.getDifferenceValue(T.uint32_video_arq_packets,g.uint32_video_arq_packets))),E(T.uint32_encode_cost)||(g.uint32_encode_cost=Math.round(this.getDifferenceValue(T.uint32_encode_cost,g.uint32_encode_cost)/s)),E(T.uint32_send_packet_cost)||(g.uint32_send_packet_cost=Math.round(this.getDifferenceValue(T.uint32_send_packet_cost,g.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(g=>u.find(T=>T.msg_user_info.uint64_tinyid===g.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;return h.forEach(g=>{let T=u.find(O=>O.msg_user_info.uint64_tinyid===g.msg_user_info.uint64_tinyid);if(!Ti(g.msg_audio_status)&&!Ti(T.msg_audio_status)){let O=g.msg_audio_status,K=T.msg_audio_status,G=this.getDifferenceValue(K.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms_count);delete O.uint32_audio_cache_ms_count,O.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(K.uint32_audio_cache_ms,O.uint32_audio_cache_ms)/G)||0;let ee=this.room.remotePublishedUserMap.get(g.msg_user_info.str_identifier);ee&&(ee.remoteAudioTrack.stat.jitterBufferDelay=O.uint32_audio_cache_ms),O.uint32_audio_origin_lost=this.getDifferenceValue(K.uint32_audio_origin_lost,O.uint32_audio_origin_lost),O.uint32_audio_receive=this.getDifferenceValue(K.uint32_audio_receive,O.uint32_audio_receive),O.uint32_audio_receive+=O.uint32_audio_origin_lost;let _e=this.getDifferenceValue(K.uint32_audio_codec_bitrate,O.uint32_audio_codec_bitrate);O.uint32_audio_codec_bitrate=Math.round(_e*8/s),O.uint32_audio_total_bitrate=Math.round(_e*8/s)}else g.msg_audio_status={};if(g.msg_video_status&&T.msg_video_status){let O=T.msg_video_status;g.msg_video_status=g.msg_video_status.filter(G=>O.find(ee=>ee.uint32_video_stream_type===G.uint32_video_stream_type)),g.msg_video_status.forEach(G=>{let ee=O.find(Qf=>Qf.uint32_video_stream_type===G.uint32_video_stream_type),_e=ee.uint32_video_receive,J=ee.uint32_video_origin_lost,Wf=ee.uint32_video_codec_bitrate,Jf=ee.uint32_video_receive_fps,qf=ee.uint32_video_dec_fps;G.uint32_video_origin_lost=this.getDifferenceValue(J,G.uint32_video_origin_lost),G.uint32_video_receive=this.getDifferenceValue(_e,G.uint32_video_receive)+G.uint32_video_origin_lost;let jf=this.getDifferenceValue(Wf,G.uint32_video_codec_bitrate);G.uint32_video_codec_bitrate=Math.round(jf*8/s);let Xf=this.getDifferenceValue(Jf,G.uint32_video_receive_fps);G.uint32_video_receive_fps=Math.round(Xf/s),G.uint32_video_dec_fps=Math.round(this.getDifferenceValue(qf,G.uint32_video_dec_fps)/s);let zf=this.getDifferenceValue(ee.uint32_video_cache_ms_count,G.uint32_video_cache_ms_count);delete G.uint32_video_cache_ms_count,G.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(ee.uint32_video_cache_ms,G.uint32_video_cache_ms)/zf)||0})}}),(A=n.msg_device_info)!=null&&A.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)/s):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(g=>{if(g.audio.concealedSamples&&g.audio.totalSamplesReceived){let T=a.receiverStats.find(O=>O.userId===g.userId);if(T&&T.audio.concealedSamples&&T.audio.totalSamplesReceived){let O=(g.audio.silentConcealedSamples||0)-(T.audio.silentConcealedSamples||0),K=g.audio.concealedSamples-T.audio.concealedSamples,G=g.audio.totalSamplesReceived-T.audio.totalSamplesReceived,ee=Math.floor((K-O)/G*1e3*s);if(ee>s*1e3/5){let _e=h.find(J=>J.msg_user_info.str_identifier===g.userId);_e&&(_e.msg_audio_status.uint32_audio_block_time=ee)}}}}),e}getStatsReport(r){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let s={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,uint32_audio_capture_energy_after3a: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(s))),this.prepareReport({stats:n,report:s,freezeMap:t}),this._prevReportTime=Date.now(),s})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var gf=Ge(tt());function ff(o){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===o){let r=Math.round(t.duration),s=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,c=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),m=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=w(v({},i),{totalCost:r,local:s,redirect:n,httpCache:a,dns:c,tcp:u,tls:l,request:h,response:m});break}}catch(e){}return i}function _f(o){return new Promise(i=>f(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://${o}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let s=ff(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var eS=700,to=class to extends gf.default{constructor({signalChannel:e,room:t}){super();d(this,"_room");d(this,"_signalChannel");d(this,"_log");d(this,"uplinkRTT",0);d(this,"uplinkLoss",0);d(this,"downlinkRTT",0);d(this,"downlinkLoss",0);d(this,"pingResults",{});d(this,"_downlinkPrevStatMap",new Map);d(this,"_downlinkLossAndRTTMap",new Map);d(this,"_interval",-1);d(this,"_uplinkNetworkQuality",0);d(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=y.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(F.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ne.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,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=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let s=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=s-n;s===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/s*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return f(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===ge.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h});continue}let m=0,_=this._downlinkPrevStatMap.get(c),A=u-_.totalPacketsLost,g=h-_.totalPacketsReceived;A<=0||g<0?m=0:m=Math.round(A/(A+g)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(c,{rtt:l,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:s,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=s,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,s)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Fr())return t;let r=e.getReceivers();try{for(let s=0;s<r.length;s++)(yield r[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&q(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===p.AUDIO||c.mediaType===p.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(s){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===ge.DISCONNECTED||e.connectionState===ge.FAILED||e.connectionState===ge.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(C.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=w(v({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(to.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-to.lastPingTime>t.interval*1e3){to.lastPingTime=Date.now();let a=t.domain.map(c=>_f(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>eS),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{N.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(c)}`)}).catch(c=>{this._log.warn(`Error during pinging domains: ${c}`)})}},{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:s,audioDelay:n})=>{let a=t.get(r);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:n})}})}};d(to,"EVENT_NETWORK_QUALITY","0"),d(to,"lastPingTime",0);var ls=to;function tS({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return lr(t)?t.catch(r=>y.error(`${o.name}() error observed ${r}`)):t}catch(t){y.error(`${o.name}() error observed ${t}`)}}}var Wc=class{constructor(i){d(this,"_frameWorkType");d(this,"_component");d(this,"_language");d(this,"connectionType");d(this,"_room");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_keyPrefix");d(this,"_log");d(this,"_intervalId");d(this,"_firstPublishedUserList");d(this,"_networkQuality");d(this,"_basicInfo");d(this,"_pathJoinRoom");d(this,"_pathLeaveRoom");d(this,"_pathMainVideoMap");d(this,"_pathMainAudioMap");d(this,"_pathAuxiliaryMap");d(this,"_remoteStreamStatMap");d(this,"_localStreamStat");d(this,"_eventMap",new Map);d(this,"_captureCostSum",0);d(this,"_captureCostCount",0);d(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=y.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ne(this[e])&&(this[e]=tS({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:we,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,xr().then(i=>{this._basicInfo.string_os_version=Hi(),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(C.JOIN_START,this.handleJoinStart).addEvent(C.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(C.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(C.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(C.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(C.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(C.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(C.JOIN_FAILED,this.handleJoinFailed).addEvent(C.LEAVE_START,this.handleLeaveStart).addEvent(C.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(C.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(C.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(C.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(C.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(C.PUBLISH_START,this.handlePublishStart).addEvent(C.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(C.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(C.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(C.PLAY_TRACK_START,this.handlePlayStart).addEvent(C.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(C.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===p.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(C.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(C.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(C.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(C.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(C.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(C.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(C.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&&(E(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),E(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),E(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:s,tcp:n,tls:a,request:c,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,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())}handleSwitchRoomStart(i){if(this.hitTest(i.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess({room:i}){if(this.hitTest(i)&&this._pathJoinRoom.uint64_end_time===0){let e=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=e,this._pathJoinRoom.uint64_end_time=e,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed({room:i,error:e}){if(this.hitTest(i)){let t=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=t,this._pathJoinRoom.uint64_end_time=t,e&&(this._pathJoinRoom.int32_end_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN)}}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let s={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:w(v({},iS),{msg_user_info:new Mn({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,s)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:s,tinyId:n,role:a}=e,c=new Mn({userId:s,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${s}_${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:c,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&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,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}`,s=this._remoteStreamStatMap.get(r);s&&s.subscribedTime===0&&(s.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),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;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:s,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,l,u,h;s&&(l=s,u=1),n&&(c=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,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:s,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:s}=t.msg_audio_status;Math.floor(s/Et*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Et,this._localStreamStat.audioLevelCount++)}r.forEach(s=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=s,l=n.str_identifier,u=this._room.remotePublishedUserMap.get(l);if(c.forEach(h=>{let m=h.uint32_video_stream_type===2,_=h.uint32_video_stream_type===7,A=`${l}_${m?"main":"auxiliary"}`,g=this._remoteStreamStatMap.get(A);if(g&&(m&&(u!=null&&u.remoteVideoTrack.isSubscribed)||_&&(u!=null&&u.remoteAuxiliaryTrack))){g.totalVideoFPS+=h.uint32_video_receive_fps,g.totalVideoBitrate+=h.uint32_video_codec_bitrate,g.videoCount++,g.statsToReport.uint32_video_width===0&&(g.statsToReport.uint32_video_width=h.uint32_video_width),g.statsToReport.uint32_video_height===0&&(g.statsToReport.uint32_video_height=h.uint32_video_height);let T=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;T.stat.jitterBufferDelay&&(g.videoJitterBufferDelay=T.stat.jitterBufferDelay),T.stat.framesReceived&&(g.statsToReport.uint32_video_consume_render_rate=Math.floor(T.stat.framesDecoded/T.stat.framesReceived*or(10,6)))}}),!fo(a)){let h=`${l}_main`,m=this._remoteStreamStatMap.get(h);this._remoteStreamStatMap.has(h)&&m&&u!=null&&u.remoteAudioTrack.isSubscribed&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/Et*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/Et,m.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let 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&ar)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&cr)>=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:m,videoDelayCount:_,totalAudioDelay:A,totalVideoDelay:g}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),m&&A&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(A/m),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:s}=this._room;s&&(i.statsToReport.uint32_audio_play_time=s.getDuration(e,p.AUDIO),i.statsToReport.uint32_video_play_time=s.getDuration(e,p.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,io));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(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>io&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+io)}),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>io&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+io)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>io&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+io)}getReportData(){this._basicInfo.uint32_networkType=vr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Mn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:_o(this._signalInfo.relayIp),uint32_client_ip:_o(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*or(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:_o(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Ns(i),i}report(){return f(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return f(this,null,function*(){var a,c;if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=(c=(a=this._room.scheduleResult)==null?void 0:a.config)!=null&&c.sso?Pi(i,2001,e):JSON.stringify(i),r=`${wi(e,sr.KEY_POINT)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(r,t));let n=[this.uploadKVStat(N),this.uploadKVStat(Br)];s||n.push(Ui({url:r,body:t,priority:"low"})),yield Promise.all(n)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){var n,a;let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=w(v({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=(a=(n=this._room.scheduleResult)==null?void 0:n.config)!=null&&a.sso?Pi(e,2003,this._room.sdkAppId):JSON.stringify(e),r=`${wi(+this._room.sdkAppId,sr.KV_STAT)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(r,t)),s||Ui({url:r,body:t})})}};D([St({settings:{timeout:500,retries:3}})],Wc.prototype,"upload",1);var io=5e3,iS={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},Mn=class{constructor(i){d(this,"str_identifier");d(this,"str_tinyid");d(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Tf=Wc;var hh=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=B())}stop(){this._endTime===0&&(this._endTime=B())}getDuration(){return this._endTime===0?B()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},Jc=hh;var mh=class{constructor(i){d(this,"_room",null);d(this,"_durationMap");d(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(C.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(C.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(C.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`,p.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,p.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,p.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);s&&(!e.hasAudio&&t.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,p.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,p.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,p.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}`,s=new Jc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(r,{userId:i,type:t,audio:e===p.AUDIO?[s]:[],video:e===p.AUDIO?[]:[s]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(s=>s.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,s)=>r+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Ef=mh;var ph=class{constructor(i){d(this,"_room");d(this,"_renderFreezeMap",new Map);d(this,"_isVideoPlayingEventFiredMap",new Map);d(this,"_dataFreezeMap",new Map);d(this,"_monitorFreezeData",new Map);d(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(C.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(C.PLAY_TRACK_START,this.onPlayTrackStart).set(C.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,s=`${r}_${e}`;this.stopDataFreeze({key:s,userId:r,type:e})}).set(C.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 s="main",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}if(e.hasAuxiliary&&!t.hasAuxiliary){let s="auxiliary",n=`${t.userId}_${s}`;this.stopDataFreeze({key:n,userId:r,type:s})}}).set(C.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==p.VIDEO)){if(e==="PLAYING"){let s=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}t===p.MUTE?this.onVideoTrackMuted(i):t===p.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(C.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}`,s=this._dataFreezeMap.get(r),n=new Jc;s?s.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:s,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:s,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,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 s=r.durationItemList[r.durationItemList.length-1];s.stop();let n=s.getDuration();n>Jn?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 f(this,arguments,function*({userId:i,fps:e,type:t}){let s=`${i}_${t}`,n=this._renderFreezeMap.get(s);if(e<=2){let a=B();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{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=B();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==p.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()<Jn&&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 s=B(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=s-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()}},Sf=ph;var Af=Ge(tt(),1);var qc=class{constructor(i,e,t,r,s=4/3){this.vbMode=i;this.faceDetectorHash=e;this.visionTaskRegistry=t;this.logger=r;d(this,"animationState");d(this,"originalAspect");d(this,"totalOffsetX",0);d(this,"totalOffsetY",0);d(this,"defaultScaleRatio",.1);d(this,"isRecovering",!1);d(this,"boundaryY",280);d(this,"lastActionTime",0);d(this,"restTime",400);this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=s||4/3}addEvent(i,e,t){let s=[{key:570704,error:t!=null?t:e?void 0:11},{key:570705,error:t!=null?t:e?void 0:22}][i-1];s&&(e?N.addSuccessEvent({key:s.key}):N.addFailedEvent({key:s.key,error:s.error}))}actionCentering(i){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTime<this.restTime||this.animationState.animating)return;let{videoWidth:t,videoHeight:r}=i;this.animationState.debounceThreshold=t/30,this.animationState.movementThreshold=t/20,this.boundaryY=r*.6;try{let s=this.visionTaskRegistry.getResult(this.faceDetectorHash);if(s.detections.length<=0){this.vbMode===1&&this.recoverOriginal(t,r);return}let n=s.detections[0].boundingBox,a=n.originX,c=n.originY,l=n.width,u=n.height;this.vbMode===1?this.dualStageCropping(t,r,a,c,l,u):this.vbMode===2&&this.movingPortrait(t,r,a,c,l,u)}catch(s){this.logger.error(s)}this.lastActionTime=e}calculateBoundary(i,e,t,r){let s,n;return i>e/2?(s=e-t-r,n=t-s):(s=t,n=0),{min:s,offset:n}}calculateTargetPosition(i,e,t,r,s,n,a=.4){let c=i+t/2,l=e+r/2,u,h,{min:m,offset:_}=this.calculateBoundary(c,s,i,t),{min:A,offset:g}=this.calculateBoundary(l,n,e,r);return u=2*m+t,h=2*A+r,u/h>this.originalAspect?(u=h*this.originalAspect,_=c-u/2):(h=u/this.originalAspect,g=l-h/2),t/s>a&&(_=0,g=0,u=s,h=n),_=Math.max(0,Math.min(_,s-u)),g=Math.max(0,Math.min(g,n-h)),{sx:_,sy:g,cropWidth:u,cropHeight:h,timestamp:Date.now()}}processFacePositionCrop(i,e,t){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:t,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;return}let r=this.positionDistance(this.animationState.target,i),s=this.positionDistance(this.animationState.current,i),n=this.animationState.current.cropWidth/e;r>this.animationState.debounceThreshold*n&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&s>this.animationState.movementThreshold*n&&(this.animationState.target=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(i){if(!this.animationState.current||!this.animationState.target){this.animationState.current=v({},i),this.animationState.target=v({},i);return}let e=this.positionDistance(this.animationState.current,i),t=this.positionDistance(this.animationState.target,i);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&t>this.animationState.movementThreshold&&(this.animationState.current=i,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let i=Date.now()-this.animationState.startTime,e=Math.min(i/this.animationState.duration,1),t=r=>r<.5?2*r*r:-1+(4-2*r)*r;if(this.animationState.current&&this.animationState.target){let r=(this.animationState.target.sx-this.animationState.current.sx)*t(e);this.animationState.current.sx+=r,this.totalOffsetX+=r;let s=(this.animationState.target.sy-this.animationState.current.sy)*t(e);if(this.animationState.current.sy+=s,this.totalOffsetY+=s,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*t(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*t(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*t(e)),q(this.animationState.current.scaleOffsetX)&&q(this.animationState.target.scaleOffsetX)&&q(this.animationState.current.scaleOffsetY)&&q(this.animationState.target.scaleOffsetY)){let n=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*t(e);this.animationState.current.scaleOffsetX+=n;let a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*t(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(i,e){return Math.sqrt(or(i.sx-e.sx,2)+or(i.sy-e.sy,2))}recoverOriginal(i,e){this.animationState.target={sx:0,sy:0,cropWidth:i,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(i,e,t,r,s,n,a=.3){if(this.isRecovering)return;let c=this.calculateTargetPosition(t,r,s,n,i,e);this.processFacePositionCrop(c,i,e),s*n/c.cropWidth/c.cropHeight>a&&this.recoverOriginal(i,e)}movingPortrait(i,e,t,r,s,n){var c,l,u,h,m,_,A,g,T,O,K,G;let a={sx:t+s/2+this.totalOffsetX,sy:r+n/2+this.totalOffsetY,cropWidth:i,cropHeight:e,scaleRatio:(l=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?l:1,scaleOffsetX:(h=(u=this.animationState.current)==null?void 0:u.scaleOffsetX)!=null?h:0,scaleOffsetY:(_=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(g=(A=this.animationState.target)==null?void 0:A.scaleRatio)!=null?g:1,scaleOffsetX:(O=(T=this.animationState.target)==null?void 0:T.scaleOffsetX)!=null?O:0,scaleOffsetY:(G=(K=this.animationState.target)==null?void 0:K.scaleOffsetY)!=null?G:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(s*n/i/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=-this.animationState.target.scaleRatio+1,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio<this.boundaryY&&(this.animationState.target.scaleOffsetY=(this.animationState.target.sy-this.boundaryY*this.animationState.target.scaleRatio)/this.animationState.target.cropHeight)),this.processFacePositionPortrait(a)}set aspectRatio(i){this.originalAspect=i}get current(){return this.animationState.current}get offset(){return{offsetX:this.totalOffsetX,offsetY:this.totalOffsetY}}get targetCrop(){return this.animationState.target}};var rS=`#version 300 es
|
|
102
71
|
in vec2 a_position;
|
|
103
72
|
in vec2 a_texCoord;
|
|
104
73
|
out vec2 v_texCoord;
|
|
105
74
|
void main() {
|
|
106
75
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
107
76
|
v_texCoord = a_texCoord;
|
|
108
|
-
}`,
|
|
77
|
+
}`,oS=`#version 300 es
|
|
109
78
|
precision highp float;
|
|
110
79
|
uniform sampler2D u_texture;
|
|
111
80
|
uniform sampler2D mask;
|
|
@@ -114,7 +83,7 @@ in vec2 v_texCoord;
|
|
|
114
83
|
out vec4 outColor;
|
|
115
84
|
void main() {
|
|
116
85
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
117
|
-
}`,
|
|
86
|
+
}`,jc=class extends Dt{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:t.width,height:t.height,logger:e.log});d(this,"_bgTexture");d(this,"_waterMarkTexture");d(this,"_lastMaskTexture");d(this,"_lastMaskFbo");d(this,"_textureValid",!1);d(this,"_selfieTextureValid",!1);d(this,"_selfieSegmentationHash");d(this,"wasm");d(this,"_prePrograme");d(this,"_segmentationMask");d(this,"_weixin",!1);d(this,"_centerFace");d(this,"_textureMatrixLocation");d(this,"_offsetMatrixLocation");d(this,"_enableFaceCentering",!1);d(this,"_mat4");d(this,"_onAbort");d(this,"_visionTaskRegistry");this.init(t).catch(r=>{e.log.error(r),e.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${r.message||r}`}))})}init(e){return f(this,null,function*(){var n;let t=e.Wasm,r=this.context.ctx;if(e.mat4&&(this._mat4=e.mat4),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this.wasm=new t.AllIn1(r),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.rotation=e.rotation||0,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,this._onAbort=e.onAbort,e.waterMark){let{x:a,y:c,width:l,height:u}=e.waterMark;this.wasm.setWaterMark(a,c,l,u)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:l}=e.beautyParams;this.wasm.setBeauty(a,c,l,e==null?void 0:e.width,e==null?void 0:e.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(r.uniform1i(r.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(r.uniform1i(r.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=r.getUniformLocation(this.program,"u_textureMatrix"),r.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=r.getUniformLocation(this.program,"u_offsetMatrix"),r.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),r.uniform1i(r.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(r.FRAGMENT_SHADER,oS),c=this.context.createShader(r.VERTEX_SHADER,rS);this._prePrograme=this.context.createProgram(c,a),r.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.uniform1i(r.getUniformLocation(this._prePrograme,"mask"),1)}yield this.initVisionTasks(e)})}initVisionTasks(e){return f(this,null,function*(){if(e.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._visionTaskRegistry.video=this.image,this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._enableFaceCentering){this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let t=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!t)return;this._centerFace=new qc(this.wasm.vbMode,t,this._visionTaskRegistry,this.context.log)}}})}onPredict(e){let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),this.bindMaskTexture(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindMaskTexture(e){let t=this.context.ctx;if(!e.confidenceMasks)return;let r=e.confidenceMasks[0].getAsWebGLTexture();t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,r),e.close()}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){let t=this.context.ctx,{image:r}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=r;if(dt(this.wasm.rotation)&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;r.width=s,r.height=n;let a=!1;if(this.totalFrames)this.useTexture(),a=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;a=this._textureValid,this._textureValid=!0}this.width!==s||this.height!==n||!a?(this.resize(s,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,r),this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(this.bindMaskTexture(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0));try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let e=this.context.ctx;this._centerFace.aspectRatio=e.canvas.width/e.canvas.height,this._centerFace.actionCentering(this.image);let{current:t,offset:r}=this._centerFace;if(t&&(this.wasm.vbMode===1&&this.drawImage(t.sx,t.sy,t.cropWidth,t.cropHeight),r&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:c=0}=t;this._mat4.fromTranslation(s,[-r.offsetX/e.canvas.width+a,c,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,t,r,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:c}=n.canvas,l=this._mat4.create();this._mat4.fromTranslation(l,[e/a,1-(t+s)/c,0]),this._mat4.scale(l,l,[r/a,s/c,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,l)}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var Xc=class extends Ye{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
118
87
|
precision highp float;
|
|
119
88
|
uniform sampler2D ySampler;
|
|
120
89
|
uniform sampler2D uSampler;
|
|
@@ -139,4 +108,15 @@ void main() {
|
|
|
139
108
|
void main() {
|
|
140
109
|
gl_Position = vertexPos;
|
|
141
110
|
textureCoord = texturePos;
|
|
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 Di=[i=>{i.codec="avc1.42e01f"},i=>{delete i.hardwareAcceleration}],Jg=(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 US(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var VS=0,Cu=class{constructor(t){u(this,"id",VS++);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=yt(),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=Ne(e.availableState,de.OFF),this.stopOB=yt(),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),be(this.stateChangeOB,tp((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Ye(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=be(this.pipe(this.track),Ye(this.stopOB),yi());be(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Q.addFailedEvent({key:Jg(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED"),Q.addFailedEvent({key:514704});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`),Q.addSuccessEvent({key:Jg(this.type,this.renderer)}),Q.addSuccessEvent({key:514704})})),be(e,Dr(1),Le(()=>{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"&&!em()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var c,l;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!US(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(((c=this.decoder)==null?void 0:c.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(m=>this.decode(m,!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=Ie();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} ${(l=t.getMetadata)==null?void 0:l.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=>y(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var c;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(c=this.videoContext)==null||c.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 l=0;l<=Di.length;l++){let{supported:m}=yield VideoDecoder.isConfigSupported(this.config);if(m)break;if(l===Di.length){e.error(3);return}Di[l](this.config)}r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let c=0;if(r.on("videoFrame",l=>{this.decodedFrameCount++,c++,(c<=10||c%500===0)&&t.log.debug(`frame ${c} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${l.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(l.timestamp)),e.next(l)}),r.on("error",l=>{t.log.error(l),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 Tt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Tt.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let l=new vu(this.videoContext);r.on("videoCodecInfo",m=>l.resize(m.width,m.height)),r.on("videoFrame",m=>{({y:l.Y,u:l.U,v:l.V}=m),this.downgradeLevel===1?this.decodedFrameCount%2===0&&l.render(this.decodedFrameCount):l.render(this.decodedFrameCount)}),t.source=l,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let l=new MediaStreamTrackGenerator({kind:"video"}),m=l.writable.getWriter();t.setInputMediaStreamTrack(l),r.on("videoFrame",f=>m.write(f))}else{this.videoContext=new Ft({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let l=this.videoContext.createVideoImageSource();r.on("videoFrame",f=>{try{l.image=f,l.update()}catch(E){delete this.goodType,t.log.error(E),e.error(11)}});let m=new is(this.videoContext,{name:"remotePlayer",logger:t.log});l.connect(m),t.source=l,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(c){t.log.error(c),e.error(n==="webCodecs"?2:6)}})}};var Ga=class extends zg.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,"_rotation",0);u(this,"cameraTrack");u(this,"cameraNode");u(this,"transformNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"_enableFaceCentering",!1);u(this,"onAbort");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,"_mixScreenOption",{});u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",$.createLogger({id:"vm"}));u(this,"_mat4");u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ft({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var o;let{width:e,height:r}=((o=this.cameraTrack)==null?void 0:o.settings)||{};return ni(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Ft({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Tt({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(Tt.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)}}initVirtualBackground(e,r){this.onAbort=e,this._mat4=r}enablePrintDetail(e=2e3){this._checkId=vt.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(),vt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Yi||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?Q.addFailedEvent({key:o,error:r}):Q.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 Tt({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}setSmallVideo(e,r){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new qd(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Tt.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;Yi&&n.setCanvas(e);let c=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this.log.info(`set main output ${c?c.label:"no output track"}`),this.setSmallVideo(s,e),o.setOutputMediaStreamTrack(c)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack)return;if(!this.initialTrack)return this.updateWithoutCamera();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}),this.destination.on("render",()=>{var n;(n=this.cameraTrack)==null||n.player.emit("render")})),Jt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof bi?(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 bi?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);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new jd(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on("render",()=>{var m;(m=this.cameraTrack)==null||m.player.emit("render")}));let{width:n,height:c}=this.cameraResolution,l=yield this.getWatermarkImage(n,c);this._waterMarkOption={x:0,y:0,width:l.width,height:l.height,image:l},this.cameraNode=new Ru(this.videoContext,{input:this.initialTrack,width:n,height:c,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,onAbort:this.onAbort,mat4:this._mat4}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()}if(this.videoContext.frameRate=o.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Au(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),ni(this._rotation)&&this.transformNode.resize(r.height,r.width),this.log.info(`start ${this._isMirror?"mirror":""}${this._isRotate?`, rotate ${this.rotation}`:""}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Wa(this.videoContext,this.log),this.mixNode.resize(r.width,r.height),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:l,height:m}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(l,m),l&&m&&this.waterMarkNode.resize(l,m)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),this.changeMixLayout(this._mixScreenOption),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}updateWithoutCamera(){return y(this,null,function*(){var o;if(!this._isMixScreen)return;if(!this.screenTrack||!this.screenTrack.mediaTrack){this.clearLastFrame();return}if(this.checkOrCreateVideoContext(),!this._use2d)return;this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on("render",()=>{}));let{settings:e,profile:r}=this.screenTrack;return this.videoContext.frameRate=((o=this.cameraTrack)==null?void 0:o.profile.frameRate)||r.frameRate,this.mixNode&&this.mixNode.close(),this.mixNode=new Wa(this.videoContext,this.log),this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.shouldUpdate=!0,this.screenNode.resize(e.width,e.height),this.screenNode.connect(this.mixNode,{zIndex:0}),this.changeMixLayout(this._mixScreenOption),this.mixNode.connect(this.destination),this.log.info("mix without camera"),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,n;if(e instanceof io)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof Nr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof ao){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var r;e instanceof io?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Nr?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof ao&&e.source&&e.source.context.destroy()}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return y(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,r){return y(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 ue({code:q.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,c)=>n.zIndex-c.zIndex),this.watermarkImageList.forEach(({image:n,x:c,y:l,width:m,height:f})=>{s.drawImage(n,c,l,m,f)}),ws(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 y(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return y(this,null,function*(){this._beautyParams=void 0,this.update()})}setVideoMixer(e){this._isMixScreen=!0,this._mixScreenOption=e,this.update()}updateVideoMixer(e){this.changeMixLayout(e),ur(this._mixScreenOption,e)}changeMixLayout(e){if(!this._isMixScreen||!this.mixNode)return;let{camera:r,screen:o,container:s}=e;if(this.cameraNode&&r){let{width:n,height:c}=this.cameraNode,{x:l,y:m,width:f,height:E}=r;f&&!E?E=f*c/n:!f&&E&&(f=E*n/c),this.mixNode.changeInputLayout(this.cameraNode,{x:l,y:m,width:f,height:E})}if(this.screenNode&&o){let{width:n,height:c}=this.screenNode,{x:l,y:m,width:f,height:E}=o;f&&!E?E=f*c/n:!f&&E&&(f=E*n/c),this.mixNode.changeInputLayout(this.screenNode,{x:l,y:m,width:f,height:E})}s&&this.mixNode.resize(s.width,s.height)}deleteVideoMixer(){var e;this._isMixScreen=!1,this._mixScreenOption={},(e=this.screenNode)==null||e.close(),delete this.screenNode,this.update(),this.log.info("delete screenMixer")}setWatermark(e){return y(this,null,function*(){let r;try{r=yield ws((e==null?void 0:e.imageElement)||e.imageUrl)}catch(E){throw new ue({code:q.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:c=r.height,type:l="watermark",zIndex:m=2}=e;this.watermarkImageList.some(E=>E.type===l)?(this.watermarkImageList=this.watermarkImageList.filter(E=>E.type!==l),this.pushWaterMarkImageList({x:o,y:s,width:n,height:c,image:r,zIndex:m,type:l,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.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:c,image:r,zIndex:m,type:l,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(E,_)=>E==="imageUrl"?void 0:_))})}deleteWatermark(e="watermark"){return y(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 y(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:r}=this.cameraResolution,o=yield this.getWatermarkImage(e,r);this._waterMarkOption={x:0,y:0,width:o.width,height:o.height,image:o},this.update()})}setVirtualBackground(e){return y(this,null,function*(){var r;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 ws(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering}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 ue({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._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var r;this._rotation!==e&&(this._rotation=e,this._isTransform||((r=this.transformNode)==null||r.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return y(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 Cu(e)}clear(){var e,r;(e=this.videoContext)==null||e.disconnect(),(r=this.destination)==null||r.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,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}};Z([xf(function(e){this.log.error("update failed",e)})],Ga.prototype,"update",1);var FS=0;var Nu=class extends de{constructor(e){super("room");u(this,"seq",++FS);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,"smallMode","canvas");u(this,"_isUsingCachedSchedule",!1);u(this,"_log",$.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,st(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),st(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),st(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Gg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new jg({room:this}),this.badCaseDetector=new qg({room:this}),this.audioManager=new wd(this),this.videoManager=new Ga(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 y(this,null,function*(){return this.publish(e)})}removeTrack(e){return y(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return y(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Oe(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Lt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:c}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=c,c?(ou([c,c]),wo(`https://${c}`)):(s&&wo(s),n&&ou(n))}V.once(U.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:zr.main,sched_back_domain:zr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return y(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return y(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 y(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 ue({code:q.INVALID_OPERATION,message:Be({key:$e.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Xt.INVALID_DESTROY),new ue({code:q.INVALID_OPERATION,message:Be({key:$e.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,V.emit(U.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,c,l;let o=Ie();try{let{isCached:m,result:f,detailCost:E}=yield gp({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:at,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} ${dr(f,{keysToExclude:["username","credential"]})}`),m&&V.once(U.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=X(X({},this.scheduleResult),f),ke((s=f.config)==null?void 0:s.retryCount)&&il(f.config.retryCount),Oe((n=f.config)==null?void 0:n.loggerDomain)&&wo(f.config.loggerDomain),this.videoDecodeFallbackType=((c=f.config)==null?void 0:c.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((l=f.config)==null?void 0:l.smallMode)||this.smallMode,V.emit(U.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:E}),Q.addSuccessEvent({key:521700,cost:Ie()-o})}catch(m){throw Q.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};function Xg(i,t=!1){let e=Object.defineProperties(yt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=He,i.onmessageerror=He,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 Lp=class extends fe{constructor(t,e){super(t);let r=new fe(t);r.next=He,e(r)}},WF=_e(Lp,"takeUntilComplete");var Mt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Qg="__INLINE__WORKER__",Yg="__INLINE__WASM__",{debug:Zg}=console;Mt.debug||(console.debug=()=>{});var $S=!Qg.startsWith("__"),BS=!Yg.startsWith("__");function Du(){let i=Uo(`${Mt.assetsPath?`${Mt.assetsPath}/`:""}worker.js`);return $S?URL.createObjectURL(new Blob([atob(Qg)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var ja;function wu(){return y(this,null,function*(){let i=Mt.assetsPath?`${Mt.assetsPath}/`:"";return ja||(BS?ja=new TextEncoder().encode(atob(Yg)).buffer:ja=yield fetch(Uo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),ja)})}var Up=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 y(this,null,function*(){let t=ze("player"),e=Du();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),$.info("global audio player worklet addModule success",e)}catch(r){throw $.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield wu(),flag:Mt},numberOfInputs:2}),$.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},Mu=new Up;var Vp=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),YF=Vp?Promise.resolve().then(function(){return jS}):Promise.resolve().then(function(){return YS});var ZF=Vp?Promise.resolve().then(function(){return JS}):Promise.resolve().then(function(){return KS});var HS=Vp?Promise.resolve().then(function(){return XS}):Promise.resolve().then(function(){return ty});function Fp(...i){return y(this,null,function*(){return(yield HS).default(...i)})}var WS=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),GS=(...t)=>y(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(c=>{e[n].accept[c]=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(WS));return i[0].multiple?o:o[0]}),jS={__proto__:null,default:GS};function Ou(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 Ou=function(e){this.s=e,this.n=e.next},Ou.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 Ou(i)}var Kg=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let c=[],l=[];var m,f=!1,E=!1;try{for(var _,v=function(k){var M,N,B,ee=2;for(typeof Symbol!="undefined"&&(N=Symbol.asyncIterator,B=Symbol.iterator);ee--;){if(N&&(M=k[N])!=null)return M.call(k);if(B&&(M=k[B])!=null)return new Ou(M.call(k));N="@@asyncIterator",B="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());f=!(_=yield v.next()).done;f=!1){let k=_.value,M=`${e}/${k.name}`;k.kind==="file"?l.push(k.getFile().then(N=>(N.directoryHandle=i,N.handle=k,Object.defineProperty(N,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>M})))):k.kind!=="directory"||!t||r&&r(k)||c.push(Kg(k,t,M,r))}}catch(k){E=!0,m=k}finally{try{f&&v.return!=null&&(yield v.return())}finally{if(E)throw m}}return[...(yield Promise.all(c)).flat(),...yield Promise.all(l)]}),qS=(...t)=>y(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 Kg(e,i.recursive,void 0,i.skipDirectory)}),JS={__proto__:null,default:qS},zS=(s,...n)=>y(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 c=[],l=null;if(i instanceof Blob&&i.type?l=i.type:i.headers&&i.headers.get("content-type")&&(l=i.headers.get("content-type")),t.forEach((E,_)=>{c[_]={description:E.description||"Files",accept:{}},E.mimeTypes?(_===0&&l&&E.mimeTypes.push(l),E.mimeTypes.map(v=>{c[_].accept[v]=E.extensions||[]})):l?c[_].accept[l]=E.extensions||[]:c[_].accept["*/*"]=E.extensions||[]}),e)try{yield e.getFile()}catch(E){if(e=null,r)throw E}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:c,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let f=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(f),m):"body"in i?(yield i.body.pipeTo(f),m):(yield f.write(yield i),yield f.close(),m)}),XS={__proto__:null,default:zS},QS=(...t)=>y(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(m=>m.mimeTypes||[]),...i.map(m=>m.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=m=>{typeof c=="function"&&c(),e(m)},c=i[0].legacySetup&&i[0].legacySetup(n,()=>c(r),o),l=()=>{window.removeEventListener("focus",l),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",l)}),o.addEventListener("change",()=>{window.removeEventListener("focus",l),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),YS={__proto__:null,default:QS},ZS=(...t)=>y(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=c=>{typeof n=="function"&&n(),e(c)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let c=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(c=c.filter(l=>l.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):c=c.filter(l=>l.webkitRelativePath.split("/").length===2),s(c)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),KS={__proto__:null,default:ZS},ey=(e,...r)=>y(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(l,m){return y(this,null,function*(){let f=l.getReader(),E=new ReadableStream({start:k=>function M(){return y(this,null,function*(){return f.read().then(({done:N,value:B})=>{if(!N)return k.enqueue(B),M();k.close()})})}()}),_=new Response(E),v=yield _.blob();return f.releaseLock(),new Blob([v],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof c=="function"&&c()},c=t.legacySetup&&t.legacySetup(n,()=>c(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),ty={__proto__:null,default:ey};var $p=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 y(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=Du(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>y(this,null,function*(){r.onmessage=({data:{id:n,type:c,payload:l}})=>{var m;if(n)(m=this.transactions.get(n))==null||m(l),this.transactions.delete(n);else switch(c){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",l),s(l);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(l.value){let f=typeof l.old=="string"?l.old:`${l.old.action}ing`,E=typeof l.value=="string"?l.value:`${l.value.action}ing`;console.log(bc(),l.group,l.name,f,"\u{1F449}",E)}break;case"log":console.log(l);break;case"glog":window.dispatchEvent(new CustomEvent(c,{detail:l}));break}},r.postMessage({wasm:yield wu(),flag:Mt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Bp=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()}},Hp=class i extends $p{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 y(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)})}},fo=new Hp,ds,ry=-1;function eE(i){return console.log(i),ds.push(i.slice()),ds.length>1e3&&ds.shift(),i}function tE(i){return y(this,null,function*(){switch(ry){case 0:this.edpl.willDecodeAudio=eE;break;case 2:this.edpl.didEncodeAudio=eE;break}yield fo.create(),V.emit(U.JOIN_SEND_CMD,{room:this});let t=new Bp(fo,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:c}=s;this.onWorkerEvent(n,c)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(V.emit(U.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ue({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:Be({key:$e.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Wp},useWt:{set:iy},enableDebug:{set(i){console.debug=i?Zg:()=>{},fo.setSwitchValue("enableDebug",i)}},useV2:{set:Gp},dump:{value(){if(ds||(console.warn("dump audio will be activated at next time join room"),ds=[]),!ds.length){console.warn("no audio data to dump,try it later");return}let i=[];return ds.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Fp(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;fo.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,fo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Fp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Mt.useHardDecoder="prefer-hardware";break;case!1:Mt.useHardDecoder="prefer-software";break;default:Mt.useHardDecoder="no-preference"}}}});function Wp(i){return y(this,null,function*(){fo.setSwitchValue("useAINS",i)})}function Gp(i){return y(this,null,function*(){fo.setSwitchValue("useV2",i)})}function iy(i){return y(this,null,function*(){fo.setSwitchValue("useWt",i)})}function rE(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function iE(i){return y(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),be(Xg(r.port2),Ye(Ne(i,de.INIT)),Le(s=>{let{data:n,packetsReceived:c}=s;i.stat.packetsReceived=c,i.stat.framesReceived++,e++;let l=n[4]&31;if(e<=10){let f=Array.from(n.slice(0,10)).map(E=>E.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${l}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${f}`)}let m;switch(l){case 5:case 7:m="key";break;default:m="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:m,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var xu=[];function sE(i){var l;let t=yt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=xu.length;m++)if(!xu[m]){xu[m]=this,this.index=m;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(l=this.session)==null||l.postMessage({cmd:"pushAudio",payload:X({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=m=>{m.data==null||(typeof m.data=="number"?t.next(m.data):o&&o.port1.postMessage(Te(X({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,c=m=>{let f=s.getAudioTracks()[0];f&&(n.disconnect(),s.removeTrack(f)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=ze("player").createMediaStreamSource(s),n.connect(Mu.worklet,0,this.index)};be(Ne(i,"output-media-track-changed"),Ye(Ne(i,"ready")),Le(c,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),xu[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),be(t,Da(m=>i.volume=m),Ai(Gd(1e3)),Le(()=>{i.volume=0})),c(i.outMediaTrack)}var O$=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var jp=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 y(this,null,function*(){yield this.recreate(r),e.signal.addEventListener("abort",()=>{this.encoder.close()});let o=0;return t.pipeThrough(new TransformStream({transform:(s,n)=>{this.encoder.state==="configured"&&(this.tsMap.set(o,Date.now()),this.encode(s),o++,n.enqueue(s))}}),e)})}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){yield this.recreate(r);let o=0;t.pipeTo(new WritableStream({write:s=>{this.encoder.state==="configured"&&(o<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,o,Date.now(),s.timestamp,s.displayWidth,s.displayHeight),(s.displayWidth!==this.config.width||s.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",s.displayWidth,s.displayHeight,this.config.width,this.config.height),this.configure({width:s.displayWidth,height:s.displayHeight})),this.tsMap.set(o,Date.now()),this.encode(s),o<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,o),o++,s.close())}}),e).catch(s=>{var n;this.localTrack.log.warn(s),(n=this.encoder)==null||n.close()})})}recreate(t,e=0){return y(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&&V.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 c=null;if(this.localTrack.enableEncodeFrame){c=new Uint8Array(s.byteLength),s.copyTo(c);let l=this.localTrack.encodeFrame({data:c.buffer},this.type===3);c=new Uint8Array(l.data)}c?(this.localTrack.stat.bytesSent+=c.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:c,duration:s.duration},timestamp:n},[c.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({},r===0?e:0),o})}configure(t,e=0){return y(this,null,function*(){var r;if(Object.assign(this.config,t),e===0)for(let o=0;o<=Di.length;o++){let{supported:s}=yield VideoDecoder.isConfigSupported(this.config);if(s)break;if(o===Di.length)return;Di[o](this.config)}else e<=Di.length&&Di[e-1](this.config);(r=this.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function Pu(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.640028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Mt.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 jp(i,t.type,o,s.port2);return s.port2.onmessage=c=>{if(c.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:l}=c.data;Pn({configureBr:[c.data.bitrate,l]}),n.configure({bitrate:l})}},this._log.info("start push",r,t),n})}function nE(i){return y(this,null,function*(){var f;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((f=i.manager)!=null&&f.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 c=yield Pu.call(this,i,r);this._log.info("VideoEncoder created",r);let l,m=E=>y(this,null,function*(){if(l==null||l.abort("track changed"),!E)return;l=new AbortController;let{width:_,height:v,displaySurface:k}=E.getSettings();_&&(c.config.width=_),v&&(c.config.height=v);let M=tr.match(/Chrome\/(\d+)/);(M==null?void 0:M[1])==="114"&&k==="browser"&&delete c.config.hardwareAcceleration,this._log.info("push",e,"track:",E.readyState,E.getSettings());let N;if(typeof MediaStreamTrackProcessor!="undefined"&&!(E instanceof CanvasCaptureMediaStreamTrack))N=new MediaStreamTrackProcessor({track:E}).readable;else{let ee;N=new ReadableStream({pull(me){return y(this,null,function*(){if(Ei())return new Promise(oe=>{var Xe;i.player.mode===0?(Xe=i.player.element)==null||Xe.requestVideoFrameCallback((J,Ue)=>{let _o=new VideoFrame(i.player.element);me.enqueue(_o),oe()}):i.player.on("render",()=>{let J=new VideoFrame(i.player.canvas);me.enqueue(J),oe()})})})}})}let B="small"in i&&i.small;return B?(this.smallEncoder||(this.smallEncoder=yield Pu.call(this,i,{profile:B,type:3,trackType:o})),this.smallEncoder.track=E,this.smallEncoder.label="small",N=yield this.smallEncoder.trans(N,l,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),c.track=E,c.label=e,c.start(N,l,this)});return be(Ne(i,"output-media-track-changed"),Ye(Ne(i,"ready")),Le(m,console.error,()=>{var E;this._log.info("stop push",e,r),l.abort("unpublish"),c.close(),(E=this.smallEncoder)==null||E.close()})),m(i.outMediaTrack)})}var go=class go extends de{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(go.INTERVALCHANGED,this.interval)}),be(Ne(this,go.INTERVALCHANGED),no(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):be(Yf(s),so(()=>[]))),Le(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==de.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(go.INTERVALCHANGED,this.interval)}stop(){}};u(go,"INTERVALCHANGED","intervalChanged"),Z([Qe([de.INIT,de.OFF],de.ON)],go.prototype,"start",1),Z([Qe([],de.OFF)],go.prototype,"stop",1);var ku=go;var Eo=class Eo extends Nu{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 ku(this));u(this,"enableAIVoice",Wp);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:Dl(),uint32_device_type:0,str_os_verion:wl(),uint32_link_type:1,str_client_version:at,uint32_net_type:Mo[Vr.getNetworkType()],ua:navigator.userAgent,version:""}});u(this,"joinAbortController",new AbortController);u(this,"smallAbortCtrl");u(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,Gp(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return y(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=c=>{n.port2.close(),o(c.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=c=>{c.data?o.next(c.data):o.complete()},s.port2.onmessageerror=c=>o.error(c),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return y(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 y(this,null,function*(){var l,m,f;let s=Vr.getEnv(),n=nd(),c={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(l=this.proxy_wt)==null?void 0:l.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(f=this.scheduleResult.iceServers)!=null&&f.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:$s(),browserInfo:nd(),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:at,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 tE.call(this,c),console.log(this),Mu.playAudio(E=>this.postMessage({cmd:"setAudioWorkletPort"},[E])),this.checkDestroy()})}leave(){return y(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 y(this,null,function*(){let e=Ye(Ne(this,"left"));be(r=>y(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,Le(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(Te(X({},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:V.emit(e,X({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 Iu(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let E=r,_=this.remotePublishedUserMap.get(E);_&&(_.remoteVideoTrack.close(),_.remoteAuxiliaryTrack.close(),_.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(E),this.emit("remote-unpublished",_))}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:E,muteState:_,flag:v}=r,k=this.remotePublishedUserMap.get(_.userId);if(!k){this.emit("remote-publish-state-changed",r);return}k.flag=v}V.emit(U.REMOTE_PUBLISH_STATE_CHANGED,X({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=X({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:c,downlinkInfo:l,msg_down_stream_info:m}=r,f={str_sdk_version:at,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:Mo[xn()]},msg_event_msg:Zf(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:c,msg_down_stream_info:m};V.emit(U.HEARTBEAT_REPORT,{room:this,report:f}),this.emit("heartbeat-report",f),V.emit(U.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:l}),delete r.downlinkInfo;break;case"signal-connection-state-changed":V.emit(U.SIGNAL_CONNECTION_STATE_CHANGED,X({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 y(this,null,function*(){let r=e.reduce((c,l)=>l.mediaType|c,0),o=this.sendMessage("publish",r).then(c=>c.err!==0?Promise.reject(c.err):c),s=0,n=c=>y(this,null,function*(){switch(yield o,c.muted&&(s|=c.mediaType),Vt(c,c).add("mute",()=>{this.postMessage("mute",{mediaType:c.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:c.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),c.mediaType){case 1:sE.call(this,c);break;default:yield nE.call(this,c)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return y(this,null,function*(){e.forEach(ht)})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((E,_)=>_.mediaType|E,0),{userId:o,tinyId:s,streamType:n}=e[0],c=this.remotePublishedUserMap.get(o),l=X({},c.subscribeState),m=Object.assign(new ta,l);m.mediaType|=r,V.emit(U.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:c,subscribeState:m});let f=yield this.sendMessage("subscribe",{mediaType:m.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(E=>m.mediaType&E).map(E=>({mediaType:E,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",f),yield Promise.all(e.filter(E=>!E.isSubscribed).map(E=>{switch(E.mediaType){case 1:return rE.call(this,E);default:return iE.call(this,E)}})),V.emit(U.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:c})})}unsubscribe(...e){return y(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 c of e)c.unsubscribe();V.emit(U.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return y(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield Pu.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);if(!o)return;let s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:o.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(c=>s&c).map(c=>({mediaType:c,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"))}};Z([ro(Eo.prototype.afterJoin),Qe(["left",de.INIT],"joined"),Fg()],Eo.prototype,"join",1),Z([Qe("joined","left",{ignoreError:!0}),$g()],Eo.prototype,"leave",1),Z([vd((...e)=>0),Bg()],Eo.prototype,"publish",1),Z([vd((...e)=>0),Hg()],Eo.prototype,"unpublish",1),Z([vd((...e)=>e[0].userId),Wg()],Eo.prototype,"subscribe",1);var Lu=Eo;un.frameWorkType=37;un.create=function(i){let t=un._create.call(this,Lu,i);return t._use(up,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Mt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",at,"created",Mt),t};Object.assign(un.prototype,{_setCurrentSpeaker(i){let t=ze("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(up.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{be(Ne(i,"decode-downgrade-state-changed"),sr(o=>o.state==="STARTED"),Dr(1),sp(1e4),Ye(Ne(i,de.INIT)),Le(e,r))})})}});im(37);var iH=un;export{iH as default};
|
|
111
|
+
}`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),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),s}render(e){let t=this.context.ctx,r=this.width,s=this.height;return this.useProgram(),t.viewport(0,0,r,s),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,s,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,s/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,s/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 fh=[o=>{o.codec="avc1.42e01f"},o=>{delete o.hardwareAcceleration}],If=(o,i)=>{switch(o){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 sS(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var nS=0,zc=class{constructor(i){d(this,"id",nS++);d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"decodeFrameCount",0);d(this,"downgradeLevel",0);d(this,"lastDowngradeTime",0);d(this,"lastFrameDiff",0);d(this,"lastDecodeFrameTimestamp",0);d(this,"config");d(this,"gop_before_configure",[]);d(this,"videoElement");d(this,"type","wasm");d(this,"goodType");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);d(this,"track");d(this,"stateChangeOB");d(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=nt(),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=me(e.availableState,$.OFF),this.stopOB=nt(),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),ue(this.stateChangeOB,Ru((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),He(this.stopOB),be()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ue(this.pipe(this.track),He(this.stopOB),Qi());ue(e,be(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),N.addFailedEvent({key:If(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),N.addFailedEvent({key:514704});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:If(this.type,this.renderer)}),N.addSuccessEvent({key:514704})})),ue(e,Yi(1),be(()=>{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"&&!js()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,c;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!sS(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,s=!1;switch(r){case 5:case 7:s=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(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(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=B();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} ${(c=i.getMetadata)==null?void 0:c.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=>f(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:s,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 c=0;c<=fh.length;c++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(c===fh.length){e.error(3);return}fh[c](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",c=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${c.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(c.timestamp)),e.next(c)}),t.on("error",c=>{i.log.error(c),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new ke({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(ke.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new Xc(this.videoContext);t.on("videoCodecInfo",l=>c.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:c.Y,u:c.U,v:c.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&c.render(this.decodedFrameCount):c.render(this.decodedFrameCount)}),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){i.player.setCanvas();let c=new MediaStreamTrackGenerator({kind:"video"}),l=c.writable.getWriter();i.setInputMediaStreamTrack(c),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new Fe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let c=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{c.image=u,c.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new Qr(this.videoContext,{name:"remotePlayer",logger:i.log});c.connect(l),i.source=c,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var kn=class extends Af.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"_rotation",0);d(this,"cameraTrack");d(this,"cameraNode");d(this,"transformNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"_enableFaceCentering",!1);d(this,"onAbort");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"_isMixScreen",!1);d(this,"_mixScreenOption",{});d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",y.createLogger({id:"vm"}));d(this,"_mat4");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Fe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var e;return((e=this.room)==null?void 0:e.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}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())}get cameraResolution(){var r;let{width:e,height:t}=((r=this.cameraTrack)==null?void 0:r.settings)||{};return dt(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on(ke.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)}}initVirtualBackground(e,t){this.onAbort=e,this._mat4=t}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(ci||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?N.addFailedEvent({key:r,error:t}):N.addSuccessEvent({key:r})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}setSmallVideo(e,t){if(this.smallMode!=="api")if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new pc(this.smallVideoContext,e,this.log),this.smallVideoContext.on(ke.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:s}=this.cameraTrack.settings;this.smallTrackSource.resize(r,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 t;try{let r=this.cameraTrack,{small:s,player:n}=r;ci&&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.log.info(`set main output ${a?a.label:"no output track"}`),this.setSmallVideo(s,e),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return f(this,null,function*(){var s;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})),Je===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Dt?(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 Dt?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);else if(e&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new mc(this.videoContext,{name:"mainDestination",logger:this.log});let{width:n,height:a}=this.cameraResolution,c=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new jc(this.videoContext,{input:this.initialTrack,width:n,height:a,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,onAbort:this.onAbort,mat4:this._mat4}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute()}if(this.videoContext.frameRate=r.frameRate,this._use2d){let n=this.cameraNode;if(n.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Ot(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),dt(this._rotation)&&this.transformNode.resize(t.height,t.width),this.log.info(`start ${this._isMirror?"mirror":""}${this._isRotate?`, rotate ${this.rotation}`:""}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new Yo(this.videoContext,this.log),this.mixNode.resize(t.width,t.height),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:c,height:l}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(c,l),c&&l&&this.waterMarkNode.resize(c,l)}(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)}n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}clearLastFrame(){var e;this.destination&&((e=this.destination.ctx2d)==null||e.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(e){var t,r,s,n;if(e instanceof Ze)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof Be)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof Ci){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.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 Ze?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof Be?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Ci&&e.source&&e.source.context.destroy()}setCameraTrack(e){return this.cameraTrack=e,this.update(!0)}setScreenTrack(e){return f(this,null,function*(){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):yield this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)})}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let s=r.getContext("2d");if(!s)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:c,width:l,height:u})=>{s.drawImage(n,a,c,l,u)}),To(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=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)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield To((e==null?void 0:e.imageElement)||e.imageUrl)}catch(h){throw new b({code:I.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:s=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some(h=>h.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(h=>h.type!==c),this.pushWaterMarkImageList({x:r,y:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.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:s,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(h,m)=>h==="imageUrl"?void 0:m))})}deleteWatermark(e="watermark"){return f(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var s;(s=this.waterMarkNode)==null||s.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:t}=this.cameraResolution,r=yield this.getWatermarkImage(e,t);this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.update()})}setVirtualBackground(e){return f(this,null,function*(){var t;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 To(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering}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._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(e){var t;this._rotation!==e&&(this._rotation=e,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return f(this,null,function*(){var e;(e=this.cameraTrack)!=null&&e.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}createDecodeContext(e){return new zc(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.transformNode,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}};D([za(function(e){this.log.error("update failed",e)})],kn.prototype,"update",1);var aS=0;var Qc=class extends ${constructor(e){super("room");d(this,"seq",++aS);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"smallMode","canvas");d(this,"_isUsingCachedSchedule",!1);d(this,"_log",y.createLogger({id:`r${this.seq}`}));d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,de(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),de(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),de(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Tf({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new Ef({room:this}),this.badCaseDetector=new Sf({room:this}),this.audioManager=new Tc(this),this.videoManager=new kn(this)}get scriptTransformWorker(){}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(te(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(ze(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(yc([a,a]),Ar(`https://${a}`)):(s&&Ar(s),n&&yc(n))}S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ri.main,sched_back_domain:Ri.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let s=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=s.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:I.INVALID_OPERATION,message:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ve.INVALID_DESTROY),new b({code:I.INVALID_OPERATION,message:P({key:L.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(C.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,c;let r=B();try{let{isCached:l,result:u,detailCost:h}=yield Pu({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:we,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=l,this._log.info(`schedule cache:${+l} ${yt(u,{keysToExclude:["username","credential"]})}`),l&&S.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),u),q((s=u.config)==null?void 0:s.retryCount)&&pd(u.config.retryCount),te((n=u.config)==null?void 0:n.loggerDomain)&&Ar(u.config.loggerDomain),this.videoDecodeFallbackType=((a=u.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((c=u.config)==null?void 0:c.smallMode)||this.smallMode,S.emit(C.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),N.addSuccessEvent({key:521700,cost:B()-r})}catch(l){throw N.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var xf=Ge(tt());var _h=Ge(ah());var Cf=o=>{let i=Ce(o),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var s;if(t.ssrcs&&!E(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((s=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:s.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 Rf(o){var e;let i=[];for(let t=0;t<o.rtp.length;t++){if(["rtx","red","ulpfec"].includes(o.rtp[t].codec))continue;let r=o.fmtp.filter(s=>s.payload===o.rtp[t].payload)[0];i.push({payload:o.rtp[t].payload,codec:o.rtp[t].codec,fmtp:r?r.config:"",rate:o.rtp[t].rate,rtx:((e=o.rtp[t+1])==null?void 0:e.codec)==="rtx"?o.rtp[t+1].payload:0,rtcpfb:((o==null?void 0:o.rtcpFb)||[]).filter(s=>s.payload===o.rtp[t].payload).map(({type:s,subtype:n})=>({id:s,params:n?[n]:[]}))})}return i}function cS(){return f(this,null,function*(){let o=new RTCPeerConnection;o.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield o.createOffer();if(!i.sdp)return[];let e=Ce(i.sdp),t=Rf(e.media[0]);return o.close(),t})}var yf=(o,i,e)=>f(void 0,null,function*(){var l;let t=Ce(o),r={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};r.ice.ufrag=String(t.media[0].iceUfrag),r.ice.password=t.media[0].icePwd||"",t.fingerprint&&(r.dtls.hash=t.fingerprint.type,r.dtls.fingerprint=t.fingerprint.hash,r.dtls.setup=t.setup||""),t.media[0].fingerprint&&(r.dtls.hash=t.media[0].fingerprint.type,r.dtls.fingerprint=t.media[0].fingerprint.hash),r.dtls.setup=t.media[0].setup||"";let s=t.media[0],n=t.media[1];s.ext&&(r.audio.extensions=s.ext.map(u=>({id:u.value,uri:u.uri}))),n.ext&&(r.video.extensions=n.ext.map(u=>({id:u.value,uri:u.uri})));let a={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channels:s.rtp[0].encoding,rtcpfb:[],rtx:0};(l=s.rtcpFb)==null||l.forEach(({payload:u,type:h,subtype:m})=>{if(u===a.payload){let _={id:h,params:[]};m&&_.params.push(m),a.rtcpfb.push(_)}}),r.audio.codecs.push(a);let c=["h264","vp8","h265"];return i&&c.shift(),e&&c.pop(),r.video.codecs=[...Rf(n)].filter(u=>c.includes(u.codec.toLocaleLowerCase())),r.video.decoders=(yield cS()).filter(u=>["h264","vp8","h265"].includes(u.codec.toLocaleLowerCase())),r}),bf=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Ce(e),s={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:o.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:p.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[{payload:o.audio.codecs[0].payload,config:o.audio.codecs[0].fmtp}],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:"0",payloads:String(o.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:p.AUDIO,setup:o.dtls.setup,rtcpFb:o.audio.codecs[0].rtcpfb.map(a=>({payload:o.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:o.audio.codecs[0].payload,codec:o.audio.codecs[0].codec,rate:o.audio.codecs[0].rate,encoding:o.audio.codecs[0].channels}]};return s.media.push(n),[1,2,3].forEach(a=>{s.media.push(gh({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),wt(s)},gh=({mid:o,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let s={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:p.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(o),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:p.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=>{ro(s,a)})}else{let n;i.useH265?n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()==="h265"):n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264"));let a=i.video.codecs[n]||e.video.codecs[0];ro(s,a)}return s},ro=(o,i)=>{o.payloads=`${o.payloads} ${i.payload}`.trim(),o.fmtp.push({payload:i.payload,config:i.fmtp}),o.rtcpFb=[...o.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],o.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(o.payloads=`${o.payloads} ${i.rtx}`,o.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),o.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function dS(o){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"]);o.ext&&(o.ext=o.ext.filter(e=>!i.has(e.uri)))}function lS(o){if(!o.rtcpFb)return;let i=[];o.rtcpFb.forEach((e,t)=>{var r;i.push(e),o.rtcpFb&&((r=o.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),o.rtcpFb=i}function uS(o){o.type===p.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function hS(o){o.type===p.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Nf=(o,i,e)=>{let t=_h.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(lS(r),uS(r),hS(r),dS(r),r.type===p.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>ro(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>ro(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),_h.default.write(t)};var vf=Ge(tt());var Yc=class extends vf.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!pe&&it&&S.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:s}){if(!(e||t===7||s!=="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)}};d(Yc,"EVENT_BAD_HEALTH","bad_health");var Df=Yc;function Of({seiMessageList:o,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let s=t;i?audioEncodePipeline.forEach(n=>{s=n({frame:s})}):videoEncodePipeline.forEach(n=>{s=n({frame:s,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:s.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(s)}})}function Mf(o,i,e){return new TransformStream({transform(t,r){let s=t;videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)}})}function kf(o){let i=[zi],e=[Xu,qu,ju,Ju,Of,Mf],t=()=>{let l=[],u=[],h=[];self.onmessage=m=>{m.data.type==="sei"&&(m.data.isMain?(l.push(m.data.data),m.data.small&&h.push(m.data.data)):u.push(m.data.data))},self.onrtctransform=m=>{let{options:_}=m.transformer,A=_.isReceiver?Mf(_.userId,_.streamType,_.isAudio):Of({isAudio:_.isAudio,seiMessageList:_.isMain?_.small?h:l:u,isMain:_.isMain});m.transformer.readable.pipeThrough(A).pipeTo(m.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
|
|
112
|
+
const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
|
|
113
|
+
const audioEncodePipeline = [${o.audioEncodePipeline.toString()}];
|
|
114
|
+
const audioDecodePipeline = [${o.audioDecodePipeline.toString()}];`,s=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
|
|
115
|
+
`)}
|
|
116
|
+
${e.map(l=>l.toString()).join(`
|
|
117
|
+
`)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var bi=(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))(bi||{}),Lf=0,Pf=!1,mS=new Set,pS=o=>Lf>2&&!Pf&&mS.size===0&&o,fS=1,Kt=class extends xf.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearWaitForConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);d(this,"originOffer",null);d(this,"autoSubscribedSsrcGroups",new Map);d(this,"autoSubscribedUserMap",new Map);d(this,"_h265DecodeFailed",!1);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=y.createLogger({id:`spc${fS++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Ji?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 isH265EncodeSupported(){let e=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),e}get videoCodec(){var t,r,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(n=>["h264","vp8","h265"].includes(n.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.useH265?"h265":(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e,t,r;return(e=this._serverAbility)!=null&&e.useH265&&((t=this._serverAbility)!=null&&t.video.decoders.find(s=>s.codec.toLowerCase()==="h265"))&&!this._h265DecodeFailed?"h265":(r=this._serverAbility)!=null&&r.video.decoders.find(s=>s.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?Cf(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(){Bo&&(this.scriptTransformWorker=kf({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 s;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=(s=this._peerConnection)==null?void 0:s.getConfiguration().encodedInsertableStreams;return ia(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return f(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),N.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&N.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let s=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[s==="closed"?"debug":"info"](`signaling state: ${s}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let n=new Eh(s.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_SENDONLY}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield yf(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;s&&(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),N.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw N.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
|
|
118
|
+
offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return f(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e,(r,s)=>r==="username"||r==="credential"?"hided":s)),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 s=r.getParameters();s.encodings[0]&&(s.encodings[0].priority=e,s.encodings[0].networkPriority=e,r.setParameters(s).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,s,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=B(),c={type:"answer",sdp:bf({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(c),yield this.waitForPeerConnectionConnected();let l=((s=this._room.scheduleResult.config)==null?void 0:s.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:B()-a})}catch(a){let c=a instanceof b&&a.code===I.API_CALL_ABORTED;throw c||this._log.error(`connect failed: ${a}`,e),this.reset(),!c&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return f(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(Ne.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),s=yield this._signalChannel.sendWaitForResponse({command:z.REBUILD_PEER_CONNECTION,responseCommand:F.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new b({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(C.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Vt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Li(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>=Oi()&&this._log.warn(`SDK has tried reconnect for ${Oi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ne.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ge.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var s;let t=((s=this._peerConnection)==null?void 0:s.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===ge.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ge.FAILED||e.target.connectionState===ge.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ge.CONNECTED||e.target.connectionState===ge.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(C.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 Pt;let e=null;return!mr()||this._peerConnection.getSenders().length===0?Pt:(e=this._peerConnection.getSenders()[0].transport,!Fr()||this._peerConnection.getReceivers().length===0?Pt:e?e.state:Pt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(bi.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,r]of e)if(hr(r)){let s=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);s&&(this._log.info(`local candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port} ${s.networkType||""} ${s.candidateType==="relay"?`relayProtocol:${s.relayProtocol}`:""}`),s.networkType&&Yn(s.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},s=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:I.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(C.LEAVE_SUCCESS,s,this),this.off(bi.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new b({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Lf+=1,pS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Pf=!0,this.emit(bi.FIREWALL_RESTRICTION)),t(c)},Ss);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new b({code:I.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(C.LEAVE_SUCCESS,s,this),this.on(bi.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return f(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let s=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=p.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var _;return(_=m.ssrcs)==null?void 0:_.find(A=>{var g;return(g=A.value)==null?void 0:g.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(s.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[1])),l=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(s[2]));else if(s.length===0){this._peerConnection.addTransceiver(p.AUDIO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:p.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=gh({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),l=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=p.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${p.MAIN} ${u}-audio`}],c.direction=p.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${p.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=p.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${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${p.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${p.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return f(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),r=!1;this._peerConnection.getTransceivers().forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(s=>{t!=null&&t.includes(Number(s.mid))&&(r=!0,s.direction="inactive",s.ssrcs=[],s.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(s=>this._downlinkMIDUserIDMap.delete(s)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:s,auxVideo:n}=e;try{if(Qs()){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&&s?h=s:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,s;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp)),(s=this._parsedAnswer.media[e])!=null&&s.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:s}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=Ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp));let a=ae?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:ae?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ae?s*1e3:s}]);let c={type:"offer",sdp:wt(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let s=e.getParameters();(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]);let n=s.encodings[0].scaleResolutionDownBy;if(E(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}setDegradationPreference(e,t,r){if(it&<<83||Ie&&Bs(gt,"12.1")||ae&&Ro<138)return;let s=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),s.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),s.degradationPreference=n,e.setParameters(s).catch(c=>this._log.warn(`${a} failed: ${c}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=wt(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,s)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
119
|
+
next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
|
|
120
|
+
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:m})=>({mid:l,currentDirection:u,direction:h,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===ie.INACTIVE&&n===ie.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===ie.SENDONLY&&n===ie.INACTIVE&&(this._parsedAnswer.media[s].direction=ie.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Ce(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=Nf(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=Ce(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===p.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],ro(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];E(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===p.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],ro(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>si(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),N.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:z.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};D([Za("reconnect")],Kt.prototype,"startReconnection",1),D([Xi(e=>e.userId)],Kt.prototype,"addDownlink",1),D([Xi(e=>e)],Kt.prototype,"removeDownlink",1),D([Nt(!0)],Kt.prototype,"updateSDP",1),D([pt(521712,!1)],Kt.prototype,"setOffer",1),D([pt(521713,!1)],Kt.prototype,"setAnswer",1);var Th=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Eh=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new Th(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},wf=new Set;function Rt(){let o=Math.floor(Math.random()*4294967296);return wf.has(o)?Rt():(wf.add(o),o)}var Uf=Ge(tt());var oo=class extends Uf.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=y.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(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var Sh=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=y.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
|
|
121
|
+
const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
|
|
122
|
+
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!js()||!s||!i||E(Worker)){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,h,m;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(h=a.msg_down_stream_info)==null?void 0:h.filter(A=>{var g;return((g=A.msg_user_info)==null?void 0:g.str_identifier)===r})[0];c=(m=_==null?void 0:_.msg_video_status)==null?void 0:m.filter(A=>A.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},rr=new Sh;var wn=class extends oo{constructor(e){super(w(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,s=Object.keys(t).find(n=>t[n]!==r[n]);if(s)if(e)this._log.warn(`publish state not matched, ${s} local:${t[s]} server:${r[s]} ${Hi()} ${Lr()}`),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,s,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(hi()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===p.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&cr),bigVideo:!!(this.flag&ar),smallVideo:!!(this.flag&Ts),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 s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let n={h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working, switch to vp8"},h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working, switch to h264"}}[t];n!=null&&n.supported&&(this._log.warn(n.log),r.switchVideoEncoder(n.target))}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,m,_,A,g;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:I.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),this.singlePC.isUsingH265&&this.singlePC.isH265EncodeSupported&&(this._log.info("encoder switch to H265"),yield this.singlePC.switchVideoEncoder("h265")),pe&&Oo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(nr)}`),t.setProfile(nr),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:z.SPC_PUBLISH,responseCommand:F.SPC_PUBLISH_RESULT,data:w(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:T}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],T,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:(_=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:_.bitrate,auxVideo:(A=this.localAuxVideoTrack)==null?void 0:A.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!ht())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],h=(_,A,g)=>{var O;let T=c[A].sender.replaceTrack(g);u.push(A),(O=this.singlePC)!=null&&O.enableInsertableStreams&&T.then(()=>this.createEncodedStreams(c[A].sender,_)),this.initSenderTransform(c[A].sender,_),l.push(T)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let m=this.singlePC.setTransceiverDirection(ie.SENDONLY,u);return l.push(m),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var m,_;let h=this.getTrackByMediaType(t);u.enqueue(((m=this.singlePC)!=null&&m.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265)&&h?h.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!Bo)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return f(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!La()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(N.addSuccessEvent({key:c}),!a){N.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ie.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),this._blackSmallVideoDetectionId=rr.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;N.addFailedEvent({key:u,error:10002}),rr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})})}doPublishSmall(r){return f(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=Eo(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return f(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ie.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),rr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ie.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:z.PUBLISH_STATE_CHANGE,data:t,responseCommand:F.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:z.UNPUBLISH,commandDesc:"unpublish",responseCommand:F.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),mi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=a.width/c||0,this._mediaSettings.videoHeight=a.height/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=a.width/c||0,this._mediaSettings.auxVideoHeight=a.height/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:z.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:F.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?p.AUXILIARY:p.MAIN} stream`),hi()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ie.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ie.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?p.AUXILIARY:p.MAIN} stream`),hi()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===p.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ie.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?p.AUXILIARY:p.MAIN} stream`),r.kind===p.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===p.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===p.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:z.UPDATE_MUTE_STAT,responseCommand:F.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=p.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===p.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===p.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===p.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===p.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Rr?(this._log.error(Ve.NOT_SUPPORTED_H264ENCODE),new b({code:I.NOT_SUPPORTED_H264,message:P({key:L.NOT_SUPPORTED_H264ENCODE})})):new b({code:I.UNKNOWN,message:P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};D([st(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],wn.prototype,"publish",1),D([st(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],wn.prototype,"unpublish",1);var Ih=wn;function Vf(o){return Object.keys(o).filter(i=>o[i])}var us=class extends oo{constructor(e){super(w(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Qt(this._room,this),this.remoteVideoTrack=new Ci(this._room,this),this.remoteAuxiliaryTrack=new Ko(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return xi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===p.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,h;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=p.AUDIO;r.kind===p.VIDEO&&(c=a===p.MAIN?p.VIDEO:p.AUXILIARY);let l=this.remoteAudioTrack;c===p.VIDEO?l=this.remoteVideoTrack:c===p.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(h=this.singlePC)!=null&&h.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===p.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${Vf(e)}`),this.hasSSRC){let a="subscribe_change";Object.values(e).find(c=>c===!0)||(a="unsubscribe"),yield this.sendSubscription(a,e)}else{if((r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let a=this.singlePC.autoSubscribedUserMap.get(this.userId);if(a){this.singlePC.autoSubscribedUserMap.delete(this.userId);let c=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[a.groupIndex];c&&(this.ssrc={audio:c.audioSsrc,video:c.bigVideoSsrc,videoRtx:c.bigVideoRtxSsrc,auxiliary:c.auxVideoSsrc,auxiliaryRtx:c.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}if(e.smallVideo){let{user:a,mediaTrack:c}=this.remoteVideoTrack;N.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=rr.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),N.addFailedEvent({key:524702}),rr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})}else rr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new b({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),it&<<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return f(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Vf(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(rr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=z.UNSUBSCRIBE,n=F.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=z.SUBSCRIBE_CHANGE,n=F.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:P({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return f(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 f(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Rt(),bigVideoSsrc:Rt(),bigVideoRtxSsrc:Rt(),auxVideoSsrc:Rt(),auxVideoRtxSsrc:Rt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:z.SPC_SUBSCRIBE,responseCommand:F.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new 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(!Ua)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(q(n)||q(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return f(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Ua||!this.singlePC||!this._peerConnection||Vi(e)&&Vi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return q(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),q(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Vi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var h;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Vi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Vi(t)||!c&&Vi(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};D([Nt(),Y(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new b({code:I.API_CALL_ABORTED,message:P({key:L.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],us.prototype,"subscribe",1),D([Nt()],us.prototype,"unsubscribe",1),D([Xi(()=>"jitter")],us.prototype,"setJitterBufferDelay",1);var Bf=us;function Ff(){return Y(o=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Hf(){return Y(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var $f=Ge(tt());function gS(){return Math.floor(Math.random()*16383)}var Kc=class Kc extends $f.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=y.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(F.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||gS(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(z.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Kc.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Li(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Kc,"SEQ_INTERVAL",300);var Zc=Kc;var{isString:Gf,isUndefined:Ir,getNetworkType:TS,isEmpty:xn}=_t,ei=class extends Qc{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",Vo);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);this._stats=new On(this,this._log),this.userManager=new Ic(this.userId,this._log),this._version=we,this.sdpSemantics=ao,Ir(e.sdpSemantics)?pi.isUnifiedPlanDefault()&&(this.sdpSemantics=dr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${TS()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Ir(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Vo,!Ir(e.enableSPC)&&Vo&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Df(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=yh(n,[]);S.emit(C.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},s)),this.emit("remote-publish-state-changed",v({},s))}),this.joinParams=e,new Promise((s,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof b&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=B();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:B()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){N.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Kt({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,s)=>f(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ne.SETUP_FAILED,h=>{this.clearJoinTimeout(),S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),s(h)}),de((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&Vo&&(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:Zd(),netType:vr(),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(()=>{s(new b({code:I.JOIN_ROOM_FAILED,message:P({key:L.JOIN_ROOM_TIMEOUT})}))},a),S.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?z.SPC_JOIN_ROOM:z.JOIN_ROOM,n),this.signalChannel.once(F.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:_,data:A,tinyId:g}=h.data;S.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),g&&(this.tinyId=g),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=A.publishers,this._iceServersFromJoin=A.iceServer?[A.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var T;(T=this.singlePC)==null||T.connect(w(v({},A.ability),{useVp8:A.ability.useVp8||!!e.useVp8,useH265:A.ability.useH265||!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${_}`),s(new b({code:I.JOIN_ROOM_FAILED,extraCode:m,message:P({key:L.JOIN_ROOM_FAILED,data:{error:_,code:m}})})))}))}))}reJoin(){return f(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(w(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),se.logSuccessEvent({userId:this.userId,eventType:ct.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(bi.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Ih&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(bi.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Dn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),se.logFailedEvent({userId:this.userId,eventType:ct.REJOIN,error:e}),this.emit("error",new b({code:I.JOIN_ROOM_FAILED,message:P({key:L.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||tf(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new ns({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 Zc(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new ls({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(ls.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Qe(this,this.signalChannel).add(Ne.CONNECTION_STATE_CHANGED,a=>{S.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ne.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(F.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(F.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(F.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(F.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(se.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(F.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)})}).add(F.FALLBACK_CODEC,a=>f(this,null,function*(){var l,u,h,m,_;let c=a.data.data;this._log.warn(`fallback codec enableH265Enc: ${(l=c.videoControlInfo)==null?void 0:l.enableH265Enc}`),((u=c.videoControlInfo)==null?void 0:u.enableH265Enc)===0&&((h=this.singlePC)==null?void 0:h.videoCodec)==="h265"&&(N.addCount({key:513e3}),yield(m=this.singlePC)==null?void 0:m.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Ne.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||ve(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(z.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return f(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Tp(this.userId):[],s=w(v({str_sdk_version:fs,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:vr()},t.msg_device_info)});if(this.heartbeatReport=s,S.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(z.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",w(v({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==ld).map(({userId:r,srcTinyId:s,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:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof Dn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?Bf:lh)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",w(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:z.GET_USER_LIST,responseCommand:F.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw P({key:L.SIGNAL_RESPONSE_FAILED,data:{signalResponse:F.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!oh)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)===ge.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof at&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===ge.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),se.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Dn({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 lh({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:P({key:L.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}switchRole(e){return f(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:z.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:F.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new b({code:I.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new b({code:I.SWITCH_ROLE_FAILED,message:P({key:L.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof Ct&&(c instanceof Ii?r.audio=c:t.audio=c),c instanceof Be&&(c instanceof Ze&&c.mediaType===2?r.video=c:t.video=c)});let s=xn(t),n=xn(r);(!s||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Ih({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Dn({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",w(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");s||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},r={};e.forEach(s=>{!s.mediaTrack||!s.isPublished||(s instanceof Ct&&(s instanceof Ii?r.audio=s:t.audio=s),s instanceof Be&&(s instanceof Ze&&s.mediaType===2?r.video=s:t.video=s))});try{let s=e.map(n=>n.kind).join(",");xn(t)||(this._log.info(`unpublish() => main ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),xn(r)||(this._log.info(`unpublish() => aux ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(s){}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||!Al()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(C.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:p.VIDEO,videoType:p.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${Gc(n)}] prev: [${Gc(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():I.UNKNOWN,c=n;throw n instanceof b?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:I.API_CALL_ABORTED,message:P({key:L.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new b({code:a,message:P({key:L.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(C.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var s;$r.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!$r.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!Cl||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;q(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&q(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return f(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(_t.getTurnServer(s))):_t.isPlainObject(e)&&r.push(_t.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:z.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:z.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:F.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?z.START_PUBLISH_TENCENT_CDN:z.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.START_PUBLISH_TENCENT_CDN_RES:F.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?z.STOP_PUBLISH_TENCENT_CDN:z.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?F.STOP_PUBLISH_TENCENT_CDN_RES:F.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:z.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:z.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:z.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:F.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:z.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:F.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=_t.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return f(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${co-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=co}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${co-a.reSubscribeCount}. reason: ${h}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:co};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(Gf(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Ir(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:I.INVALID_PARAMETER,message:P({key:L.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(!Ir(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:P({key:L.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Ir(e.userDefinePushArgs))if(Gf(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:P({key:L.INVALID_USER_DEFINE_PUSH_ARGS})});xn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ji)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}switchRoom(e){return f(this,null,function*(){var A,g;if(!this.signalChannel)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((A=this.scheduleResult.config)==null?void 0:A.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let T=0;T<a;T++)l.push({audioSsrc:Rt(),bigVideoSsrc:Rt(),bigVideoRtxSsrc:Rt(),auxVideoSsrc:Rt(),auxVideoRtxSsrc:Rt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:(g=this.singlePC)==null?void 0:g.clientAbility,userSig:s!=null?s:this.userSig,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC&&(this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l)),S.emit(C.SWITCH_ROOM_START,{room:this});let h=yield this.signalChannel.sendWaitForResponse({command:z.SWITCH_ROOM,responseCommand:F.SEND_SWITCH_ROOM_RES,data:u}),{code:m,message:_}=h.data;if(m===0){let T=this.roomId;this.roomId=this.useStringRoomId?r:String(t),Ir(s)||(this.userSig=s),Ir(n)||(this.privateMapKey=n),S.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:T,targetRoomId:c})}else{this._log.error(`switch room failed. result: ${m} error: ${_}`),this.singlePC&&this.singlePC.autoSubscribedSsrcGroups.clear();let T=new b({code:I.SWITCH_ROOM_FAILED,extraCode:m,message:_});throw S.emit(C.SWITCH_ROOM_FAILED,{room:this,error:T}),T}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}};D([Te(["left",$.INIT],"joined"),St({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"),Yt(!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())}}),Qp()],ei.prototype,"join",1),D([Te("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Yp(),Za("leave room"),on({fnName:"publish",validateArgs:!1}),on({fnName:"unsubscribe",validateArgs:!1})],ei.prototype,"leave",1),D([Nt(),Ff(),St({settings:{retries:Oi,timeout:e=>Vt(e)},onError(e,t,r){var s;(s=e.message)!=null&&s.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),S.emit(C.PUBLISH_FAILED,{room:this}))}})],ei.prototype,"publish",1),D([on({fnName:"publish"}),np("api-call"),Nt(),Hf(),st(function(){var e,t;this.localTracks.size===0&&mr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],ei.prototype,"unpublish",1),D([za(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),Xi(e=>e.userId)],ei.prototype,"replaceTrack",1),D([Xi((...e)=>e[0].userId),Ec(),Zp(),St({settings:{retries:Oi,timeout:e=>Vt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],ei.prototype,"subscribe",1),D([on({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")})}}),Xi((...e)=>e[0].userId)],ei.prototype,"unsubscribe",1);Nn.create=Nn._create.bind(Nn,ei);bl(30);var HG=Nn;export{HG as default};
|