trtc-sdk-v5 5.13.2-beta.1 → 5.13.2-wasm.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/av_processing.wasm +0 -0
- package/assets/worker.js +17 -0
- package/index.d.ts +1 -1
- package/package.json +4 -6
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/custom-encryption.esm.js +1 -1
- package/plugins/custom-encryption/custom-encryption.umd.js +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- 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-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/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +65 -44
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
var L_=Object.create;var Cs=Object.defineProperty,P_=Object.defineProperties,Zh=Object.getOwnPropertyDescriptor,U_=Object.getOwnPropertyDescriptors,V_=Object.getOwnPropertyNames,Yn=Object.getOwnPropertySymbols,Kh=Object.getPrototypeOf,bd=Object.prototype.hasOwnProperty,em=Object.prototype.propertyIsEnumerable,B_=Reflect.get;var nr=Math.pow,yd=(o,i,e)=>i in o?Cs(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,D=(o,i)=>{for(var e in i||(i={}))bd.call(i,e)&&yd(o,e,i[e]);if(Yn)for(var e of Yn(i))em.call(i,e)&&yd(o,e,i[e]);return o},x=(o,i)=>P_(o,U_(i));var tm=(o,i)=>{var e={};for(var t in o)bd.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&Yn)for(var t of Yn(o))i.indexOf(t)<0&&em.call(o,t)&&(e[t]=o[t]);return e};var Oi=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Mi=(o,i)=>{for(var e in i)Cs(o,e,{get:i[e],enumerable:!0})},F_=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of V_(i))!bd.call(o,r)&&r!==e&&Cs(o,r,{get:()=>i[r],enumerable:!(t=Zh(i,r))||t.enumerable});return o};var Ge=(o,i,e)=>(e=o!=null?L_(Kh(o)):{},F_(i||!o||!o.__esModule?Cs(e,"default",{value:o,enumerable:!0}):e,o));var O=(o,i,e,t)=>{for(var r=t>1?void 0:t?Zh(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&&Cs(i,e,r),r};var d=(o,i,e)=>yd(o,typeof i!="symbol"?i+"":i,e);var Ue=(o,i,e)=>B_(Kh(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=Oi((hI,vd)=>{"use strict";var H_=Object.prototype.hasOwnProperty,at="~";function Rs(){}Object.create&&(Rs.prototype=Object.create(null),new Rs().__proto__||(at=!1));function $_(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function im(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new $_(e,t||o,r),n=at?at+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 Zn(o,i){--o._eventsCount===0?o._events=new Rs:delete o._events[i]}function et(){this._events=new Rs,this._eventsCount=0}et.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)H_.call(e,t)&&i.push(at?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};et.prototype.listeners=function(i){var e=at?at+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};et.prototype.listenerCount=function(i){var e=at?at+i:i,t=this._events[e];return t?t.fn?1:t.length:0};et.prototype.emit=function(i,e,t,r,s,n){var a=at?at+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,g;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(g=1,u=new Array(l-1);g<l;g++)u[g-1]=arguments[g];c[h].fn.apply(c[h].context,u)}}return!0};et.prototype.on=function(i,e,t){return im(this,i,e,t,!1)};et.prototype.once=function(i,e,t){return im(this,i,e,t,!0)};et.prototype.removeListener=function(i,e,t,r){var s=at?at+i:i;if(!this._events[s])return this;if(!e)return Zn(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&Zn(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:Zn(this,s)}return this};et.prototype.removeAllListeners=function(i){var e;return i?(e=at?at+i:i,this._events[e]&&Zn(this,e)):(this._events=new Rs,this._eventsCount=0),this};et.prototype.off=et.prototype.removeListener;et.prototype.addListener=et.prototype.on;et.prefixed=at;et.EventEmitter=et;typeof vd!="undefined"&&(vd.exports=et)});var Qa=Oi((UA,Xm)=>{"use strict";var jm=Xm.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(jm).forEach(function(o){var i=jm[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ym=Oi(qi=>{"use strict";var jo=function(o){return String(Number(o))===o?Number(o):o},Xg=function(o,i,e,t){if(t&&!e)i[t]=jo(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=jo(o[r+1]))},zg=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;Xg(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},zm=Qa(),Qg=RegExp.prototype.test.bind(/^([a-z])=(.*)/);qi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(Qg).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<(zm[s]||[]).length;a+=1){var c=zm[s][a];if(c.reg.test(n))return zg(c,t,n)}}),i.media=e,i};var Qm=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=jo(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};qi.parseParams=function(o){return o.split(/;\s?/).reduce(Qm,{})};qi.parseFmtpConfig=qi.parseParams;qi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};qi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(jo),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};qi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Qm,{})})};qi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=jo(e):(t=jo(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Km=Oi((BA,Zm)=>{"use strict";var Ul=Qa(),Yg=/%[sdv%]/g,Zg=function(o){var i=1,e=arguments,t=e.length;return o.replace(Yg,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""}})},rn=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 Zg.apply(null,r)},Kg=["v","o","s","i","u","e","p","c","b","t","r","z","a"],eT=["i","c","b","a"];Zm.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||Kg,t=i.innerOrder||eT,r=[];return e.forEach(function(s){Ul[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(rn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(rn(s,n,a))})})}),o.media.forEach(function(s){r.push(rn("m",Ul.m[0],s)),t.forEach(function(n){Ul[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(rn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(rn(n,a,c))})})})}),r.join(`\r
|
|
1
|
+
var v_=Object.create;var Xn=Object.defineProperty,C_=Object.defineProperties,Qp=Object.getOwnPropertyDescriptor,N_=Object.getOwnPropertyDescriptors,D_=Object.getOwnPropertyNames,Xp=Object.getOwnPropertySymbols,Yp=Object.getPrototypeOf,Zp=Object.prototype.hasOwnProperty,w_=Object.prototype.propertyIsEnumerable,M_=Reflect.get;var eo=Math.pow,wl=(i,t,e)=>t in i?Xn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,X=(i,t)=>{for(var e in t||(t={}))Zp.call(t,e)&&wl(i,e,t[e]);if(Xp)for(var e of Xp(t))w_.call(t,e)&&wl(i,e,t[e]);return i},ge=(i,t)=>C_(i,N_(t));var Qn=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),hi=(i,t)=>{for(var e in t)Xn(i,e,{get:t[e],enumerable:!0})},O_=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of D_(t))!Zp.call(i,o)&&o!==e&&Xn(i,o,{get:()=>t[o],enumerable:!(r=Qp(t,o))||r.enumerable});return i};var pi=(i,t,e)=>(e=i!=null?v_(Yp(i)):{},O_(t||!i||!i.__esModule?Xn(e,"default",{value:i,enumerable:!0}):e,i));var te=(i,t,e,r)=>{for(var o=r>1?void 0:r?Qp(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&&Xn(t,e,o),o};var l=(i,t,e)=>wl(i,typeof t!="symbol"?t+"":t,e);var Pt=(i,t,e)=>M_(Yp(i),e,t);var y=(i,t,e)=>new Promise((r,o)=>{var s=u=>{try{a(e.next(u))}catch(m){o(m)}},n=u=>{try{a(e.throw(u))}catch(m){o(m)}},a=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);a((e=e.apply(i,t)).next())});var bi=Qn((Mb,Tm)=>{"use strict";var jT=Object.prototype.hasOwnProperty,Jt="~";function ba(){}Object.create&&(ba.prototype=Object.create(null),new ba().__proto__||(Jt=!1));function qT(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function $f(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new qT(e,r||i,o),n=Jt?Jt+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 Md(i,t){--i._eventsCount===0?i._events=new ba:delete i._events[t]}function qt(){this._events=new ba,this._eventsCount=0}qt.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)jT.call(e,r)&&t.push(Jt?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};qt.prototype.listeners=function(t){var e=Jt?Jt+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};qt.prototype.listenerCount=function(t){var e=Jt?Jt+t:t,r=this._events[e];return r?r.fn?1:r.length:0};qt.prototype.emit=function(t,e,r,o,s,n){var a=Jt?Jt+t:t;if(!this._events[a])return!1;var u=this._events[a],m=arguments.length,p,g;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),m){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,r),!0;case 4:return u.fn.call(u.context,e,r,o),!0;case 5:return u.fn.call(u.context,e,r,o,s),!0;case 6:return u.fn.call(u.context,e,r,o,s,n),!0}for(g=1,p=new Array(m-1);g<m;g++)p[g-1]=arguments[g];u.fn.apply(u.context,p)}else{var E=u.length,A;for(g=0;g<E;g++)switch(u[g].once&&this.removeListener(t,u[g].fn,void 0,!0),m){case 1:u[g].fn.call(u[g].context);break;case 2:u[g].fn.call(u[g].context,e);break;case 3:u[g].fn.call(u[g].context,e,r);break;case 4:u[g].fn.call(u[g].context,e,r,o);break;default:if(!p)for(A=1,p=new Array(m-1);A<m;A++)p[A-1]=arguments[A];u[g].fn.apply(u[g].context,p)}}return!0};qt.prototype.on=function(t,e,r){return $f(this,t,e,r,!1)};qt.prototype.once=function(t,e,r){return $f(this,t,e,r,!0)};qt.prototype.removeListener=function(t,e,r,o){var s=Jt?Jt+t:t;if(!this._events[s])return this;if(!e)return Md(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&Md(this,s);else{for(var a=0,u=[],m=n.length;a<m;a++)(n[a].fn!==e||o&&!n[a].once||r&&n[a].context!==r)&&u.push(n[a]);u.length?this._events[s]=u.length===1?u[0]:u:Md(this,s)}return this};qt.prototype.removeAllListeners=function(t){var e;return t?(e=Jt?Jt+t:t,this._events[e]&&Md(this,e)):(this._events=new ba,this._eventsCount=0),this};qt.prototype.off=qt.prototype.removeListener;qt.prototype.addListener=qt.prototype.on;qt.prefixed=Jt;qt.EventEmitter=qt;typeof Tm!="undefined"&&(Tm.exports=qt)});var Fd=Qn((pR,Kf)=>{"use strict";var Zf=Kf.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(Zf).forEach(function(i){var t=Zf[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var rg=Qn(Di=>{"use strict";var hn=function(i){return String(Number(i))===i?Number(i):i},eI=function(i,t,e,r){if(r&&!e)t[r]=hn(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=hn(i[o+1]))},tI=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;eI(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},eg=Fd(),rI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Di.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(rI).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var a=0;a<(eg[s]||[]).length;a+=1){var u=eg[s][a];if(u.reg.test(n))return tI(u,r,n)}}),t.media=e,t};var tg=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=hn(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};Di.parseParams=function(i){return i.split(/;\s?/).reduce(tg,{})};Di.parseFmtpConfig=Di.parseParams;Di.parsePayloads=function(i){return i.toString().split(" ").map(Number)};Di.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(hn),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};Di.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(tg,{})})};Di.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=hn(e):(r=hn(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var og=Qn((gR,ig)=>{"use strict";var Lm=Fd(),iI=/%[sdv%]/g,oI=function(i){var t=1,e=arguments,r=e.length;return i.replace(iI,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""}})},xa=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 oI.apply(null,o)},sI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],nI=["i","c","b","a"];ig.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||sI,r=t.innerOrder||nI,o=[];return e.forEach(function(s){Lm[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(xa(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(a){o.push(xa(s,n,a))})})}),i.media.forEach(function(s){o.push(xa("m",Lm.m[0],s)),r.forEach(function(n){Lm[n].forEach(function(a){a.name in s&&s[a.name]!=null?o.push(xa(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(u){o.push(xa(n,a,u))})})})}),o.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var ep=Oi(_i=>{"use strict";var Jr=Ym(),tT=Km(),iT=Qa();_i.grammar=iT;_i.write=tT;_i.parse=Jr.parse;_i.parseParams=Jr.parseParams;_i.parseFmtpConfig=Jr.parseFmtpConfig;_i.parsePayloads=Jr.parsePayloads;_i.parseRemoteCandidates=Jr.parseRemoteCandidates;_i.parseImageAttributes=Jr.parseImageAttributes;_i.parseSimulcastStreamList=Jr.parseSimulcastStreamList});var Ph=Oi((O2,Hf)=>{"use strict";var Ff=Hf.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(Ff).forEach(function(o){var i=Ff[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Wf=Oi(rr=>{"use strict";var Ts=function(o){return String(Number(o))===o?Number(o):o},US=function(o,i,e,t){if(t&&!e)i[t]=Ts(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=Ts(o[r+1]))},VS=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;US(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},$f=Ph(),BS=RegExp.prototype.test.bind(/^([a-z])=(.*)/);rr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(BS).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<($f[s]||[]).length;a+=1){var c=$f[s][a];if(c.reg.test(n))return VS(c,t,n)}}),i.media=e,i};var Gf=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=Ts(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};rr.parseParams=function(o){return o.split(/;\s?/).reduce(Gf,{})};rr.parseFmtpConfig=rr.parseParams;rr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};rr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(Ts),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};rr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Gf,{})})};rr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Ts(e):(t=Ts(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var qf=Oi((k2,Jf)=>{"use strict";var Uh=Ph(),FS=/%[sdv%]/g,HS=function(o){var i=1,e=arguments,t=e.length;return o.replace(FS,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""}})},Jn=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 HS.apply(null,r)},$S=["v","o","s","i","u","e","p","c","b","t","r","z","a"],GS=["i","c","b","a"];Jf.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||$S,t=i.innerOrder||GS,r=[];return e.forEach(function(s){Uh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(Jn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(Jn(s,n,a))})})}),o.media.forEach(function(s){r.push(Jn("m",Uh.m[0],s)),t.forEach(function(n){Uh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(Jn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(Jn(n,a,c))})})})}),r.join(`\r
|
|
4
|
-
`)+`\r
|
|
5
|
-
`}});var Vh=Oi(or=>{"use strict";var uo=Wf(),WS=qf();or.write=WS;or.parse=uo.parse;or.parseParams=uo.parseParams;or.parseFmtpConfig=uo.parseFmtpConfig;or.parsePayloads=uo.parsePayloads;or.parseRemoteCandidates=uo.parseRemoteCandidates;or.parseImageAttributes=uo.parseImageAttributes;or.parseSimulcastStreamList=uo.parseSimulcastStreamList});import P3 from"webrtc-adapter";var kf=Ge(tt());var rm=(F=>(F[F.INVALID_PARAMETER=4096]="INVALID_PARAMETER",F[F.INVALID_OPERATION=4097]="INVALID_OPERATION",F[F.NOT_SUPPORTED=4098]="NOT_SUPPORTED",F[F.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",F[F.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",F[F.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",F[F.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",F[F.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",F[F.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",F[F.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",F[F.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",F[F.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",F[F.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",F[F.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",F[F.CLIENT_BANNED=16448]="CLIENT_BANNED",F[F.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",F[F.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",F[F.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",F[F.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",F[F.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",F[F.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",F[F.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",F[F.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",F[F.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",F[F.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",F[F.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",F[F.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",F[F.API_CALL_ABORTED=16461]="API_CALL_ABORTED",F[F.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",F[F.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",F[F.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",F[F.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",F[F.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",F[F.UNKNOWN=65535]="UNKNOWN",F))(rm||{}),A=rm;var G_=function(o){for(let i in A)if(A[i]===o)return i;return"UNKNOWN"},ys=class extends Error{constructor({name:e="RtcError",message:t,code:r=A.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${G_(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}},N=ys;var Nd=0,om=!0,Kn=function(o){Nd=o;let i=new Date;i.setTime(i.getTime()+o),y[om?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),om=!1},sm=function(){return Nd},ki=function(){return Date.now()+Nd},ea=function(){let o=new Date;return o.setTime(ki()),o.toLocaleString()},_o=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 At={};Mi(At,{REPORT_TYPE:()=>Oo,buildSSOPackage:()=>Vi,bytes2ms:()=>pm,calculateScaleResolutionDownNumber:()=>Do,concatArrayBuffers:()=>Ea,convertObjectNumberToInt:()=>Vs,copyProperties:()=>mm,deepClone:()=>kr,deepCloneBasic:()=>ma,deepMerge:()=>Jt,delay:()=>St,fibonacci:()=>xr,formatedTime:()=>Cm,getConstructorName:()=>Ro,getContainerFromElement:()=>Am,getEnv:()=>um,getFirst16Bits:()=>ym,getInternalVersion:()=>Sm,getLast16Bits:()=>Sa,getLoggerUrl:()=>Ui,getMediaStreamTrackInfo:()=>Ta,getMuteStateFromFlag:()=>Wt,getNetworkType:()=>Zd,getNumNetworkType:()=>wr,getReconnectionTimeout:()=>Gt,getStringByteLength:()=>Us,getTurnServer:()=>Im,getUint32Version:()=>fa,getValueType:()=>ve,getViewListFromView:()=>vo,glog:()=>tl,ipv4ToUint32:()=>bo,isArray:()=>Ce,isAudioWorkletSupported:()=>Tm,isBoolean:()=>de,isConstructor:()=>Lr,isEmpty:()=>yo,isFunction:()=>ne,isLangChinese:()=>$t,isMediaStreamTrack:()=>_m,isNumber:()=>X,isObject:()=>Et,isOverseaSdkAppId:()=>Pi,isPlainObject:()=>rt,isPortrait:()=>il,isPromise:()=>hr,isRemoteTrack:()=>gm,isRotate90Or270:()=>It,isSetSinkIdSupported:()=>Em,isString:()=>ee,isUndefined:()=>E,loadImage:()=>No,loadVideo:()=>Rm,ms2bytes:()=>fm,ms2samples:()=>el,normalizeUrl:()=>ga,performanceNow:()=>P,promiseAny:()=>Pr,samples2ms:()=>Kd,setNetworkType:()=>pa,stringify:()=>lt,stringifyIncludeValue:()=>Ps,throttlePromise:()=>_a});var $d={};Mi($d,{AUDIO_MUTE_BIT:()=>na,AUDIO_STAT_BIT:()=>lr,AUX_STAT_BIT:()=>Nr,AUX_STREAM_MSID:()=>Ld,BACKEND_ENV:()=>sa,BASE_DOC_URL:()=>li,BASE_HOST:()=>nm,CAPABILITIES_KEYS:()=>da,CLASS_NAME:()=>ug,CLOUD_CONSOLE_URL:()=>j_,CROSS_ROOM_BIT:()=>xd,DATA_FREEZE_TIMING:()=>ca,DOC_URL:()=>X_,DTLS_STATE_UNKNOWN:()=>Ht,ENV_NAME:()=>wi,EXCHANGE_SDP_TIMEOUT:()=>Fd,IS_WORKER:()=>go,IS_WORKLET:()=>vs,KIBANA_EVENT:()=>ze,LOCAL_STREAM_PUBLISH_STATE:()=>cm,LOGGER_CMD_TYPE:()=>ar,LOGGER_DOMAIN:()=>Od,LOGGER_DOMAIN_OVERSEA:()=>Md,LOG_LEVEL:()=>Bt,LOG_LEVEL_NAME:()=>mg,MAIN_STREAM_MSID:()=>Os,MAX_RTT:()=>ws,MICROPHONE_COMMUNICATIONS:()=>hg,MICROPHONE_DEFAULT:()=>Mr,MUTE_ALL_BIT:()=>Y_,NAME:()=>p,NETWORK_TYPE:()=>ta,NOT_SUPPORTED_H264:()=>Dr,PAUSED_RETRY_COUNT:()=>Or,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Ms,PEER_CONNECTION_STATE:()=>Se,PEER_LEAVE_REASON:()=>Hd,RECOVER_CAPTURE_INTERVAL:()=>So,REMOTE_STREAM_TYPE_AUX:()=>Ud,REMOTE_STREAM_TYPE_MAIN:()=>Pd,RENDER_FREEZE_TIMING:()=>ag,SCHEDULE_DOMAIN:()=>Li,SCHEDULE_TIMEOUT:()=>lg,SDP_SEMANTICS_PLAN_B:()=>To,SDP_SEMANTICS_UNIFIED_PLAN:()=>ur,SECOND_HOST:()=>J_,SIGNAL_PING_PONG_INTERVAL:()=>Q_,SIGNAL_PING_TIMEOUT:()=>z_,SIGNAL_RECONNECTION_COUNT:()=>sg,SMALL_STAT_BIT:()=>Ds,SPEAKER_DEFAULT:()=>ks,STORAGE_EXPIRES_TIME:()=>ia,STREAM_TYPE_BIG:()=>cg,STREAM_TYPE_SMALL:()=>dg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Eo,SYNC_USER_LIST_INTERVAL:()=>ng,Scene:()=>ui,THIRD_HOST:()=>q_,TRANSPORT_DIRECTION:()=>oe,TRTC_ERROR_ASSISTANCE:()=>kd,TRTC_QUALITY_BAD:()=>ig,TRTC_QUALITY_DISCONNECTED:()=>og,TRTC_QUALITY_EXCELLENT:()=>K_,TRTC_QUALITY_GOOD:()=>eg,TRTC_QUALITY_POOR:()=>tg,TRTC_QUALITY_UNKNOWN:()=>Z_,TRTC_QUALITY_VERY_BAD:()=>rg,UPDATE_OFFER_TIMEOUT:()=>Bd,VIDEO_MUTE_BIT:()=>aa,VIDEO_STAT_BIT:()=>dr,audioProfileMap:()=>ra,defaultBigVideoProfile:()=>cr,defaultSmallVideoProfile:()=>wd,getRetryCount:()=>xi,getScriptDir:()=>W_,innerVersion:()=>bs,loggerProxy:()=>Ns,screenProfileMap:()=>oa,setLoggerProxy:()=>vr,setRetryCount:()=>Vd,setVersion:()=>Dd,version:()=>Ve,videoProfileMap:()=>Ft});var bs="4.15.00.1600",Ve="5.0.0";function Dd(o){Ve=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));bs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var go=typeof importScripts!="undefined",vs=typeof registerProcessor!="undefined",W_=()=>{let o=go?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Ns="",vr=o=>Ns=o,nm="web.sdk.qcloud.com",J_="web.sdk.tencent.cn",q_="web.sdk.cloud.tencent.cn",j_="https://console.cloud.tencent.com/trtc",li=`https://${nm}/trtc/webrtc/v5/doc`,X_=`${li}/zh-cn/`,Od="https://yun.tim.qq.com",Md="https://apisgp.my-imcloud.com",kd="trtc_error_assistance",ar={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},wi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Bt=(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))(Bt||{}),z_=18e3,Q_=2e3,ta={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ia=7*24*3600*1e3,ra={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}},Ft={"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}},cr=Ft["480p_2"],wd=Ft["120p_2"],oa={"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",RESIZE:"resize",TIME_UPDATE:"timeupdate"},oe={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},sa={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ui=(e=>(e.LIVE="live",e.RTC="rtc",e))(ui||{}),dr=1,Ds=2,Nr=4,lr=8,na=64,aa=16,Y_=112,xd=128,Os="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Ld="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Pd=p.MAIN,Ud=p.AUXILIARY,Z_=0,K_=1,eg=2,tg=3,ig=4,rg=5,og=6,Ht="unknown",Se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},am=1/0;function Vd(o){am=o}function xi(){return am}var sg=30,ze={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},ng=1e4,Bd=1e4,Fd=1e4,ur="unified-plan",To="plan-b",Dr=1028,cm=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(cm||{}),ca=500,ag=1e3,cg=p.BIG,dg=p.SMALL,Ms=10*1e3,Li={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"},lg=2e3,ug={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Or=5,Mr="default",ks=Mr,hg="communications",mg=Object.keys(Bt),Hd=["normal leave","timeout leave","kick","role change"],Eo=10,So=2e3,da=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],ws=10*1e3;var pg=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())})},Gd=Symbol(32),Wd=Symbol(16),Jd=Symbol(8),hi=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 pg(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(Gd)}readU16(){return this.read(Wd)}readU8(){return this.read(Jd)}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===Gd){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===Wd){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===Jd){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}};hi.U32=Gd;hi.U16=Wd;hi.U8=Jd;var fg=128,_g=127,II=~_g,AI=Math.pow(2,31);function qd(o){let i=new hi;for(;o>=128;)i.malloc(1)[0]=o&255|fg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function la(o,i=0){let e=new hi,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(qd(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(qd(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 hi;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=la(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=la(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(qd(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var xs=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 jd(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 it(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function Xd(o,i){return o[i]}function Io(o,i,e){return new TextDecoder().decode(gg(o,i,e))}function gg(o,i,e){return o.slice(i,i+e)}var zd=0,ua=2654435769,ha=16,Yd=4,Ao=2,Co=7;function Tg(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 dm(o,i){let e=new xs,t=Tg(i,o,zd);zd=zd+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 xs;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 q=4;q<16;q++)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 g=n.length;n.data[0]=g>>>24&255,n.data[1]=g>>>16&255,n.data[2]=g>>>8&255,n.data[3]=g&255,ee(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let T=new Uint8Array(n.data),_=null;t.encryption===1?_=new TextEncoder().encode(t.uin):t.encryption===2&&(_=new Uint8Array(16)),_&&(T=Eg(T,_)),e.writeBytes(T);let S=new Uint8Array(e.data),R=S.length;return S[0]=R>>>24&255,S[1]=R>>>16&255,S[2]=R>>>8&255,S[3]=R&255,S}function Eg(o,i){let e=o.length,r=(e+1+Ao+Co)%8;r&&(r=8-r);let s=e+1+Ao+Co+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 g=0;g<r;g++)c[h]=Math.floor(Math.random()*256)&255,h+=1;for(let g=0;g<Ao;)if(h<8&&(c[h]=Math.floor(Math.random()*256)&255,h+=1,g+=1),h===8){Qd(c,i,l,u,n,a),a+=8,h=0;for(let T=0;T<8;T++)u[T]=n[a-8+T]}let m=0;for(;m<e;)if(h<8&&(c[h]=o[m],h+=1,m+=1),h===8){Qd(c,i,l,u,n,a),a+=8,h=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}for(let g=0;g<Co;)if(h<8&&(c[h]=0,h+=1,g+=1),h===8){Qd(c,i,l,u,n,a),a+=8,h=0;for(let T=0;T<8;T++)u[T]=n[a-8+T]}return n}function Qd(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];Sg(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 Sg(o,i,e,t){let r=it(o,0),s=it(o,4),n=[];for(let c=0;c<4;c++)n[c]=it(i,c*4);let a=0;for(let c=0;c<ha;c++)a+=ua,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;jd(e,r,t),jd(e,s,t+4)}var um=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Pi=o=>Number(o)<14e8,Ui=function(o,i){let e;Ns?e=Ns:e=Pi(o)?Md:Od;let t=Math.floor(Math.random()*nr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},Ls="unknown";function Zd(){if(Ls!=="unknown")return Ls;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&&(Ls=hm(t,r)),Ls}function hm(o,i){if(ta[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function pa(o){Ls=hm(o)}function wr(){return ta[Zd()]}function mm(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 pm(o,i=48e3){return Kd(o/4,i)}function Kd(o,i=48e3){return o*1e3/i}function fm(o,i=48e3){return el(o,i)*4}function el(o,i=48e3){return o*i/1e3}var tl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},$t=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},rt=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 xr(o,i=1,e=1){return o<=1?e:xr(o-1,e,i+e)}function Gt(o){return o>8?30*1e3:xr(o)*1e3}function ve(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",ee=o=>typeof o=="string",X=o=>typeof o=="number",de=o=>typeof o=="boolean",Et=o=>ve(o)==="object",Ce=o=>ve(o)==="array",_m=o=>ve(o)==="MediaStreamTrack".toLowerCase(),gm=o=>o.isRemote,hr=o=>ve(o)==="promise",Lr=o=>ne(o)&&o.prototype.constructor===o,Ro=o=>Lr(o)?o.prototype.constructor.name:"",Tm=typeof AudioWorkletNode!="undefined",Em=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Pr(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 P(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var lm=o=>+o<10?`0${o}`:o,Sm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=lm(e[1])+lm(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Ig=Object.prototype.hasOwnProperty,{toString:xI}=Object.prototype;function yo(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(rt(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(Ig.call(o,i))return!1;return!0}}return!1}function Wt(o,i){return{userId:i,hasAudio:!!(o&lr),hasVideo:!!(o&dr),hasAuxiliary:!!(o&Nr),hasSmall:!!(o&Ds),audioMuted:!!(o&na),videoMuted:!!(o&aa),audioAvailable:!!(o&lr)&&!(o&na),videoAvailable:!!(o&dr)&&!(o&aa)}}function Im(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 bo(o,i=!0){if(!ee(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 Jt=function(o,i,e,t){if(!(Et(o)&&Et(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(Et(o[n])&&Et(i[n]))r+=Jt(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=kr(i[n]),r+=1)}return r};function kr(o){if(Ce(o)){let i=[];return o.forEach((e,t)=>{i[t]=kr(e)}),i}if(Et(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=kr(o[e])}),i}return o}var vo=o=>{let i=[];if(Ce(o))i=[...o];else if(ee(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Am=o=>ee(o)?document.getElementById(o):o,Ag=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}`},Cm=()=>Ag(new Date);function lt(o,{keysToInclude:i,keysToExclude:e}){try{if(Ce(o))return`[${o.map(n=>lt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!rt(o)||!Ce(i)&&!Ce(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]=rt(o[n])||Ce(o[n])?JSON.parse(lt(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Ps(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),lt(o,{keysToInclude:e})}function Us(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var il=()=>{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},No=o=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ee(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 N({code:A.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),fa=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Vs=o=>(Object.keys(o).forEach(i=>{X(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(rt(o[i])||Ce(o[i]))&&Vs(o[i])}),o);function St(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function _a(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function ga(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 Do(o,i){return o.width*o.height===i.width*i.height?1:il()&&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 It(o){return o===90||o===270}function Rm(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 ma(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]=ma(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]=ma(o[t],i)}),e}return o}var Oo=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(Oo||{});function Cg(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return E(t)||(r=x(D({},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 Vi(o,i,e,t){try{let r=Cg(o,i,e,t),s=la(r);return dm(s,e)}catch(r){return JSON.stringify(o)}}function Ea(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Sa(o){return(o&65535)>>>0}function ym(o){return(o&4294901760)>>>0}function bm(o){let i=Rg(o);return i==null?void 0:i.busiBuff}function Rg(o){try{let i={},e=0;i.totalLength=it(o,e),e+=4,i.version=it(o,e),e+=4,i.encryption=Xd(o,e),e+=1,i.uinType=Xd(o,e),e+=1,i.uinLength=it(o,e),e+=4,i.uin=i.uinLength>4?Io(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=yg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=it(o,e),e+=4,i.seqNo=it(o,e),e+=4,i.retCode=it(o,e),e+=4,i.retStrLength=it(o,e),e+=4,i.retStr=i.retStrLength?Io(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=it(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Io(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=it(o,e),e+=4,i.cookie=i.cookieLength?Io(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=it(o,e),e+=4,i.busiBuffLength=it(o,e),e+=4,i.busiBuff=i.busiBuffLength?Io(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function vm(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=ua*ha>>>0;for(let s=0;s<ha;s++)t-=(e<<Yd)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<Yd)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=ua,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 yg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=vm(r,i),n=s[0]&7,a=o.length-1-n-Ao-Co,c=new Uint8Array(a),l=0,u=t,h=o.slice(0,8);e=8;let m=1;m+=n;for(let T=1;T<=Ao;)if(m<8)m++,T++;else if(m===8){let _=rl(o,e,u,h,s,i);u=_.ivPreCrypt,h=_.ivCurCrypt,s=_.debiBuf,e=_.bufPos,m=0}let g=a;for(;g>0;)if(m<8)c[l++]=s[m]^u[m],m++,g--;else if(m===8){let T=rl(o,e,u,h,s,i);u=T.ivPreCrypt,h=T.ivCurCrypt,s=T.debiBuf,e=T.bufPos,m=0}for(let T=1;T<=Co;)if(m<8)s[m]^u[m],m++,T++;else if(m===8){if(e>=o.length)break;let _=rl(o,e,u,h,s,i);if(!_.success)break;u=_.ivPreCrypt,h=_.ivCurCrypt,s=_.debiBuf,e=_.bufPos,m=0}return c}function rl(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=vm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Nm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Bi({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:bm(new Uint8Array(l))||(Nm?Nm.decode(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)})}function ol(o){return f(this,null,function*(){let i=P(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return y.debug(`compressJSON ${e.length} -> ${a.byteLength} ${P()-i}ms`),a}catch(t){return e}})}var bg=Object.prototype.hasOwnProperty;var mi=o=>typeof o=="function",Fi=o=>typeof o=="undefined";var Ia=o=>typeof o=="boolean";var sl=o=>o.isRemote;var nl=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 Dm(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(nl(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(bg.call(o,i))return!1;return!0}}return!1}var vg=0,Ng=1,Om=2;function Dg({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=vg,g=(T,_)=>f(this,null,function*(){let S=n||this;try{let R=yield o.apply(S,a);u>0&&s&&s.call(this,u),u=0,T(R)}catch(R){let q=()=>{clearTimeout(h),u=0,m=Om,_(R)},H=()=>{m!==Om&&u<(mi(c)?c():c)?(u++,m=Ng,mi(t)&&t.call(this,u,q),h=window.setTimeout(()=>{h=-1,g(T,_)},mi(l)?l(u):l)):(q(),mi(r)&&r.call(this,R))};mi(e)?e.call(this,{error:R,retry:H,reject:_,retryFuncArgs:a,retriedCount:u}):H()}});return new Promise(g)}}var pi=Dg;var Mo=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,Fi(this.userId)||Dm(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 Wo={};Mi(Wo,{ANDROID_VERSION:()=>Ca,CHROME_MAJOR_VERSION:()=>We,CHROME_VERSION:()=>Fa,EDGE_VERSION:()=>ya,EDG_MAJOR_VERSION:()=>cl,EDG_VERSION:()=>ba,ELECTRON_MAJOR_VERSION:()=>ml,FIREFOX_MAJOR_VERSION:()=>xo,FIREFOX_VERSION:()=>Ra,HUAWEI_VERSION:()=>Pa,IE_VERSION:()=>xg,IOS_MAIN_VERSION:()=>Qe,IOS_VERSION:()=>ut,IPADQQB_VERSION:()=>xa,IS_ANDROID:()=>me,IS_ANDROID_WEBVIEW:()=>Vg,IS_ANY_SAFARI:()=>Ot,IS_CHROME:()=>Go,IS_CHROME_OS:()=>dl,IS_CHROMIUM_BASE:()=>Be,IS_DESKTOP_IOS_CHROME:()=>gl,IS_EDG:()=>Lo,IS_EDGE:()=>Ur,IS_ELECTRON:()=>Pg,IS_FIREFOX:()=>te,IS_HEADLESS_CHROME:()=>hl,IS_HONOR:()=>ul,IS_HUAWEI:()=>Xs,IS_HUAWEIBROWSER:()=>js,IS_IE:()=>xm,IS_IE8:()=>wg,IS_IOS:()=>_e,IS_IOS_13_OR_14:()=>_l,IS_IOS_15_1:()=>fl,IS_IOS_CHROME:()=>Bs,IS_IPAD:()=>wo,IS_IPADQQB:()=>Ws,IS_IPAD_PRO:()=>al,IS_IPHONE:()=>mr,IS_IPOD:()=>wm,IS_LINUX:()=>Js,IS_LOCAL:()=>Qt,IS_MAC:()=>zt,IS_MACQQB:()=>Gs,IS_MIBROWSER:()=>qs,IS_MQQB:()=>Bo,IS_NATIVE_ANDROID:()=>kg,IS_OLD_ANDROID:()=>Mg,IS_OPENHARMONY:()=>Ho,IS_OPPOBROWSER:()=>Fo,IS_SAFARI:()=>ke,IS_SAFARI_15_1:()=>Bg,IS_SAMSUNGBROWSER:()=>zs,IS_SOGOU:()=>Hs,IS_SOGOUM:()=>Fs,IS_TBS:()=>Xt,IS_UCBROWSER:()=>ll,IS_VIVOBROWSER:()=>Qs,IS_WECHAT:()=>Uo,IS_WIN:()=>Vr,IS_WQQB:()=>$s,IS_WX:()=>Lg,IS_X5MQQB:()=>Vo,IS_XWEB:()=>Po,MACQQB_VERSION:()=>wa,MI_VERSION:()=>La,MQQB_VERSION:()=>ko,OPENHARMONY_VERSION:()=>Ug,OPPO_VERSION:()=>Va,SAFARI_VERSION:()=>Hi,SAMSUNG_VERSION:()=>Ua,SOGOUM_VERSION:()=>va,SOGOU_VERSION:()=>Na,TBS_VERSION:()=>Da,UA_DATA_STRING:()=>qt,USER_AGENT:()=>jt,VIVO_VERSION:()=>Ba,WECHAT_VERSION:()=>Ma,WQQB_VERSION:()=>ka,XWEB_VERSION:()=>Oa,browserInfo:()=>fi,getBrowserCoreNumber:()=>El,getBrowserInfo:()=>Lm,getChromeMajorVersion:()=>$o,getDeviceModel:()=>Gi,getGPUInfo:()=>Tl,getOSName:()=>Ha,getOSNumber:()=>Fr,getOSString:()=>Wi,getOSType:()=>Fg,getTerminalType:()=>Sl,getUserAgentData:()=>Br,isLocalStorageEnabled:()=>$i,isMobile:()=>Zs,isVersionLargerThan:()=>pl,isVersionSmallerThan:()=>Ys});var jt=typeof navigator=="undefined"?"":navigator.userAgent,Z=o=>new RegExp(o,"i").test(jt),Oe=o=>{if(Z(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=jt.match(i);if(e&&e[1])return e[1]}return""},Aa=o=>{if(Z(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=jt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Mm=/AppleWebKit\/([\d.]+)/i.exec(jt),Og=Mm?parseFloat(Mm[1]):NaN,wo=Z("iPad"),al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Z("Macintosh"),mr=Z("iPhone")&&!wo,wm=Z("iPod"),_e=mr||wo||wm||al,me=Z("Android"),Ca=function(){if(me){let o=jt.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}(),Mg=me&&Z("webkit")&&Ca<2.3,kg=me&&Ca<5&&Og<537,te=Z("Firefox"),Ra=Oe("Firefox"),xo=Aa("Firefox"),Ur=Z("Edge"),ya=Oe("Edge"),Lo=Z("Edg"),ba=Oe("Edg"),cl=Aa("Edg"),Fs=Z("SogouMobileBrowser"),va=Oe("SogouMobileBrowser"),Hs=Z("MetaSr\\s"),Na=Oe("MetaSr\\s"),Xt=Z("TBS"),Da=Oe("TBS"),Po=Z("XWEB"),Oa=Oe("XWEB"),wg=Z("MSIE\\s8\\.0"),xm=Z("MSIE\\/\\d+"),xg=function(){if(xm){let o=/MSIE\s(\d+)\.\d/.exec(jt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(jt)&&/rv:11.0/.test(jt)&&(i=11),i}return NaN}(),Uo=Z("(micromessenger|webbrowser)"),Ma=Oe("MicroMessenger"),Vo=!Xt&&Z("MQQBrowser")&&Z("COVC"),Bo=!Xt&&Z("MQQBrowser")&&!Z("COVC"),ko=Bo||Vo?Oe("MQQBrowser"):"",$s=!Xt&&Z(" QQBrowser"),ka=Oe(" QQBrowser"),Gs=!Xt&&Z("QQBrowserLite"),wa=Oe("QQBrowserLite"),Ws=!Xt&&Z("MQBHD"),xa=Oe("MQBHD"),Vr=Z("Windows"),zt=!_e&&Z("MAC OS X"),Js=!me&&Z("Linux"),dl=Z("CrOS"),Lg=Z("MicroMessenger"),ll=Z("UCBrowser"),Pg=Z("Electron"),qs=Z("MiuiBrowser"),La=Oe("MiuiBrowser"),js=Z("HuaweiBrowser"),Xs=Z("Huawei")||Z("HUAWEI"),ul=Z("Honor")||Z("HONOR"),Pa=Oe("HuaweiBrowser"),zs=Z("SamsungBrowser"),Ua=Oe("SamsungBrowser"),Fo=Z("HeyTapBrowser"),Va=Oe("HeyTapBrowser"),Qs=Z("VivoBrowser"),Ba=Oe("VivoBrowser"),Ho=Z("OpenHarmony"),Ug=Oe("OpenHarmony"),$o=()=>Aa("Chrome"),Bs=Z("CriOS"),Be=Z("Chrome"),Go=!Ur&&!Hs&&!Fs&&!Xt&&!Po&&!Lo&&!$s&&!qs&&!js&&!zs&&!Fo&&!Qs&&Be,hl=Z("HeadlessChrome"),We=$o(),Fa=Oe("Chrome"),ml=Aa("Electron"),ke=!Be&&!Bo&&!Vo&&!Gs&&!Ws&&Z("Safari"),Ot=ke||_e,Hi=Oe("Version"),Vg=/Android.*(wv|.0.0.0)/.test(jt),ut=(()=>{if(al)return Hi;if(_e){let o=jt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function Ys(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 pl(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 Qe=Number(ut.split(".")[0]),Bg=Hi==="15.1",fl=ut==="15.1",_l=(()=>{let o=Number(ut.split(".")[0]);return o===14||o===13})(),gl=Bs&&Hi==="11.1.1",Qt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",$i=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),fi=Lm();function Lm(){let o=new Map([[te,["Firefox",Ra]],[Lo,["Edg",ba]],[Go,["Chrome",Fa]],[Bs,["ChiOS",Oe("CriOS")]],[ke&&!Bs,["Safari",Hi]],[Xt,["TBS",Da]],[Po,["XWEB",Oa]],[Uo&&mr,["WeChat",Ma]],[$s,["QQ(Win)",ka]],[Bo,["QQ(Mobile)",ko]],[Vo,["QQ(Mobile X5)",ko]],[Gs,["QQ(Mac)",wa]],[Ws,["QQ(iPad)",xa]],[qs,["MI",La]],[js,["HW",Pa]],[zs,["Samsung",Ua]],[Fo,["OPPO",Va]],[Qs,["VIVO",Ba]],[Ur,["EDGE",ya]],[Fs,["SogouMobile",va]],[Hs,["Sogou",Na]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var ce=null;function Zs(){return ce&&typeof ce.mobile=="boolean"?ce.mobile:me||_e||mr||wo||Ho}var qt="";function Br(){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&&!qt&&(qt=`UAData: ${ce.platform}/${ce.platformVersion}`,ce.architecture&&ce.bitness&&(qt+=` ${ce.architecture}/${ce.bitness}`),ce.mobile&&(qt+=" mobile"),ce.model&&(qt+=` model: ${ce.model.replace(/\s+/g,"/")}`),ce.fullVersionList&&(qt+=` ${ce.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),ce}catch(o){return null}})}function Tl(){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 Gi(){return(ce==null?void 0:ce.model)||""}var km=new Map([[me,"Android"],[_e,"iOS"],[Vr,"Windows"],[zt,"MacOS"],[Js,"Linux"],[dl,"ChromeOS"]]),Ha=function(){return km.get(!0)?km.get(!0):ce?ce.platform:"unknown"};function Fr(){return Vr?1:me?2:zt?3:_e?4:Js?5:dl?6:Ho?7:0}function El(){return Be?1:ke?2:te?3:0}var Wi=()=>{let o=Ha();return ce!=null&&ce.platformVersion?o+=`/${ce.platformVersion}`:_e?o+=`/${ut}`:me&&(o+=`/${Ca}`),o+=`/${fi.name}/${ke&&!Bs?fi.version:fi.version.split(".")[0]}`,ce!=null&&ce.architecture&&(o+=`/${ce.architecture}`),o};function Sl(){return me?4:mr?2:wo?3:zt?12:Vr?5:Js?13:Ho?22:1}function Fg(){return me?"Android":mr?"iPhone":wo?"iPad":zt?"Mac":Vr?"Windows":Js?"Linux":"unknown"}var Pm=Ge(tt(),1),Hg=new Pm.default,I=Hg;var ht=(G=>(G.ROOM_DESTROY="1",G.JOIN_START="21",G.JOIN_SCHEDULE_SUCCESS="22",G.JOIN_SIGNAL_CONNECTION_START="23",G.JOIN_SIGNAL_CONNECTION_END="24",G.JOIN_SEND_CMD="25",G.JOIN_RECEIVED_CMD_RES="26",G.JOIN_SUCCESS="27",G.JOIN_FAILED="28",G.LEAVE_START="51",G.LEAVE_SEND_CMD="52",G.LEAVE_SUCCESS="53",G.PUBLISH_START="61",G.SEND_FIRST_VIDEO_FRAME="62",G.PUBLISH_FAILED="63",G.SUBSCRIBE_START="81",G.SUBSCRIBE_SUCCESS="82",G.SUBSCRIBE_FAILED="84",G.UNSUBSCRIBE_SUCCESS="83",G.LOCAL_TRACK_CAPTURE_START="101",G.LOCAL_TRACK_CAPTURE_SUCCESS="102",G.LOCAL_TRACK_CAPTURE_FAILED="103",G.LOCAL_TRACK_PUBLISHED="104",G.LOCAL_TRACK_UNPUBLISHED="105",G.LOCAL_TRACK_REPLACED="106",G.SWITCH_DEVICE_SUCCESS="107",G.TRACK_MUTED="108",G.TRACK_UNMUTED="109",G.REMOTE_TRACK_SUBSCRIBED="110",G.REMOTE_TRACK_UNSUBSCRIBED="111",G.LOCAL_TRACK_RECAPTURE="112",G.LOCAL_AUDIO_STARTED="113",G.LOCAL_AUDIO_STOPPED="114",G.REMOTE_AUDIO_STARTED="115",G.REMOTE_AUDIO_STOPPED="116",G.PLAY_TRACK_START="151",G.PLAYER_STATE_CHANGED="152",G.VIDEO_LOADED_DATA="153",G.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",G.AUDIO_CONTEXT_LONG_SUSPENDED="155",G.SIGNAL_CONNECTION_STATE_CHANGED="201",G.PEER_CONNECTION_STATE_CHANGED="202",G.SINGLE_CONNECTION_STAT="203",G.SPC_RECONNECTED="204",G.HEARTBEAT_REPORT="251",G.RECEIVED_PUBLISHED_USER_LIST="252",G.REMOTE_PUBLISH_STATE_CHANGED="253",G.AUDIO_LEVEL_INTERVAL="260",G.NETWORK_QUALITY="261",G.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",G.QUALITY_LIMITATION_CHANGED="263",G.LOG="264",G.AUDIO_PROCESSOR_DEBUG="265",G.SSO_SWITCH="266",G.SWITCH_ROOM_START="401",G.SWITCH_ROOM_SUCCESS="407",G.SWITCH_ROOM_FAILED="408",G))(ht||{});var C=ht;var Il=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);I.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&I.emit("266",{enable:!0})}),I.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&I.emit("266",{enable:!1})}},pr=new Il;var $g="%cTRTC%c%s",Gg="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Wg="display: inline",$a=class $a{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);!go&&!vs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){I.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Bt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),I.on(C.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),I.once(C.JOIN_FAILED,()=>{this.startUpload()}),I.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(ee(t.userId)&&X(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:ea(),sdkAppId:String(a),userId:n,version:Ve,log:c.map(m=>m.log).join(`
|
|
6
|
-
`)},u=JSON.stringify(l),h=pr.enable?Vi(l,2002,a):u;yield this.uploadLogWithRetry(h,a,h instanceof Uint8Array,u),c.forEach(m=>m.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return pi({retryFunction:()=>Bi({url:Ui(e,ar.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(pr.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(ki()),`[${_o(e)}] <${Bt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){E(Bt[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(ee(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};I.emit(C.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=Bt[i])==null?void 0:a.toLowerCase())||"info";$a.PRINT_LOG_TAG?console[n]($g,Gg,Wg,...e):console[n](...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 Mo(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Bt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d($a,"PRINT_LOG_TAG",!(_e||me||hl));var Al=$a,y=new Al;var Jg=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)})},Ks=Jg;var Cl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!$i())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($i())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){y.warn(i)}}getItem(i){if(!$i())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($i())try{let t={expiresIn:Date.now()+ia,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){y.warn(t)}}deleteItem(i){if(!$i())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($i())try{localStorage.clear()}catch(i){y.warn(i)}}},Jo=new Cl;var Ei={};Mi(Ei,{HTTPS_API:()=>pT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>Xl,IS_GET_CAPABILITIES_SUPPORTED:()=>jl,IS_GET_SETTINGS_SUPPORTED:()=>Ti,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>ql,IS_INSERTABLE_STREAM_SUPPORTED:()=>ii,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>ac,IS_RTC_RTP_SENDER_SUPPORTED:()=>an,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Qo,IS_SEI_SUPPORTED:()=>dn,IS_SPC_SUPPORTED:()=>zo,basis:()=>gT,capabilityCheck:()=>Yl,checkSystemRequirementsInternal:()=>rc,decodeSupportStatus:()=>ic,detectVideoCodecCapabilities:()=>Zl,detectVideoDecoderCapabilities:()=>pp,detectVideoEncoderCapabilities:()=>mp,encodeSupportStatus:()=>Wl,getBrowserInfo:()=>aT,getDisplayResolution:()=>sp,getH264ProfileLevelIds:()=>ET,isAddTransceiverSupported:()=>pt,isBrowserSupported:()=>Gl,isCanvasCaptureStreamAPISupported:()=>cp,isCanvasSmallStreamSupported:()=>oc,isGetReceiversSupported:()=>jr,isGetSendersSupported:()=>_r,isGetTransceiversSupported:()=>gi,isGetUserMediaSupported:()=>np,isMediaDevicesSupported:()=>tc,isMediaSessionSupported:()=>lp,isMediaStreamTrackGeneratorSupported:()=>cT,isMediaStreamTrackProcessorSupported:()=>sn,isReplaceTrackSupported:()=>Jl,isRequestVideoFrameCallbackSupported:()=>Xr,isSIMDSupported:()=>Ql,isScaleResolutionDownBySupported:()=>dp,isScreenCaptureApiAvailable:()=>nn,isSelectedCandidatePair:()=>fr,isSetParametersSupported:()=>cn,isSetSinkIdSupported:()=>uT,isSmallStreamSupported:()=>sc,isStopTransceiverSupported:()=>_T,isTRTCSupported:()=>lT,isUnifiedPlanDefault:()=>fT,isUsedInHttpProtocol:()=>ji,isWebAudioSupported:()=>ap,isWebCodecSupported:()=>nc,isWebCodecsSupported:()=>on,isWebRTCSupported:()=>zl,isWebTransportSupported:()=>up});var Pl={};Mi(Pl,{AUDIO_LEVEL_SCALE:()=>Rt,AudioCodecPipelineType:()=>Xa,AudioDecoderDowngradeState:()=>vl,AudioPlayerMode:()=>Ml,AudioType:()=>Fm,BASIC_TYPE:()=>Ji,BannedReason:()=>kl,CONNECTION_CLOSED_REASON:()=>yl,CheckPermissionType:()=>Ll,ClientEvent:()=>Um,CodecType:()=>Jm,ConnectionEvent:()=>Yt,ConnectionState:()=>Ct,DECODE_FAILED_ERROR_CODE:()=>xl,DenoiserMode:()=>wl,DeviceType:()=>za,FacingMode:()=>Ja,FrameWorkType:()=>Ga,LeaveReason:()=>Wm,LocalTrackEvent:()=>Hr,MULTI_VIDEO_DATA_TYPE:()=>ei,MediaType:()=>we,MediaTypeLabel:()=>qg,MonitorEventId:()=>en,MutedFlag:()=>Bm,NetworkQualityValue:()=>Ol,PlayerState:()=>$r,ReceiveMode:()=>Gm,RemoteStreamType:()=>mt,RemoteTrackEvent:()=>Gr,RoomEvent:()=>Zt,SMALL_MODE:()=>tn,SceneNumber:()=>bl,StreamEvent:()=>Vm,StreamType:()=>$m,SubscribeMediaType:()=>Rl,TIMER_TYPE:()=>ti,TRACK_ACTION:()=>Dl,TRACK_KIND:()=>Nl,TrackEvent:()=>Kt,UserRole:()=>ot,UserRoleNumber:()=>Wr,VideoCodec:()=>Mt,VideoCodecPipelineType:()=>ja,VideoContentHint:()=>qo,VideoDecoderDowngradeState:()=>Wa,VideoPlayerMode:()=>qa,VideoType:()=>Hm});var Ga=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(Ga||{}),Yt=(_=>(_.TRACK_ADDED="track-added",_.TRACK_UPDATED="track-updated",_.TRACK_SUBSCRIBED="track-subscribed",_.STREAM_ADDED="stream-added",_.STREAM_REMOVED="stream-removed",_.STREAM_UPDATED="stream-updated",_.STREAM_PUBLISHED="stream-published",_.STREAM_SUBSCRIBED="stream-subscribed",_.STREAM_UNSUBSCRIBED="stream-unsubscribed",_.STATE_CHANGED="state-changed",_.ERROR="error",_.CONNECTION_STATE_CHANGED="connection-state-changed",_.FIREWALL_RESTRICTION="firewall-restriction",_.SEI_MESSAGE="sei-message",_.CLOSED="closed",_))(Yt||{}),yl=(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))(yl||{}),Um=(S=>(S.STREAM_ADDED="stream-added",S.STREAM_REMOVED="stream-removed",S.STREAM_UPDATED="stream-updated",S.STREAM_SUBSCRIBED="stream-subscribed",S.CONNECTION_STATE_CHANGED="connection-state-changed",S.PEER_JOIN="peer-join",S.PEER_LEAVE="peer-leave",S.MUTE_AUDIO="mute-audio",S.MUTE_VIDEO="mute-video",S.UNMUTE_AUDIO="unmute-audio",S.UNMUTE_VIDEO="unmute-video",S.CLIENT_BANNED="client-banned",S.NETWORK_QUALITY="network-quality",S.AUDIO_VOLUME="audio-volume",S.SEI_MESSAGE="sei-message",S.ERROR="error",S))(Um||{}),Vm=(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))(Vm||{}),Hr=(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.RENDER="render",c))(Hr||{}),$r=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))($r||{}),Zt=(w=>(w.PEER_JOIN="peer-join",w.PEER_LEAVE="peer-leave",w.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",w.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",w.BANNED="banned",w.NETWORK_QUALITY="network-quality",w.AUDIO_VOLUME="audio-volume",w.SEI_MESSAGE="sei-message",w.ERROR="error",w.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",w.REMOTE_PUBLISHED="remote-published",w.REMOTE_UNPUBLISHED="remote-unpublished",w.FIREWALL_RESTRICTION="firewall-restriction",w.HEARTBEAT_REPORT="heartbeat-report",w.CUSTOM_MESSAGE="custom-message",w.LAYER_DATA="layerData",w.FIRST_VIDEO_FRAME="first-video-frame",w.DUMP="dump",w.AUDIO_FRAME="audio-frame",w.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",w.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",w.NTP_TIME_UPDATED="ntp-time-updated",w))(Zt||{}),Kt=(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.VIDEO_SIZE_CHANGED="video-size-changed",c))(Kt||{}),Gr=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(Gr||{}),Bm=(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))(Bm||{}),bl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(bl||{}),Wr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Wr||{}),ot=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(ot||{}),Ct=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Ct||{}),vl=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(vl||{}),Wa=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(Wa||{}),Nl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Nl||{}),Dl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Dl||{}),we=(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))(we||{}),qg={1:"audio",2:"auxVideo",4:"video"},Fm=(i=>(i[i.opus=111]="opus",i))(Fm||{}),Hm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Hm||{}),$m=(e=>(e.Big="big",e.Small="small",e))($m||{}),mt=(e=>(e.Main="main",e.Aux="auxiliary",e))(mt||{}),ei=(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))(ei||{}),en=(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))(en||{}),Ol=(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))(Ol||{}),Gm=(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))(Gm||{}),Ja=(e=>(e.user="user",e.environment="environment",e))(Ja||{}),qa=(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))(qa||{}),Ml=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Ml||{}),kl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(kl||{}),Wm=(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))(Wm||{}),Rt=1e8,wl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(wl||{}),Rl=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)}},Ji=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Ji||{}),Mt=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Mt||{}),ja=(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))(ja||{}),Xa=(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))(Xa||{}),Jm=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(Jm||{}),xl=(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))(xl||{}),qo=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(qo||{}),ti=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(ti||{}),tn=(e=>(e.CANVAS="canvas",e.API="api",e))(tn||{}),Ll=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Ll||{}),za=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(za||{});var V={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"},Je={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: ${ve(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: ${ve(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 qm=(o,i)=>i?`${li}/${o}/${i}`:`${li}/${o}/index.html`;var jg=()=>{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(kd);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 B(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";ne(Je[i])?s=Je[i](e):ee(Je[i])&&(s=Je[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=jg();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ne(l[i])?a=l[i](e):ee(l[i])&&(a=l[i]));let u=s;return $t()&&(c&&c[i]&&(ne(c[i])?n=c[i](e):ee(c[i])&&(n=c[i])),n&&(r?u=`${n}
|
|
7
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${qm("zh-cn",a)}
|
|
3
|
+
`}});var sg=Qn(ti=>{"use strict";var os=rg(),aI=og(),cI=Fd();ti.grammar=cI;ti.write=aI;ti.parse=os.parse;ti.parseParams=os.parseParams;ti.parseFmtpConfig=os.parseFmtpConfig;ti.parsePayloads=os.parsePayloads;ti.parseRemoteCandidates=os.parseRemoteCandidates;ti.parseImageAttributes=os.parseImageAttributes;ti.parseSimulcastStreamList=os.parseSimulcastStreamList});var Kp=(ie=>(ie[ie.INVALID_PARAMETER=4096]="INVALID_PARAMETER",ie[ie.INVALID_OPERATION=4097]="INVALID_OPERATION",ie[ie.NOT_SUPPORTED=4098]="NOT_SUPPORTED",ie[ie.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",ie[ie.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",ie[ie.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",ie[ie.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",ie[ie.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",ie[ie.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",ie[ie.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",ie[ie.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",ie[ie.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",ie[ie.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",ie[ie.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",ie[ie.CLIENT_BANNED=16448]="CLIENT_BANNED",ie[ie.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",ie[ie.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",ie[ie.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",ie[ie.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",ie[ie.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",ie[ie.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",ie[ie.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",ie[ie.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",ie[ie.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",ie[ie.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",ie[ie.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",ie[ie.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",ie[ie.API_CALL_ABORTED=16461]="API_CALL_ABORTED",ie[ie.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",ie[ie.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",ie[ie.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",ie[ie.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",ie[ie.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",ie[ie.UNKNOWN=65535]="UNKNOWN",ie))(Kp||{}),q=Kp;var x_=function(i){for(let t in q)if(q[t]===i)return t;return"UNKNOWN"},Yn=class extends Error{constructor({name:e="RtcError",message:r,code:o=q.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${x_(o)} 0x${o.toString(16)}>`,u=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(a)?"":` ${a}`}`;super(u);l(this,"code");l(this,"extraCode");l(this,"message");l(this,"originMessage");l(this,"name");l(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=u,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},de=Yn;var ef=0;var tf=function(){return ef},fi=function(){return Date.now()+ef},Gc=function(){let i=new Date;return i.setTime(fi()),i.toLocaleString()},Vs=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 Zr={};hi(Zr,{REPORT_TYPE:()=>Ys,buildSSOPackage:()=>Ii,bytes2ms:()=>hf,calculateScaleResolutionDownNumber:()=>cd,concatArrayBuffers:()=>Rf,convertObjectNumberToInt:()=>ua,copyProperties:()=>mf,deepClone:()=>Wo,deepCloneBasic:()=>rd,deepMerge:()=>xr,delay:()=>zo,fibonacci:()=>Go,formatedTime:()=>od,getConstructorName:()=>qs,getContainerFromElement:()=>yf,getEnv:()=>df,getFirst16Bits:()=>Cf,getInternalVersion:()=>If,getLast16Bits:()=>vf,getLoggerUrl:()=>Ti,getMediaStreamTrackInfo:()=>ad,getMuteStateFromFlag:()=>qo,getNetworkType:()=>na,getNumNetworkType:()=>id,getReconnectionTimeout:()=>ff,getStringByteLength:()=>Af,getTurnServer:()=>Sf,getUint32Version:()=>sd,getValueType:()=>ut,getViewListFromView:()=>Xs,glog:()=>aa,ipv4ToUint32:()=>Js,isArray:()=>at,isAudioWorkletSupported:()=>_f,isBoolean:()=>Qe,isConstructor:()=>jo,isEmpty:()=>zs,isFunction:()=>je,isLangChinese:()=>Or,isMediaStreamTrack:()=>gf,isNumber:()=>ke,isObject:()=>ar,isOverseaSdkAppId:()=>_i,isPlainObject:()=>jt,isPortrait:()=>Zl,isPromise:()=>ro,isRemoteTrack:()=>Ef,isRotate90Or270:()=>cr,isSetSinkIdSupported:()=>Tf,isString:()=>Ne,isUndefined:()=>M,loadImage:()=>Qs,loadVideo:()=>bf,ms2bytes:()=>pf,ms2samples:()=>Yl,normalizeUrl:()=>Jo,performanceNow:()=>Ee,promiseAny:()=>ca,samples2ms:()=>Ql,setNetworkType:()=>lf,stringify:()=>Er,stringifyIncludeValue:()=>da,throttlePromise:()=>nd});var $l={};hi($l,{AUDIO_MUTE_BIT:()=>Xc,AUDIO_STAT_BIT:()=>Bs,AUX_STAT_BIT:()=>ta,AUX_STREAM_MSID:()=>j_,BACKEND_ENV:()=>Jc,BASE_DOC_URL:()=>Xr,BASE_HOST:()=>rf,CAPABILITIES_KEYS:()=>Zc,CLASS_NAME:()=>fT,CLOUD_CONSOLE_URL:()=>U_,CROSS_ROOM_BIT:()=>W_,DATA_FREEZE_TIMING:()=>Yc,DOC_URL:()=>V_,DTLS_STATE_UNKNOWN:()=>tT,ENV_NAME:()=>gi,EXCHANGE_SDP_TIMEOUT:()=>aT,IS_WORKER:()=>Fs,IS_WORKLET:()=>Zn,KIBANA_EVENT:()=>gr,LOCAL_STREAM_PUBLISH_STATE:()=>sf,LOGGER_CMD_TYPE:()=>to,LOGGER_DOMAIN:()=>xl,LOGGER_DOMAIN_OVERSEA:()=>Pl,LOG_LEVEL:()=>wr,LOG_LEVEL_NAME:()=>ET,MAIN_STREAM_MSID:()=>G_,MAX_RTT:()=>ia,MICROPHONE_COMMUNICATIONS:()=>gT,MICROPHONE_DEFAULT:()=>Ho,MUTE_ALL_BIT:()=>H_,NAME:()=>O,NETWORK_TYPE:()=>$o,NOT_SUPPORTED_H264:()=>dT,PAUSED_RETRY_COUNT:()=>Bo,PEERCONNECTION_CONNECTING_TIMEOUT:()=>hT,PEER_CONNECTION_STATE:()=>rT,PEER_LEAVE_REASON:()=>nf,RECOVER_CAPTURE_INTERVAL:()=>Hs,REMOTE_STREAM_TYPE_AUX:()=>z_,REMOTE_STREAM_TYPE_MAIN:()=>q_,RENDER_FREEZE_TIMING:()=>uT,SCHEDULE_DOMAIN:()=>Ei,SCHEDULE_TIMEOUT:()=>pT,SDP_SEMANTICS_PLAN_B:()=>cT,SDP_SEMANTICS_UNIFIED_PLAN:()=>Fl,SECOND_HOST:()=>k_,SIGNAL_PING_PONG_INTERVAL:()=>$_,SIGNAL_PING_TIMEOUT:()=>F_,SIGNAL_RECONNECTION_COUNT:()=>oT,SMALL_STAT_BIT:()=>Ul,SPEAKER_DEFAULT:()=>ra,STORAGE_EXPIRES_TIME:()=>jc,STREAM_TYPE_BIG:()=>lT,STREAM_TYPE_SMALL:()=>mT,SUBSCRIBE_SMALL_RETRY_COUNT:()=>_T,SYNC_USER_LIST_INTERVAL:()=>sT,Scene:()=>Qr,THIRD_HOST:()=>L_,TRANSPORT_DIRECTION:()=>B_,TRTC_ERROR_ASSISTANCE:()=>kl,TRTC_QUALITY_BAD:()=>Z_,TRTC_QUALITY_DISCONNECTED:()=>eT,TRTC_QUALITY_EXCELLENT:()=>X_,TRTC_QUALITY_GOOD:()=>Q_,TRTC_QUALITY_POOR:()=>Y_,TRTC_QUALITY_UNKNOWN:()=>J_,TRTC_QUALITY_VERY_BAD:()=>K_,UPDATE_OFFER_TIMEOUT:()=>nT,VIDEO_MUTE_BIT:()=>Qc,VIDEO_STAT_BIT:()=>$s,audioProfileMap:()=>qc,defaultBigVideoProfile:()=>ea,defaultSmallVideoProfile:()=>Ll,getRetryCount:()=>iT,getScriptDir:()=>P_,innerVersion:()=>Ml,loggerProxy:()=>Kn,screenProfileMap:()=>zc,setLoggerProxy:()=>Fo,setRetryCount:()=>Vl,setVersion:()=>Ol,version:()=>dt,videoProfileMap:()=>Mr});var Ml="4.15.00.1600",dt="5.0.0";function Ol(i){dt=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));Ml=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var Fs=typeof importScripts!="undefined",Zn=typeof registerProcessor!="undefined",P_=()=>{let i=Fs?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},Kn="",Fo=i=>Kn=i,rf="web.sdk.qcloud.com",k_="web.sdk.tencent.cn",L_="web.sdk.cloud.tencent.cn",U_="https://console.cloud.tencent.com/trtc",Xr=`https://${rf}/trtc/webrtc/v5/doc`,V_=`${Xr}/zh-cn/`,xl="https://yun.tim.qq.com",Pl="https://apisgp.my-imcloud.com",kl="trtc_error_assistance",to={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},gi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},wr=(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))(wr||{}),F_=18e3,$_=2e3,$o={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},jc=7*24*3600*1e3,qc={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}},Mr={"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}},ea=Mr["480p_2"],Ll=Mr["120p_2"],zc={"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}},O={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",RESIZE:"resize",TIME_UPDATE:"timeupdate"},B_={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Jc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Qr=(e=>(e.LIVE="live",e.RTC="rtc",e))(Qr||{}),$s=1,Ul=2,ta=4,Bs=8,Xc=64,Qc=16,H_=112,W_=128,G_="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",j_="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",q_=O.MAIN,z_=O.AUXILIARY,J_=0,X_=1,Q_=2,Y_=3,Z_=4,K_=5,eT=6,tT="unknown",rT={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},of=1/0;function Vl(i){of=i}function iT(){return of}var oT=30,gr={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",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},sT=1e4,nT=1e4,aT=1e4,Fl="unified-plan",cT="plan-b",dT=1028,sf=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(sf||{}),Yc=500,uT=1e3,lT=O.BIG,mT=O.SMALL,hT=10*1e3,Ei={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},pT=2e3,fT={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Bo=5,Ho="default",ra=Ho,gT="communications",ET=Object.keys(wr),nf=["normal leave","timeout leave","kick","role change"],_T=10,Hs=2e3,Zc=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],ia=10*1e3;var TT=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 a(p){try{m(r.next(p))}catch(g){n(g)}}function u(p){try{m(r.throw(p))}catch(g){n(g)}}function m(p){p.done?s(p.value):o(p.value).then(a,u)}m((r=r.apply(i,t||[])).next())})},Bl=Symbol(32),Hl=Symbol(16),Wl=Symbol(8),Yr=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.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(t,e){return e&&this.consume(),this.need=t,this.flush()}read(t){return TT(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,r)=>{var o;this.reject=r,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(t,!0)||(o=this.pull)===null||o===void 0||o.call(this,t)})})}readU32(){return this.read(Bl)}readU16(){return this.read(Hl)}readU8(){return this.read(Wl)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null,e=this.buffer.subarray(this.consumed),r=0,o=s=>e.length<(r=s);if(typeof this.need=="number"){if(o(this.need))return;t=e.subarray(0,r)}else if(this.need===Bl){if(o(4))return;t=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===Hl){if(o(2))return;t=e[0]<<8|e[1]}else if(this.need===Wl){if(o(1))return;t=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(o(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,r)),t=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(o(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,t&255]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,t&255]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){let e=this.buffer.length,r=e+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{let o=new Uint8Array(r);o.set(this.buffer),this.buffer=o}return this.buffer.subarray(e,r)}else return this.buffer=new Uint8Array(t),this.buffer}};Yr.U32=Bl;Yr.U16=Hl;Yr.U8=Wl;var IT=128,ST=127,YA=~ST,ZA=Math.pow(2,31);function Gl(i){let t=new Yr;for(;i>=128;)t.malloc(1)[0]=i&255|IT,i>>>=7;return t.malloc(1)[0]=i&255,t.buffer||new Uint8Array(0)}function Kc(i,t=0){let e=new Yr,r=t<<3;switch(typeof i){case"boolean":let o=e.malloc(2);o[0]=r,o[1]=i?1:0;break;case"number":e.malloc(1)[0]=r,e.write(Gl(i));break;case"string":e.malloc(1)[0]=r|2;let s=new TextEncoder().encode(i);e.write(Gl(s.length));let n=e.malloc(s.length);for(let u=0;u<s.length;u++)n[u]=s[u];break;case"object":let a=new Yr;if(Array.isArray(i))for(let u=0;u<i.length;u++){let m=Kc(i[u],u+1);m&&a.write(m)}else{let u=1;for(let m in i){let p=Kc(i[m],u++);p&&a.write(p)}}t===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=r|2,a.buffer&&(e.write(Gl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var oa=class{constructor(){l(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(t){this.buffer.push(t>>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(t&255)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(t&255)}writeByte(t){this.buffer.push(t&255)}writeBytes(t){for(let e=0;e<t.length;e++)this.buffer.push(t[e])}};function jl(i,t,e){i[e]=t>>>24&255,i[e+1]=t>>>16&255,i[e+2]=t>>>8&255,i[e+3]=t&255}function Gt(i,t){return i[t]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3]}function ql(i,t){return i[t]}function Ws(i,t,e){return new TextDecoder().decode(yT(i,t,e))}function yT(i,t,e){return i.slice(t,t+e)}var zl=0,ed=2654435769,td=16,Xl=4,Gs=2,js=7;function AT(i,t,e,r="AVQualityReportSvc.C2S",o=2e3,s=2,n=30){return{version:o,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:i,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:r,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:t}}function af(i,t){let e=new oa,r=AT(t,i,zl);zl=zl+1&2147483647,e.writeInt32(0),e.writeInt32(r.version),e.writeByte(r.encryption);let o=new TextEncoder().encode(r.d2);e.writeInt32(o.length+4),o&&e.writeBytes(o),e.writeByte(r.uinType);let s=new TextEncoder().encode(r.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new oa;n.writeInt32(0),n.writeInt32(r.reqHead.seqNumber),n.writeInt32(r.reqHead.appId),n.writeByte(r.reqHead.appId>>>24&255),n.writeByte(r.reqHead.appId>>>16&255),n.writeByte(r.reqHead.appId>>>8&255),n.writeByte(r.reqHead.appId&255);for(let Z=4;Z<16;Z++)n.writeByte(0);let a=new TextEncoder().encode(r.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let u=new TextEncoder().encode(r.reqHead.serviceCmd);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let m=new TextEncoder().encode(r.reqHead.cookie);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let p=new TextEncoder().encode(r.reqHead.imei);n.writeInt32(p.length+4),p.length&&n.writeBytes(p);let g=new TextEncoder().encode(r.reqHead.ksid);n.writeInt32(g.length+4),g.length&&n.writeBytes(g);let E=new TextEncoder().encode(r.reqHead.clientVersionInfo);n.writeInt16(E.length+2),E.length&&n.writeBytes(E);let A=n.length;n.data[0]=A>>>24&255,n.data[1]=A>>>16&255,n.data[2]=A>>>8&255,n.data[3]=A&255,Ne(i)&&(i=new TextEncoder().encode(i)),n.writeInt32(i.length+4),i.length&&n.writeBytes(i);let C=new Uint8Array(n.data),N=null;r.encryption===1?N=new TextEncoder().encode(r.uin):r.encryption===2&&(N=new Uint8Array(16)),N&&(C=bT(C,N)),e.writeBytes(C);let D=new Uint8Array(e.data),x=D.length;return D[0]=x>>>24&255,D[1]=x>>>16&255,D[2]=x>>>8&255,D[3]=x&255,D}function bT(i,t){let e=i.length,o=(e+1+Gs+js)%8;o&&(o=8-o);let s=e+1+Gs+js+o,n=new Uint8Array(s),a=0,u=new Uint8Array(8),m=new Uint8Array(8),p=new Uint8Array(8),g=0;u[0]=Math.floor(Math.random()*256)&248|o,g=1;for(let A=0;A<o;A++)u[g]=Math.floor(Math.random()*256)&255,g+=1;for(let A=0;A<Gs;)if(g<8&&(u[g]=Math.floor(Math.random()*256)&255,g+=1,A+=1),g===8){Jl(u,t,m,p,n,a),a+=8,g=0;for(let C=0;C<8;C++)p[C]=n[a-8+C]}let E=0;for(;E<e;)if(g<8&&(u[g]=i[E],g+=1,E+=1),g===8){Jl(u,t,m,p,n,a),a+=8,g=0;for(let A=0;A<8;A++)p[A]=n[a-8+A]}for(let A=0;A<js;)if(g<8&&(u[g]=0,g+=1,A+=1),g===8){Jl(u,t,m,p,n,a),a+=8,g=0;for(let C=0;C<8;C++)p[C]=n[a-8+C]}return n}function Jl(i,t,e,r,o,s){for(let n=0;n<8;n++)i[n]^=r[n];RT(i,t,o,s);for(let n=0;n<8;n++)o[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=i[n]}function RT(i,t,e,r){let o=Gt(i,0),s=Gt(i,4),n=[];for(let u=0;u<4;u++)n[u]=Gt(t,u*4);let a=0;for(let u=0;u<td;u++)a+=ed,a=a>>>0,o+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],o=o>>>0,s+=(o<<4)+n[2]^o+a^(o>>>5)+n[3],s=s>>>0;jl(e,o,r),jl(e,s,r+4)}var df=function(){return new URLSearchParams(location.search).get("trtc_env")||""},_i=i=>Number(i)<14e8,Ti=function(i,t){let e;Kn?e=Kn:e=_i(i)?Pl:xl;let r=Math.floor(Math.random()*eo(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},sa="unknown";function na(){if(sa!=="unknown")return sa;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&&(sa=uf(r,o)),sa}function uf(i,t){if($o[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function lf(i){sa=uf(i)}function id(){return $o[na()]}function mf(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 hf(i,t=48e3){return Ql(i/4,t)}function Ql(i,t=48e3){return i*1e3/t}function pf(i,t=48e3){return Yl(i,t)*4}function Yl(i,t=48e3){return i*t/1e3}var aa=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Or=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},jt=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 Go(i,t=1,e=1){return i<=1?e:Go(i-1,e,t+e)}function ff(i){return i>8?30*1e3:Go(i)*1e3}function ut(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var je=i=>typeof i=="function",M=i=>typeof i=="undefined",Ne=i=>typeof i=="string",ke=i=>typeof i=="number",Qe=i=>typeof i=="boolean",ar=i=>ut(i)==="object",at=i=>ut(i)==="array",gf=i=>ut(i)==="MediaStreamTrack".toLowerCase(),Ef=i=>i.isRemote,ro=i=>ut(i)==="promise",jo=i=>je(i)&&i.prototype.constructor===i,qs=i=>jo(i)?i.prototype.constructor.name:"",_f=typeof AudioWorkletNode!="undefined",Tf=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function ca(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 Ee(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var cf=i=>+i<10?`0${i}`:i,If=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=cf(e[1])+cf(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},vT=Object.prototype.hasOwnProperty,{toString:ub}=Object.prototype;function zs(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(jt(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(vT.call(i,t))return!1;return!0}}return!1}function qo(i,t){return{userId:t,hasAudio:!!(i&Bs),hasVideo:!!(i&$s),hasAuxiliary:!!(i&ta),hasSmall:!!(i&Ul),audioMuted:!!(i&Xc),videoMuted:!!(i&Qc),audioAvailable:!!(i&Bs)&&!(i&Xc),videoAvailable:!!(i&$s)&&!(i&Qc)}}function Sf(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!M(i.username)&&!M(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",M(i.credentialType)||(t.credentialType=i.credentialType)),t}function Js(i,t=!0){if(!Ne(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 xr=function(i,t,e,r){if(!(ar(i)&&ar(t)))return 0;let o=0,s=Object.keys(t),n;for(let a=0,u=s.length;a<u;a++)if(n=s[a],!(M(t[n])||e&&e.includes(n)))if(ar(i[n])&&ar(t[n]))o+=xr(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=Wo(t[n]),o+=1)}return o};function Wo(i){if(at(i)){let t=[];return i.forEach((e,r)=>{t[r]=Wo(e)}),t}if(ar(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Wo(i[e])}),t}return i}var Xs=i=>{let t=[];if(at(i))t=[...i];else if(Ne(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},yf=i=>Ne(i)?document.getElementById(i):i,CT=i=>{let t=u=>u<10?`0${u}`:`${u}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),a=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${a}`},od=()=>CT(new Date);function Er(i,{keysToInclude:t,keysToExclude:e}){try{if(at(i))return`[${i.map(n=>Er(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!jt(i)||!at(t)&&!at(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]=jt(i[n])||at(i[n])?JSON.parse(Er(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function da(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),Er(i,{keysToInclude:e})}function Af(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Zl=()=>{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},Qs=i=>y(void 0,null,function*(){return new Promise((t,e)=>{let r;if(Ne(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 de({code:q.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),sd=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},ua=i=>(Object.keys(i).forEach(t=>{ke(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(jt(i[t])||at(i[t]))&&ua(i[t])}),i);function zo(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function nd(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function Jo(i){return i.replace(/(^|[^:])\/{2,}/g,"$1/")}function ad(i){var t;try{let{width:e,height:r,frameRate:o,sampleRate:s,sampleSize:n,channelCount:a}=(t=i.getSettings)==null?void 0:t.call(i),u=i.kind===O.AUDIO?`${s}x${n}@${a}`:`${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} ${u}${m}`}catch(e){return""}}function cd(i,t){return i.width*i.height===t.width*t.height?1:Zl()&&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 cr(i){return i===90||i===270}function bf(i){return y(this,null,function*(){return new Promise((t,e)=>{let r=document.createElement("video");r.crossOrigin="anonymous",r.src=i,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play().then(()=>t(r)),r.onerror=()=>{e(r.error)}})})}function rd(i,t=new WeakMap){if(typeof i!="object"||i===null)return i;if(t.has(i))return t.get(i);if(Array.isArray(i)){let e=[];return t.set(i,e),i.forEach((r,o)=>{e[o]=rd(r,t)}),e}if(Object.prototype.toString.call(i)==="[object Object]"){let e={};return t.set(i,e),Reflect.ownKeys(i).forEach(r=>{e[r]=rd(i[r],t)}),e}return i}var Ys=(r=>(r[r.END_REPORT=2001]="END_REPORT",r[r.LOG=2002]="LOG",r[r.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",r))(Ys||{});function NT(i,t,e,r){let o={data:i,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return M(r)||(o=ge(X({},o),{gzip:+r})),{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:t,bytes_report_data:JSON.stringify(o)}}}function Ii(i,t,e,r){try{let o=NT(i,t,e,r),s=Kc(o);return af(s,e)}catch(o){return JSON.stringify(i)}}function Rf(i,t){let e=new Uint8Array(i.byteLength+t.byteLength);return e.set(new Uint8Array(i),0),e.set(new Uint8Array(t),i.byteLength),e.buffer}function vf(i){return(i&65535)>>>0}function Cf(i){return(i&4294901760)>>>0}function Nf(i){let t=DT(i);return t==null?void 0:t.busiBuff}function DT(i){try{let t={},e=0;t.totalLength=Gt(i,e),e+=4,t.version=Gt(i,e),e+=4,t.encryption=ql(i,e),e+=1,t.uinType=ql(i,e),e+=1,t.uinLength=Gt(i,e),e+=4,t.uin=t.uinLength>4?Ws(i,e,t.uinLength-4):"",e+=t.uinLength-4;let r=i.slice(e);if(t.encryption===2){let o=new Uint8Array(16).fill(0);i=wT(r,o),t.decrypted=!0,e=0}else i=r,e=0;return t.rspHeadLength=Gt(i,e),e+=4,t.seqNo=Gt(i,e),e+=4,t.retCode=Gt(i,e),e+=4,t.retStrLength=Gt(i,e),e+=4,t.retStr=t.retStrLength?Ws(i,e,t.retStrLength-4):"",e+=t.retStrLength-4,t.serviceCmdLength=Gt(i,e),e+=4,t.serviceCmd=t.serviceCmdLength?Ws(i,e,t.serviceCmdLength-4):"",e+=t.serviceCmdLength-4,t.cookieLength=Gt(i,e),e+=4,t.cookie=t.cookieLength?Ws(i,e,t.cookieLength-4):"",e+=t.cookieLength-4,t.flag=Gt(i,e),e+=4,t.busiBuffLength=Gt(i,e),e+=4,t.busiBuff=t.busiBuffLength?Ws(i,e,t.busiBuffLength-4):"",e+=t.busiBuffLength-4,t}catch(t){}}function Df(i,t){let e=i[0]<<24|i[1]<<16|i[2]<<8|i[3],r=i[4]<<24|i[5]<<16|i[6]<<8|i[7];e=e>>>0,r=r>>>0;let o=ed*td>>>0;for(let s=0;s<td;s++)r-=(e<<Xl)+t[2]^e+o^(e>>>5)+t[3],r=r>>>0,e-=(r<<Xl)+t[0]^r+o^(r>>>5)+t[1],e=e>>>0,o-=ed,o=o>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}function wT(i,t){let e=0,r=new Uint8Array(8).fill(0),o=new Uint8Array(i.slice(0,8)),s=Df(o,t),n=s[0]&7,a=i.length-1-n-Gs-js,u=new Uint8Array(a),m=0,p=r,g=i.slice(0,8);e=8;let E=1;E+=n;for(let C=1;C<=Gs;)if(E<8)E++,C++;else if(E===8){let N=Kl(i,e,p,g,s,t);p=N.ivPreCrypt,g=N.ivCurCrypt,s=N.debiBuf,e=N.bufPos,E=0}let A=a;for(;A>0;)if(E<8)u[m++]=s[E]^p[E],E++,A--;else if(E===8){let C=Kl(i,e,p,g,s,t);p=C.ivPreCrypt,g=C.ivCurCrypt,s=C.debiBuf,e=C.bufPos,E=0}for(let C=1;C<=js;)if(E<8)s[E]^p[E],E++,C++;else if(E===8){if(e>=i.length)break;let N=Kl(i,e,p,g,s,t);if(!N.success)break;p=N.ivPreCrypt,g=N.ivCurCrypt,s=N.debiBuf,e=N.bufPos,E=0}return u}function Kl(i,t,e,r,o,s){if(t+8>i.length)return{success:!1};let n=new Uint8Array(r),a=i.slice(t,t+8),u=new Uint8Array(8);for(let p=0;p<8;p++)u[p]=o[p]^a[p];let m=Df(u,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:m,bufPos:t+8}}var wf=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function Si({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(u=>u.clone().json().then(m=>({data:m}),()=>u.arrayBuffer().then(m=>({data:Nf(new Uint8Array(m))||(wf?wf.decode(m):m)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let u=JSON.parse(a.response);s({data:u})}catch(u){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=r||5e3,a.open(e,i,!0),a.send(t)})}function em(i){return y(this,null,function*(){let t=Ee(),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")),a=yield(yield(yield new Response(o)).blob()).arrayBuffer();return F.debug(`compressJSON ${e.length} -> ${a.byteLength} ${Ee()-t}ms`),a}catch(r){return e}})}var MT=Object.prototype.hasOwnProperty;var io=i=>typeof i=="function",Mf=i=>typeof i=="undefined";var Of=i=>typeof i=="boolean";var tm=i=>i.isRemote;var rm=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 xf(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(rm(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(MT.call(i,t))return!1;return!0}}return!1}var OT=0,xT=1,Pf=2;function PT({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...a){let{retries:u=5,timeout:m=1e3}=t,p=0,g=-1,E=OT,A=(C,N)=>y(this,null,function*(){let D=n||this;try{let x=yield i.apply(D,a);p>0&&s&&s.call(this,p),p=0,C(x)}catch(x){let Z=()=>{clearTimeout(g),p=0,E=Pf,N(x)},ue=()=>{E!==Pf&&p<(io(u)?u():u)?(p++,E=xT,io(r)&&r.call(this,p,Z),g=window.setTimeout(()=>{g=-1,A(C,N)},io(m)?m(p):m)):(Z(),io(o)&&o.call(this,x))};io(e)?e.call(this,{error:x,retry:ue,reject:N,retryFuncArgs:a,retriedCount:p}):ue()}});return new Promise(A)}}var oo=PT;var Zs=class{constructor(t){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=Of(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),F.log(t,e,Mf(this.userId)||xf(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 ln={};hi(ln,{ANDROID_VERSION:()=>ud,CHROME_MAJOR_VERSION:()=>er,CHROME_VERSION:()=>Dd,EDGE_VERSION:()=>hd,EDG_MAJOR_VERSION:()=>om,EDG_VERSION:()=>pd,ELECTRON_MAJOR_VERSION:()=>dm,FIREFOX_MAJOR_VERSION:()=>md,FIREFOX_VERSION:()=>ld,HUAWEI_VERSION:()=>bd,IE_VERSION:()=>FT,IOS_MAIN_VERSION:()=>kt,IOS_VERSION:()=>Tr,IPADQQB_VERSION:()=>yd,IS_ANDROID:()=>it,IS_ANDROID_WEBVIEW:()=>WT,IS_ANY_SAFARI:()=>_r,IS_CHROME:()=>dn,IS_CHROME_OS:()=>sm,IS_CHROMIUM_BASE:()=>dr,IS_DESKTOP_IOS_CHROME:()=>pm,IS_EDG:()=>tn,IS_EDGE:()=>Xo,IS_ELECTRON:()=>BT,IS_FIREFOX:()=>ft,IS_HEADLESS_CHROME:()=>cm,IS_HONOR:()=>am,IS_HUAWEI:()=>Ia,IS_HUAWEIBROWSER:()=>Ta,IS_IE:()=>Vf,IS_IE8:()=>VT,IS_IOS:()=>tt,IS_IOS_13_OR_14:()=>hm,IS_IOS_15_1:()=>mm,IS_IOS_CHROME:()=>la,IS_IPAD:()=>en,IS_IPADQQB:()=>ga,IS_IPAD_PRO:()=>im,IS_IPHONE:()=>so,IS_IPOD:()=>Uf,IS_LINUX:()=>Ea,IS_LOCAL:()=>Ur,IS_MAC:()=>Lr,IS_MACQQB:()=>fa,IS_MIBROWSER:()=>_a,IS_MQQB:()=>nn,IS_NATIVE_ANDROID:()=>UT,IS_OLD_ANDROID:()=>LT,IS_OPENHARMONY:()=>cn,IS_OPPOBROWSER:()=>an,IS_SAFARI:()=>It,IS_SAFARI_15_1:()=>GT,IS_SAMSUNGBROWSER:()=>Sa,IS_SOGOU:()=>ha,IS_SOGOUM:()=>ma,IS_TBS:()=>kr,IS_UCBROWSER:()=>nm,IS_VIVOBROWSER:()=>ya,IS_WECHAT:()=>on,IS_WIN:()=>Qo,IS_WQQB:()=>pa,IS_WX:()=>$T,IS_X5MQQB:()=>sn,IS_XWEB:()=>rn,MACQQB_VERSION:()=>Sd,MI_VERSION:()=>Ad,MQQB_VERSION:()=>Ks,OPENHARMONY_VERSION:()=>HT,OPPO_VERSION:()=>vd,SAFARI_VERSION:()=>yi,SAMSUNG_VERSION:()=>Rd,SOGOUM_VERSION:()=>fd,SOGOU_VERSION:()=>gd,TBS_VERSION:()=>Ed,UA_DATA_STRING:()=>Pr,USER_AGENT:()=>Kt,VIVO_VERSION:()=>Cd,WECHAT_VERSION:()=>Td,WQQB_VERSION:()=>Id,XWEB_VERSION:()=>_d,browserInfo:()=>Kr,getBrowserCoreNumber:()=>gm,getBrowserInfo:()=>Ff,getChromeMajorVersion:()=>Nd,getDeviceModel:()=>Zo,getDeviceModelFromUA:()=>wd,getGPUInfo:()=>fm,getOSName:()=>un,getOSNumber:()=>Ko,getOSString:()=>es,getOSType:()=>_m,getTerminalType:()=>Em,getUserAgentData:()=>Yo,isLocalStorageEnabled:()=>Ai,isMobile:()=>Aa,isVersionLargerThan:()=>lm,isVersionSmallerThan:()=>um});var Kt=typeof navigator=="undefined"?"":navigator.userAgent,ye=i=>new RegExp(i,"i").test(Kt),Et=i=>{if(ye(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Kt.match(t);if(e&&e[1])return e[1]}return""},dd=i=>{if(ye(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Kt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},kf=/AppleWebKit\/([\d.]+)/i.exec(Kt),kT=kf?parseFloat(kf[1]):NaN,en=ye("iPad"),im=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&ye("Macintosh"),so=ye("iPhone")&&!en,Uf=ye("iPod"),tt=so||en||Uf||im,it=ye("Android"),ud=function(){if(it){let i=Kt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),LT=it&&ye("webkit")&&ud<2.3,UT=it&&ud<5&&kT<537,ft=ye("Firefox"),ld=Et("Firefox"),md=dd("Firefox"),Xo=ye("Edge"),hd=Et("Edge"),tn=ye("Edg"),pd=Et("Edg"),om=dd("Edg"),ma=ye("SogouMobileBrowser"),fd=Et("SogouMobileBrowser"),ha=ye("MetaSr\\s"),gd=Et("MetaSr\\s"),kr=ye("TBS"),Ed=Et("TBS"),rn=ye("XWEB"),_d=Et("XWEB"),VT=ye("MSIE\\s8\\.0"),Vf=ye("MSIE\\/\\d+"),FT=function(){if(Vf){let i=/MSIE\s(\d+)\.\d/.exec(Kt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Kt)&&/rv:11.0/.test(Kt)&&(t=11),t}return NaN}(),on=ye("(micromessenger|webbrowser)"),Td=Et("MicroMessenger"),sn=!kr&&ye("MQQBrowser")&&ye("COVC"),nn=!kr&&ye("MQQBrowser")&&!ye("COVC"),Ks=nn||sn?Et("MQQBrowser"):"",pa=!kr&&ye(" QQBrowser"),Id=Et(" QQBrowser"),fa=!kr&&ye("QQBrowserLite"),Sd=Et("QQBrowserLite"),ga=!kr&&ye("MQBHD"),yd=Et("MQBHD"),Qo=ye("Windows"),Lr=!tt&&ye("MAC OS X"),Ea=!it&&ye("Linux"),sm=ye("CrOS"),$T=ye("MicroMessenger"),nm=ye("UCBrowser"),BT=ye("Electron"),_a=ye("MiuiBrowser"),Ad=Et("MiuiBrowser"),Ta=ye("HuaweiBrowser"),Ia=ye("Huawei")||ye("HUAWEI"),am=ye("Honor")||ye("HONOR"),bd=Et("HuaweiBrowser"),Sa=ye("SamsungBrowser"),Rd=Et("SamsungBrowser"),an=ye("HeyTapBrowser"),vd=Et("HeyTapBrowser"),ya=ye("VivoBrowser"),Cd=Et("VivoBrowser"),cn=ye("OpenHarmony"),HT=Et("OpenHarmony"),Nd=()=>dd("Chrome"),la=ye("CriOS"),dr=ye("Chrome"),dn=!Xo&&!ha&&!ma&&!kr&&!rn&&!tn&&!pa&&!_a&&!Ta&&!Sa&&!an&&!ya&&dr,cm=ye("HeadlessChrome"),er=Nd(),Dd=Et("Chrome"),dm=dd("Electron"),It=!dr&&!nn&&!sn&&!fa&&!ga&&ye("Safari"),_r=It||tt,yi=Et("Version"),WT=/Android.*(wv|.0.0.0)/.test(Kt),Tr=(()=>{if(im)return yi;if(tt){let i=Kt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})();function um(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 lm(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,a=o[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var kt=Number(Tr.split(".")[0]),GT=yi==="15.1",mm=Tr==="15.1",hm=(()=>{let i=Number(Tr.split(".")[0]);return i===14||i===13})(),pm=la&&yi==="11.1.1",Ur=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ai=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Kr=Ff();function Ff(){let i=new Map([[ft,["Firefox",ld]],[tn,["Edg",pd]],[dn,["Chrome",Dd]],[la,["ChiOS",Et("CriOS")]],[It&&!la,["Safari",yi]],[kr,["TBS",Ed]],[rn,["XWEB",_d]],[on&&so,["WeChat",Td]],[pa,["QQ(Win)",Id]],[nn,["QQ(Mobile)",Ks]],[sn,["QQ(Mobile X5)",Ks]],[fa,["QQ(Mac)",Sd]],[ga,["QQ(iPad)",yd]],[_a,["MI",Ad]],[Ta,["HW",bd]],[Sa,["Samsung",Rd]],[an,["OPPO",vd]],[ya,["VIVO",Cd]],[Xo,["EDGE",hd]],[ma,["SogouMobile",fd]],[ha,["Sogou",gd]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var qe=null;function Aa(){return qe&&typeof qe.mobile=="boolean"?qe.mobile:it||tt||so||en||cn}var Pr="";function Yo(){return y(this,null,function*(){if(qe)return qe;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return qe=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),qe&&!Pr&&(Pr=`UAData: ${qe.platform}/${qe.platformVersion}`,qe.architecture&&qe.bitness&&(Pr+=` ${qe.architecture}/${qe.bitness}`),qe.mobile&&(Pr+=" mobile"),qe.model&&(Pr+=` model: ${qe.model.replace(/\s+/g,"/")}`),qe.fullVersionList&&(Pr+=` ${qe.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),qe}catch(i){return null}})}function fm(){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 Zo(){return(qe==null?void 0:qe.model)||wd()||""}function wd(){let i=/;\s*([^;)]+)\s+Build\//,t=Kt.match(i);return t!=null&&t[1]?t[1].trim():null}var Lf=new Map([[it,"Android"],[tt,"iOS"],[Qo,"Windows"],[Lr,"MacOS"],[Ea,"Linux"],[sm,"ChromeOS"]]),un=function(){return Lf.get(!0)?Lf.get(!0):qe?qe.platform:"unknown"};function Ko(){return Qo?1:it?2:Lr?3:tt?4:Ea?5:sm?6:cn?7:0}function gm(){return dr?1:It?2:ft?3:0}var es=()=>{let i=un();return qe!=null&&qe.platformVersion?i+=`/${qe.platformVersion}`:tt?i+=`/${Tr}`:it&&(i+=`/${ud}`),i+=`/${Kr.name}/${It&&!la?Kr.version:Kr.version.split(".")[0]}`,qe!=null&&qe.architecture&&(i+=`/${qe.architecture}`),i};function Em(){return it?4:so?2:en?3:Lr?12:Qo?5:Ea?13:cn?22:1}function _m(){return it?"Android":so?"iPhone":en?"iPad":Lr?"Mac":Qo?"Windows":Ea?"Linux":"unknown"}var Bf=pi(bi(),1),zT=new Bf.default,U=zT;var Ir=(j=>(j.ROOM_DESTROY="1",j.JOIN_START="21",j.JOIN_SCHEDULE_SUCCESS="22",j.JOIN_SIGNAL_CONNECTION_START="23",j.JOIN_SIGNAL_CONNECTION_END="24",j.JOIN_SEND_CMD="25",j.JOIN_RECEIVED_CMD_RES="26",j.JOIN_SUCCESS="27",j.JOIN_FAILED="28",j.LEAVE_START="51",j.LEAVE_SEND_CMD="52",j.LEAVE_SUCCESS="53",j.PUBLISH_START="61",j.SEND_FIRST_VIDEO_FRAME="62",j.PUBLISH_FAILED="63",j.SUBSCRIBE_START="81",j.SUBSCRIBE_SUCCESS="82",j.SUBSCRIBE_FAILED="84",j.UNSUBSCRIBE_SUCCESS="83",j.LOCAL_TRACK_CAPTURE_START="101",j.LOCAL_TRACK_CAPTURE_SUCCESS="102",j.LOCAL_TRACK_CAPTURE_FAILED="103",j.LOCAL_TRACK_PUBLISHED="104",j.LOCAL_TRACK_UNPUBLISHED="105",j.LOCAL_TRACK_REPLACED="106",j.SWITCH_DEVICE_SUCCESS="107",j.TRACK_MUTED="108",j.TRACK_UNMUTED="109",j.REMOTE_TRACK_SUBSCRIBED="110",j.REMOTE_TRACK_UNSUBSCRIBED="111",j.LOCAL_TRACK_RECAPTURE="112",j.LOCAL_AUDIO_STARTED="113",j.LOCAL_AUDIO_STOPPED="114",j.REMOTE_AUDIO_STARTED="115",j.REMOTE_AUDIO_STOPPED="116",j.PLAY_TRACK_START="151",j.PLAYER_STATE_CHANGED="152",j.VIDEO_LOADED_DATA="153",j.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",j.AUDIO_CONTEXT_LONG_SUSPENDED="155",j.SIGNAL_CONNECTION_STATE_CHANGED="201",j.PEER_CONNECTION_STATE_CHANGED="202",j.SINGLE_CONNECTION_STAT="203",j.SPC_RECONNECTED="204",j.HEARTBEAT_REPORT="251",j.RECEIVED_PUBLISHED_USER_LIST="252",j.REMOTE_PUBLISH_STATE_CHANGED="253",j.AUDIO_LEVEL_INTERVAL="260",j.NETWORK_QUALITY="261",j.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",j.QUALITY_LIMITATION_CHANGED="263",j.LOG="264",j.AUDIO_PROCESSOR_DEBUG="265",j.SSO_SWITCH="266",j.SWITCH_ROOM_START="401",j.SWITCH_ROOM_SUCCESS="407",j.SWITCH_ROOM_FAILED="408",j))(Ir||{});var $=Ir;var Im=class{constructor(){l(this,"enable",!1);l(this,"ssoFailCount",0);U.on("22",({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.sso&&U.emit("266",{enable:!0})}),U.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&U.emit("266",{enable:!1})}},no=new Im;var JT="%cTRTC%c%s",XT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",QT="display: inline",Od=class Od{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!Fs&&!Zn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){U.on($.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&wr[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),U.on($.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),U.once($.JOIN_FAILED,()=>{this.startUpload()}),U.on($.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(Ne(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:a,logs:u}=o[s],m={timestamp:Gc(),sdkAppId:String(a),userId:n,version:dt,log:u.map(E=>E.log).join(`
|
|
4
|
+
`)},p=JSON.stringify(m),g=no.enable?Ii(m,2002,a):p;yield this.uploadLogWithRetry(g,a,g instanceof Uint8Array,p),u.forEach(E=>E.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e,r,o){return oo({retryFunction:()=>Si({url:Ti(e,to.LOG),body:t,timeout:5e3,priority:"low"}).then(s=>{r&&s.data!=="ok"&&(no.handleUploadFailed(),this.uploadLogWithRetry(o,e,!1,o))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(t){let e=new Date;return e.setTime(fi()),`[${Vs(e)}] <${wr[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){M(wr[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(Ne(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}addLogToQueue(t,e,r=!0,o,s){let n={log:e.reduce((a,u)=>`${a} ${this.logChunkToString(u)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};U.emit($.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n)}log(t,e,r=!0,o,s){var a;if(e.unshift(this.getPrefix(t)),this.addLogToQueue(t,e,r,o,s),t<this._logLevel)return;let n=((a=wr[t])==null?void 0:a.toLowerCase())||"info";Od.PRINT_LOG_TAG?console[n](JT,XT,QT,...e):console[n](...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 Zs(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;wr[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};l(Od,"PRINT_LOG_TAG",!(tt||it||cm));var Sm=Od,F=new Sm;var YT=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)})},Ra=YT;var ym=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Ai())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(Ai())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){F.warn(t)}}getItem(t){if(!Ai())return null;try{let e=localStorage.getItem(this.getRealKey(t));if(!e)return null;let r=JSON.parse(e);return r&&r.expiresIn>=Date.now()?r.value:null}catch(e){F.warn(e)}}setItem(t,e){if(Ai())try{let r={expiresIn:Date.now()+jc,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){F.warn(r)}}deleteItem(t){if(!Ai())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return F.warn(e),!1}}clear(){if(Ai())try{localStorage.clear()}catch(t){F.warn(t)}}},mn=new ym;var uo={};hi(uo,{HTTPS_API:()=>TI,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>qm,IS_GET_CAPABILITIES_SUPPORTED:()=>jm,IS_GET_SETTINGS_SUPPORTED:()=>fn,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>NI,IS_INSERTABLE_STREAM_SUPPORTED:()=>ns,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>MI,IS_RTC_RTP_SENDER_SUPPORTED:()=>ka,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Tg,IS_SEI_SUPPORTED:()=>La,IS_SPC_SUPPORTED:()=>bI,basis:()=>DI,capabilityCheck:()=>Xm,checkSystemRequirementsInternal:()=>qd,decodeSupportStatus:()=>lg,detectVideoCodecCapabilities:()=>Qm,detectVideoDecoderCapabilities:()=>bg,detectVideoEncoderCapabilities:()=>Ag,encodeSupportStatus:()=>Gm,getBrowserInfo:()=>Gd,getDisplayResolution:()=>mg,getH264ProfileLevelIds:()=>OI,isAddTransceiverSupported:()=>Jd,isBrowserSupported:()=>Bm,isCanvasCaptureStreamAPISupported:()=>fg,isCanvasSmallStreamSupported:()=>gg,isGetReceiversSupported:()=>yI,isGetSendersSupported:()=>_g,isGetTransceiversSupported:()=>AI,isGetUserMediaSupported:()=>hg,isMediaDevicesSupported:()=>jd,isMediaSessionSupported:()=>Ig,isMediaStreamTrackGeneratorSupported:()=>hI,isMediaStreamTrackProcessorSupported:()=>Wm,isReplaceTrackSupported:()=>vI,isRequestVideoFrameCallbackSupported:()=>Mi,isSIMDSupported:()=>Jm,isScaleResolutionDownBySupported:()=>Eg,isScreenCaptureApiAvailable:()=>Pa,isSelectedCandidatePair:()=>II,isSetParametersSupported:()=>CI,isSetSinkIdSupported:()=>gI,isSmallStreamSupported:()=>zd,isStopTransceiverSupported:()=>RI,isTRTCSupported:()=>fI,isUnifiedPlanDefault:()=>SI,isUsedInHttpProtocol:()=>wi,isWebAudioSupported:()=>pg,isWebCodecSupported:()=>Xd,isWebCodecsSupported:()=>Hm,isWebRTCSupported:()=>zm,isWebTransportSupported:()=>Sg});var km={};hi(km,{AUDIO_LEVEL_SCALE:()=>Ci,AudioCodecPipelineType:()=>Ma,AudioDecoderDowngradeState:()=>Rm,AudioPlayerMode:()=>Dm,AudioType:()=>Cm,BASIC_TYPE:()=>Ni,BannedReason:()=>wm,CONNECTION_CLOSED_REASON:()=>Wf,CheckPermissionType:()=>Pm,ClientEvent:()=>Am,CodecType:()=>Qf,ConnectionEvent:()=>Hf,ConnectionState:()=>Pd,DECODE_FAILED_ERROR_CODE:()=>xm,DenoiserMode:()=>Om,DeviceType:()=>Vd,FacingMode:()=>kd,FrameWorkType:()=>xd,LeaveReason:()=>Mm,LocalTrackEvent:()=>ao,MULTI_VIDEO_DATA_TYPE:()=>vi,MediaType:()=>bt,MediaTypeLabel:()=>ZT,MonitorEventId:()=>Na,MutedFlag:()=>jf,NetworkQualityValue:()=>Jf,PlayerState:()=>ts,ReceiveMode:()=>Xf,RemoteStreamType:()=>ei,RemoteTrackEvent:()=>rs,RoomEvent:()=>Ri,SMALL_MODE:()=>Ud,SceneNumber:()=>bm,StreamEvent:()=>Gf,StreamType:()=>zf,SubscribeMediaType:()=>va,TIMER_TYPE:()=>co,TRACK_ACTION:()=>qf,TRACK_KIND:()=>vm,TrackEvent:()=>Vr,UserRole:()=>Xt,UserRoleNumber:()=>is,VideoCodec:()=>Ld,VideoCodecPipelineType:()=>wa,VideoContentHint:()=>Oa,VideoDecoderDowngradeState:()=>Ca,VideoPlayerMode:()=>Da,VideoType:()=>Nm});var xd=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(xd||{}),Hf=(N=>(N.TRACK_ADDED="track-added",N.TRACK_UPDATED="track-updated",N.TRACK_SUBSCRIBED="track-subscribed",N.STREAM_ADDED="stream-added",N.STREAM_REMOVED="stream-removed",N.STREAM_UPDATED="stream-updated",N.STREAM_PUBLISHED="stream-published",N.STREAM_SUBSCRIBED="stream-subscribed",N.STREAM_UNSUBSCRIBED="stream-unsubscribed",N.STATE_CHANGED="state-changed",N.ERROR="error",N.CONNECTION_STATE_CHANGED="connection-state-changed",N.FIREWALL_RESTRICTION="firewall-restriction",N.SEI_MESSAGE="sei-message",N.CLOSED="closed",N))(Hf||{}),Wf=(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))(Wf||{}),Am=(D=>(D.STREAM_ADDED="stream-added",D.STREAM_REMOVED="stream-removed",D.STREAM_UPDATED="stream-updated",D.STREAM_SUBSCRIBED="stream-subscribed",D.CONNECTION_STATE_CHANGED="connection-state-changed",D.PEER_JOIN="peer-join",D.PEER_LEAVE="peer-leave",D.MUTE_AUDIO="mute-audio",D.MUTE_VIDEO="mute-video",D.UNMUTE_AUDIO="unmute-audio",D.UNMUTE_VIDEO="unmute-video",D.CLIENT_BANNED="client-banned",D.NETWORK_QUALITY="network-quality",D.AUDIO_VOLUME="audio-volume",D.SEI_MESSAGE="sei-message",D.ERROR="error",D))(Am||{}),Gf=(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))(Gf||{}),ao=(u=>(u.DEVICE_AUTO_RECOVERED="1",u.DEVICE_RECOVER_FAILED="5",u.DEVICE_CHANGED="2",u.ERROR="3",u.PUBLISH_STATE_CHANGED="4",u.ENCODE_FAILED="6",u.TRACK_ENDED="7",u.RENDER="render",u))(ao||{}),ts=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(ts||{}),Ri=(H=>(H.PEER_JOIN="peer-join",H.PEER_LEAVE="peer-leave",H.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",H.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",H.BANNED="banned",H.NETWORK_QUALITY="network-quality",H.AUDIO_VOLUME="audio-volume",H.SEI_MESSAGE="sei-message",H.ERROR="error",H.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",H.REMOTE_PUBLISHED="remote-published",H.REMOTE_UNPUBLISHED="remote-unpublished",H.FIREWALL_RESTRICTION="firewall-restriction",H.HEARTBEAT_REPORT="heartbeat-report",H.CUSTOM_MESSAGE="custom-message",H.LAYER_DATA="layerData",H.FIRST_VIDEO_FRAME="first-video-frame",H.DUMP="dump",H.AUDIO_FRAME="audio-frame",H.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",H.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",H.NTP_TIME_UPDATED="ntp-time-updated",H))(Ri||{}),Vr=(u=>(u.PLAYER_STATE_CHANGED="player-state-changed",u.MUTE="mute",u.UNMUTE="unmute",u.ERROR="error",u.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",u.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",u.FIRST_VIDEO_FRAME="first-video-frame",u.VIDEO_SIZE_CHANGED="video-size-changed",u))(Vr||{}),rs=(o=>(o.DECODE_FAILED="decode-failed",o.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",o.REMOTE_PUBLISH_CHANGED="remote-publish-changed",o.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",o))(rs||{}),jf=(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))(jf||{}),bm=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(bm||{}),is=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(is||{}),Xt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Xt||{}),Pd=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Pd||{}),Rm=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Rm||{}),Ca=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Ca||{}),vm=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(vm||{}),qf=(e=>(e.ADD="add",e.REMOVE="remove",e))(qf||{}),bt=(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))(bt||{}),ZT={1:"audio",2:"auxVideo",4:"video"},Cm=(t=>(t[t.opus=111]="opus",t))(Cm||{}),Nm=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Nm||{}),zf=(e=>(e.Big="big",e.Small="small",e))(zf||{}),ei=(e=>(e.Main="main",e.Aux="auxiliary",e))(ei||{}),vi=(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))(vi||{}),Na=(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))(Na||{}),Jf=(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))(Jf||{}),Xf=(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))(Xf||{}),kd=(e=>(e.user="user",e.environment="environment",e))(kd||{}),Da=(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))(Da||{}),Dm=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Dm||{}),wm=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(wm||{}),Mm=(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))(Mm||{}),Ci=1e8,Om=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Om||{}),va=class{constructor(){l(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)}},Ni=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Ni||{}),Ld=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Ld||{}),wa=(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))(wa||{}),Ma=(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))(Ma||{}),Qf=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(Qf||{}),xm=(E=>(E[E.SUCCESS=0]="SUCCESS",E[E.FAILED=1]="FAILED",E[E.WEBCODEC_INIT=2]="WEBCODEC_INIT",E[E.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",E[E.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",E[E.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",E[E.WASM_INIT=6]="WASM_INIT",E[E.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",E[E.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",E[E.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",E[E.TEST=10]="TEST",E[E.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",E))(xm||{}),Oa=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(Oa||{}),co=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(co||{}),Ud=(e=>(e.CANVAS="canvas",e.API="api",e))(Ud||{}),Pm=(o=>(o[o.NONE=0]="NONE",o[o.MICROPHONE=1]="MICROPHONE",o[o.CAMERA=2]="CAMERA",o[o.BOTH=3]="BOTH",o))(Pm||{}),Vd=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(Vd||{});var Fe={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},tr={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: ${ut(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: ${ut(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 Yf=(i,t)=>t?`${Xr}/${i}/${t}`:`${Xr}/${i}/index.html`;var KT=()=>{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(kl);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function $e(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",a="";je(tr[t])?s=tr[t](e):Ne(tr[t])&&(s=tr[t]);let{TRTC_ERROR_INFO:u,TRTC_ERROR_LINK:m}=KT();r?a=`${r.className}.html#${r.fnName}`:m&&m[t]&&(je(m[t])?a=m[t](e):Ne(m[t])&&(a=m[t]));let p=s;return Or()&&(u&&u[t]&&(je(u[t])?n=u[t](e):Ne(u[t])&&(n=u[t])),n&&(o?p=`${n}
|
|
5
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${Yf("zh-cn",a)}
|
|
8
6
|
|
|
9
|
-
`:
|
|
7
|
+
`:p=`${n}
|
|
10
8
|
|
|
11
|
-
`,
|
|
12
|
-
Refer to: ${
|
|
13
|
-
`),u}var Hl=Ge(ep(),1);var rT=1,oT=0,Ya=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&&(I.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===p.AUDIO?501700:511700,cost:t})}),I.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===p.AUDIO?501700:511700,error:t})}),I.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:fa(this.version||Ve),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(X(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:rT,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=A.UNKNOWN;e&&(X(e)?t=e:(!E(e.extraCode)||!E(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:oT,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},Za=(w=>(w[w.enterRoom=500700]="enterRoom",w[w.exitRoom=500701]="exitRoom",w[w.switchRole=500702]="switchRole",w[w.destroy=500703]="destroy",w[w.startLocalAudio=500704]="startLocalAudio",w[w.updateLocalAudio=500705]="updateLocalAudio",w[w.stopLocalAudio=500706]="stopLocalAudio",w[w.startLocalVideo=500707]="startLocalVideo",w[w.updateLocalVideo=500708]="updateLocalVideo",w[w.stopLocalVideo=500709]="stopLocalVideo",w[w.startScreenShare=500710]="startScreenShare",w[w.updateScreenShare=500711]="updateScreenShare",w[w.stopScreenShare=500712]="stopScreenShare",w[w.startRemoteVideo=500713]="startRemoteVideo",w[w.updateRemoteVideo=500714]="updateRemoteVideo",w[w.stopRemoteVideo=500715]="stopRemoteVideo",w[w.muteRemoteAudio=500716]="muteRemoteAudio",w[w.setRemoteAudioVolume=500717]="setRemoteAudioVolume",w[w.use=500718]="use",w[w.switchRoom=500719]="switchRoom",w[w.sendSEIMessage=5e5]="sendSEIMessage",w[w.sendCustomMessage=500001]="sendCustomMessage",w))(Za||{}),Vl=(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))(Vl||{}),Bl=(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))(Bl||{}),Fl=(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))(Fl||{});var Xo=(R=>(R[R.DECODER_TYPE=514700]="DECODER_TYPE",R[R.DECODER_HW_SW=514701]="DECODER_HW_SW",R[R.DECODE_RESULT=514702]="DECODE_RESULT",R[R.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",R[R.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",R[R.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",R[R.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",R[R.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",R[R.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",R[R.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",R[R.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",R[R.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",R[R.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",R[R.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",R[R.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",R[R.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",R[R.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",R))(Xo||{});var sT=new Ya(!0),qr=new Ya(!1);var v=sT;var K={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}},nT=new Map([[te,["Firefox",Ra]],[Lo,["Edg",ba]],[Go,["Chrome",Fa]],[ke,["Safari",Hi]],[Xt,["TBS",Da]],[Po,["XWEB",Oa]],[Uo&&mr,["WeChat",Ma]],[$s,["QQ(Win)",ka]],[Bo,["QQ(Mobile)",ko]],[Vo,["QQ(Mobile X5)",ko]],[Gs,["QQ(Mac)",wa]],[Ws,["QQ(iPad)",xa]],[qs,["MI",La]],[js,["HW",Pa]],[zs,["Samsung",Ua]],[Fo,["OPPO",Va]],[Qs,["VIVO",Ba]],[Ur,["EDGE",ya]],[Fs,["SogouMobile",va]],[Hs,["Sogou",Na]]]);function aT(){let o=nT.get(!0),i=o?o[0]:"unknown",e=o?o[1]:"unknown";return{browserName:i,browserVersion:e}}var Gl=function(){return!(ll||Ur||Lo&&cl<80||te&&xo<56)},on=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(i=>i in window)},tc=function(){if(!navigator.mediaDevices)return ji()||y.error(Je.NOT_SUPPORTED_MEDIA),!1;let o=["getUserMedia","enumerateDevices"];return o.filter(i=>i in navigator.mediaDevices).length===o.length},tp=!1;function ji(){return location.protocol==="http:"&&!Qt?(tp||y.error(B({key:V.NOT_SUPPORTED_HTTP})),tp=!0,!0):!1}var sn=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},cT=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},Wl=function(){return f(this,null,function*(){var r,s,n;if(K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported)return{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported,isH265EncodeSupported:K.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}}})},ic=function(){return f(this,null,function*(){var t;if(K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return{isH264DecodeSupported:K.detail.isH264DecodeSupported,isVp8DecodeSupported:K.detail.isVp8DecodeSupported,isH265DecodeSupported:K.detail.isH265DecodeSupported};let o,i=!1,e=!1;try{let r=new RTCPeerConnection;pt()?(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}}})};function dT(){return f(this,null,function*(){let[o,i]=yield Promise.all([Wl(),ic()]);return{encode:{h264:o.isH264EncodeSupported,vp8:o.isVp8EncodeSupported,h265:o.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}})}var rc=_a(o=>f(void 0,null,function*(){let i=Date.now(),e=zl(),t=tc(),r=on();if(K.detail.isWebRTCSupported=e,K.detail.isMediaDevicesSupported=t,K.detail.isWebCodecsSupported=r,K.detail.isScreenShareSupported=nn(),K.detail.isSmallStreamSupported=sc(),o===37)return Object.assign(K.detail,yield mT()),K.detail.isBrowserSupported=r,K.result=t&&r,K.result||y.error(`${navigator.userAgent} ${Ps(K.detail,!1)}`),ip(o),v.addNumber({key:523800,value:Date.now()-i}),K;if(K.result&&K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported&&K.detail.isH265EncodeSupported&&K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported&&K.detail.isH265DecodeSupported)return K;let s=Gl(),{encode:n,decode:a}=yield dT(),{h264:c,vp8:l}=n,{h264:u}=a,{h265:h}=n,{vp8:m,h265:g}=a;if(!c||!l){let T=yield Wl();y.warn(`detect encode again h264:${c} vp8:${l} result: ${JSON.stringify(T)}`),c=T.isH264EncodeSupported,l=T.isVp8EncodeSupported}if(c&&u&&me&&Be&&!Po&&!Xt&&!(Fo&&We===115)){let{encode:T,decode:_}=yield hT();c=T,u=_}return K.result=s&&e&&t&&(c||l)&&(u||m),K.detail.isBrowserSupported=s,K.detail.isWebRTCSupported=e,K.detail.isH264EncodeSupported=c,K.detail.isVp8EncodeSupported=l,K.detail.isH265EncodeSupported=h,K.detail.isH264DecodeSupported=u,K.detail.isVp8DecodeSupported=m,K.detail.isH265DecodeSupported=g,K.result||y.error(`${navigator.userAgent} ${Ps(K.detail,!1)}`),ip(),v.addNumber({key:523800,value:Date.now()-i}),K})),lT=function(){return K.result},nn=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},uT=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,Ka=null;function hT(){return f(this,null,function*(){return Ka||(Ka=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=640,t.height=480;let s=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),l.close(),u.close(),c.getTracks().forEach(_=>_.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",_=>u.addIceCandidate(_.candidate)),u.addEventListener("icecandidate",_=>l.addIceCandidate(_.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(),g=Hl.default.parse(m.sdp),T=g.media[0].rtp.findIndex(_=>_.codec==="H264");g.media[0].rtp=[g.media[0].rtp[T]],g.media[0].fmtp=g.media[0].fmtp.filter(_=>_.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(_=>_.payload===g.media[0].rtp[0].payload)),m.sdp=Hl.default.write(g),yield u.setLocalDescription(m),yield l.setRemoteDescription(m),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),o(i));let[_,S]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||_.forEach(R=>{R.type==="outbound-rtp"&&R.mediaType===p.VIDEO&&R.bytesSent>0&&(i.encode=!0)}),i.decode||S.forEach(R=>{R.type==="inbound-rtp"&&R.mediaType===p.VIDEO&&R.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} ${qt}`),o)),Ka)})}var ec=null;function mT(){return f(this,null,function*(){return ec||(ec=new Promise(o=>f(this,null,function*(){let i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!on()){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",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{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((g,T)=>f(this,null,function*(){try{let _=new VideoEncoder({output:R=>{g(R),h.encodeSupported=!0},error:T});_.configure(u.encodeConfig),a();let S=new VideoFrame(e,{timestamp:0});_.encode(S,{keyFrame:!0}),S.close(),yield _.flush(),_.close()}catch(_){T(_)}}))}catch(g){return y.warn(`${u.type} encoder error:`,g),h}try{yield new Promise((g,T)=>f(this,null,function*(){try{let _=new VideoDecoder({output:S=>{h.decodeSupported=!0,g(0),S.close()},error:T});_.configure(u.decodeConfig),_.decode(m),yield _.flush(),_.close()}catch(_){T(_)}}))}catch(g){y.warn(`${u.type} decoder error:`,g)}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)}})),ec)})}var pT=(o,i,e)=>{location.protocol==="http:"&&!Qt&&(o[i]=()=>{throw new N({code:A.INVALID_OPERATION,message:Je.NOT_SUPPORTED_HTTP})})},fr=function(o){return o.type==="candidate-pair"&&o.nominated&&(o.state==="in-progress"||o.state==="succeeded")?!(de(o.selected)&&!o.selected):!1};function sp(){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 np(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ap(){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 cp(){return"captureStream"in HTMLCanvasElement.prototype}function oc(){return Uo||_e||We&&We<63?!1:!!(Gl()&&cp())}function dp(){return!(We<74||Ur||Qe<11||xo<46)}function sc(){return oc()||dp()}var fT=function(){if(E(window.RTCRtpTransceiver)||!pt()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let o=null,i=!1;try{o=new RTCPeerConnection({sdpSemantics:ur}),o.addTransceiver(p.AUDIO),i=!0}catch(e){}return o==null||o.close(),i};function jr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function _r(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function gi(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function pt(){return Qe===11&&!gl?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var zo=!(!pt()||Be&&We<86);function _T(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var an="RTCRtpSender"in window;function Jl(){return an&&"replaceTrack"in window.RTCRtpSender.prototype}function cn(){return an&&"setParameters"in window.RTCRtpSender.prototype&&_r()}var ql="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Ti=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,jl=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Xl=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,ii=an&&"createEncodedStreams"in window.RTCRtpSender.prototype&&$o()>=86,Qo="RTCRtpScriptTransform"in window,dn=an&&(ii||Qo),zl=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function nc(){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 lp(){return"mediaSession"in navigator&&!E(navigator.mediaSession.setActionHandler)}function up(){return!E(window.WebTransport)}function Ql(){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 gT(){let o={browser:`${fi.name}/${fi.version}`,os:Ha(),displayResolution:sp(),isScreenShareSupported:nn(),isWebRTCSupported:zl(),isGetUserMediaSupported:np(),isWebAudioSupported:ap(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:nc(),isMediaSessionSupported:lp(),isWebTransportSupported:up()};return navigator.userAgent.includes("miniProgram")&&(o.browser=`mini/${o.browser}`),o}var hp="checkResult";function ip(o=30){Jo.setItem(hp+o,{ua:navigator.userAgent,checkResult:K})}function Yl(o){ji();let i=Jo.getItem(hp+o);i&&i.ua===navigator.userAgent&&i.checkResult&&TT(i.checkResult.detail,K.detail)&&(K=i.checkResult),rc(o)}function TT(o,i){return Et(o)?Object.keys(i).every(e=>e in o):!1}function Xr(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var ac="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function rp(o){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[o]}var op=!1;function Zl(){return f(this,null,function*(){var o;try{if(op||!((o=navigator==null?void 0:navigator.mediaCapabilities)!=null&&o.encodingInfo))return;let i=Fr(),e=El();if(i===0||e===0)return;op=!0;let t=["H264","VP8","VP9","AV1","H265"],[r,s]=yield Promise.all([mp(t),pp(t)]);r&&Object.keys(r).forEach(n=>{let a=rp(n.toLowerCase());v.addEnum({key:513707,value:+`${a}${+r[n].supported}${+r[n].powerEfficient}${i}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(n=>{let a=rp(n.toLowerCase());v.addEnum({key:514713,value:+`${a}${+s[n].supported}${+s[n].powerEfficient}${i}${e}`,useUV:!1})})}catch(i){y.info("detectVideoCodecCapabilities failed",i)}})}function mp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function pp(o,i=1920,e=1080,t=30,r=3e3){return f(this,null,function*(){let s={};try{for(let n of o){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:i,height:e,bitrate:r,framerate:t}});s[n]=a}}catch(n){}return s})}function ET(){let o={sender:new Set,receiver:new Set,senderHex:new Set,receiverHex:new Set};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1]){let s=r[1];o.senderHex.add(s);let n=parseInt(s,16);isNaN(n)||o.sender.add(n)}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(t=>t.mimeType.toLowerCase()==="video/h264").forEach(t=>{if(t.sdpFmtpLine){let r=t.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(r&&r[1]){let s=r[1];o.receiverHex.add(s);let n=parseInt(s,16);isNaN(n)||o.receiver.add(n)}}})}}catch(i){y.warn("get H264 profile levelId failed",i)}return o}var _p=Ge(tt(),1);var fp=Symbol("instance"),dC=Symbol("abortCtrl"),cc=Symbol("cacheResult"),ln=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,mn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},un=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function ST(o){return typeof o=="object"&&o&&"then"in o}var hn=new Map;function Ie(o,i,e={}){return(t,r,s)=>{let n=e.action||r;if(!e.context){let c=hn.get(t)||[];hn.has(t)||hn.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=W.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[cc]:Promise.resolve(l[cc]);l.state instanceof ln&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(o)?o.length==0?l.state instanceof ln&&l.state.abort(l):(typeof l.state!="string"||!o.includes(l.state))&&(u=new un(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o.join("|")}`)):o!==l.state&&(u=new un(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${o}`));let h=S=>{if(e.fail&&e.fail.call(this,S),e.sync){if(e.ignoreError)return S;throw S}else return e.ignoreError?Promise.resolve(S):Promise.reject(S)};if(u)return h(u);let m=l.state,g=new ln(m,i,n);mn.call(l,g);let T=S=>{var R;return l[cc]=S,g.aborted||(mn.call(l,i),(R=e.success)===null||R===void 0||R.call(this,l[cc])),S},_=S=>(mn.call(l,m,S),h(S));try{let S=a.apply(this,c);return ST(S)?S.then(T).catch(_):e.sync?T(S):Promise.resolve(T(S))}catch(S){return _(new un(l._state,`${l.name} ${n} from ${o} to ${i} failed: ${S}`,S instanceof Error?S:new Error(String(S))))}}}}var IT=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 mn(o,i){let e=this._state;this._state=o;let t=o.toString();o&&this.emit(t,e),this.emit(W.STATECHANGED,o,e,i),this.updateDevTools({value:o,old:e,err:i instanceof Error?i.message:String(i)})}var W=class o extends _p.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[fp];r?this.name=r.name+"-"+r.count++:t[fp]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=hn.get(i)||[],t=new Set,r=[],s=[],n=new Set,a=Object.getPrototypeOf(i);hn.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={}){IT(o.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){mn.call(this,i)}};W.STATECHANGED="stateChanged";W.UPDATEAFSM="updateAFSM";W.INIT="[*]";W.ON="on";W.OFF="off";W.instances=new Map;W.instances2=new WeakMap;var eu=typeof window!="undefined",gp=eu&&window.requestIdleCallback||function(o){let i=Date.now();return setTimeout(()=>{o({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},AT=eu&&window.cancelIdleCallback||function(o){clearTimeout(o)},Tp=eu&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),xe=class xe{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=D({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=D({delay:1e4,count:0},t):i==="raf"?t=D({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=D({delay:2e3,count:0,backgroundTask:!0},t);let r=x(D({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,xe.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){xe.sharedWorker||(xe.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
9
|
+
`,p+=s)),o&&(p+=`
|
|
10
|
+
Refer to: ${Yf("en",a)}
|
|
11
|
+
`),p}var $m=pi(sg(),1);var dI=1,uI=0,$d=class{constructor(t=!0){l(this,"countMap",new Map);l(this,"distributionMap",new Map);l(this,"version");l(this,"log",F.createLogger({id:"kv"}));t&&(U.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===O.AUDIO?501700:511700,cost:r})}),U.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===O.AUDIO?501700:511700,error:r})}),U.on("266",({enable:e})=>{this.log.info(`${e?"enable":"disable"} sso`),e?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,e){let r={msg_sdk_basic_info:{uint32_sdk_version:sd(this.version||dt),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([o,s])=>({uint32_key:o,uint32_count:s})),stats_distribution:[...this.distributionMap.entries()].map(([o,s])=>({uint32_key:o,distribution_items:[...s.entries()].map(([n,a])=>({uint32_item_key:n,uint32_item_value:a}))})),str_user_sig:t,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),r}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 u;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=((u=this.distributionMap)==null?void 0:u.get(t))||new Map,a=0;if(ke(r))a=Math.floor(e/r);else for(let m=r.length-1;m>0;m--)if(e>r[m]){a=m;break}n.set(a,(n.get(a)||0)+1),this.distributionMap.set(t,n)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:dI,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:(!M(e.extraCode)||!M(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:uI,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},Bd=(H=>(H[H.enterRoom=500700]="enterRoom",H[H.exitRoom=500701]="exitRoom",H[H.switchRole=500702]="switchRole",H[H.destroy=500703]="destroy",H[H.startLocalAudio=500704]="startLocalAudio",H[H.updateLocalAudio=500705]="updateLocalAudio",H[H.stopLocalAudio=500706]="stopLocalAudio",H[H.startLocalVideo=500707]="startLocalVideo",H[H.updateLocalVideo=500708]="updateLocalVideo",H[H.stopLocalVideo=500709]="stopLocalVideo",H[H.startScreenShare=500710]="startScreenShare",H[H.updateScreenShare=500711]="updateScreenShare",H[H.stopScreenShare=500712]="stopScreenShare",H[H.startRemoteVideo=500713]="startRemoteVideo",H[H.updateRemoteVideo=500714]="updateRemoteVideo",H[H.stopRemoteVideo=500715]="stopRemoteVideo",H[H.muteRemoteAudio=500716]="muteRemoteAudio",H[H.setRemoteAudioVolume=500717]="setRemoteAudioVolume",H[H.use=500718]="use",H[H.switchRoom=500719]="switchRoom",H[H.sendSEIMessage=5e5]="sendSEIMessage",H[H.sendCustomMessage=500001]="sendCustomMessage",H))(Bd||{}),Um=(E=>(E[E.AudioMixer=550700]="AudioMixer",E[E.AIDenoiser=551700]="AIDenoiser",E[E.VirtualBackground=570700]="VirtualBackground",E[E.Beauty=571700]="Beauty",E[E.Watermark=572700]="Watermark",E[E.BasicBeauty=574700]="BasicBeauty",E[E.CDNStreaming=590700]="CDNStreaming",E[E.DeviceDetector=591700]="DeviceDetector",E[E.Debug=592700]="Debug",E[E.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",E[E.VideoMixer=594700]="VideoMixer",E[E.AudioProcessor=595700]="AudioProcessor",E))(Um||{}),Vm=(E=>(E[E.AudioMixer=550701]="AudioMixer",E[E.AIDenoiser=551701]="AIDenoiser",E[E.VirtualBackground=570701]="VirtualBackground",E[E.Beauty=571701]="Beauty",E[E.Watermark=572701]="Watermark",E[E.BasicBeauty=574701]="BasicBeauty",E[E.CDNStreaming=590701]="CDNStreaming",E[E.DeviceDetector=591701]="DeviceDetector",E[E.Debug=592701]="Debug",E[E.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",E[E.VideoMixer=594701]="VideoMixer",E[E.AudioProcessor=595701]="AudioProcessor",E))(Vm||{}),Fm=(E=>(E[E.AudioMixer=550702]="AudioMixer",E[E.AIDenoiser=551702]="AIDenoiser",E[E.VirtualBackground=570702]="VirtualBackground",E[E.Beauty=571702]="Beauty",E[E.Watermark=572702]="Watermark",E[E.BasicBeauty=574702]="BasicBeauty",E[E.CDNStreaming=590702]="CDNStreaming",E[E.DeviceDetector=591702]="DeviceDetector",E[E.Debug=592702]="Debug",E[E.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",E[E.VideoMixer=594702]="VideoMixer",E[E.AudioProcessor=595702]="AudioProcessor",E))(Fm||{});var pn=(x=>(x[x.DECODER_TYPE=514700]="DECODER_TYPE",x[x.DECODER_HW_SW=514701]="DECODER_HW_SW",x[x.DECODE_RESULT=514702]="DECODE_RESULT",x[x.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",x[x.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",x[x.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",x[x.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",x[x.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",x[x.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",x[x.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",x[x.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",x[x.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",x[x.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",x[x.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",x[x.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",x[x.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",x[x.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",x))(pn||{});var lI=new $d(!0),ss=new $d(!1);var Q=lI;var Re={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}},mI=new Map([[ft,["Firefox",ld]],[tn,["Edg",pd]],[dn,["Chrome",Dd]],[It,["Safari",yi]],[kr,["TBS",Ed]],[rn,["XWEB",_d]],[on&&so,["WeChat",Td]],[pa,["QQ(Win)",Id]],[nn,["QQ(Mobile)",Ks]],[sn,["QQ(Mobile X5)",Ks]],[fa,["QQ(Mac)",Sd]],[ga,["QQ(iPad)",yd]],[_a,["MI",Ad]],[Ta,["HW",bd]],[Sa,["Samsung",Rd]],[an,["OPPO",vd]],[ya,["VIVO",Cd]],[Xo,["EDGE",hd]],[ma,["SogouMobile",fd]],[ha,["Sogou",gd]]]);function Gd(){let i=mI.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Bm=function(){return!(nm||Xo||tn&&om<80||ft&&md<56)},Hm=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},jd=function(){if(!navigator.mediaDevices)return wi()||F.error(tr.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},ng=!1;function wi(){return location.protocol==="http:"&&!Ur?(ng||F.error($e({key:Fe.NOT_SUPPORTED_HTTP})),ng=!0,!0):!1}var Wm=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},hI=function(){return!!(window!=null&&window.MediaStreamTrackGenerator)},Gm=function(){return y(this,null,function*(){var o,s,n;if(Re.detail.isH264EncodeSupported&&Re.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Re.detail.isH264EncodeSupported,isVp8EncodeSupported:Re.detail.isVp8EncodeSupported,isH265EncodeSupported:Re.detail.isH265EncodeSupported};let i,t=!1,e=!1,r=!1;try{let a=new RTCPeerConnection,u=document.createElement(O.CANVAS);u.getContext("2d");let m=u.captureStream(0);return a.addTrack(m.getVideoTracks()[0],m),i=yield a.createOffer(),t=((o=i.sdp)==null?void 0:o.toLowerCase().indexOf("h264"))!==-1,e=((s=i.sdp)==null?void 0:s.toLowerCase().indexOf("vp8"))!==-1,r=((n=i.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,a.close(),{isH264EncodeSupported:t,isVp8EncodeSupported:e,isH265EncodeSupported:r}}catch(a){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},lg=function(){return y(this,null,function*(){var r;if(Re.detail.isH264DecodeSupported&&Re.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Re.detail.isH264DecodeSupported,isVp8DecodeSupported:Re.detail.isVp8DecodeSupported,isH265DecodeSupported:Re.detail.isH265DecodeSupported};let i,t=!1,e=!1;try{let o=new RTCPeerConnection;Jd()?(o.addTransceiver(O.VIDEO,{direction:"recvonly"}),i=yield o.createOffer()):i=yield o.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0);let s=((r=i.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1;return o.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e,isH265DecodeSupported:s}}catch(o){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})};function pI(){return y(this,null,function*(){let[i,t]=yield Promise.all([Gm(),lg()]);return{encode:{h264:i.isH264EncodeSupported,vp8:i.isVp8EncodeSupported,h265:i.isH265EncodeSupported},decode:{h264:t.isH264DecodeSupported,vp8:t.isVp8DecodeSupported,h265:t.isH265DecodeSupported}}})}var qd=nd(i=>y(void 0,null,function*(){let t=Date.now(),e=zm(),r=jd(),o=Hm();if(Re.detail.isWebRTCSupported=e,Re.detail.isMediaDevicesSupported=r,Re.detail.isWebCodecsSupported=o,Re.detail.isScreenShareSupported=Pa(),Re.detail.isSmallStreamSupported=zd(),i===37)return Object.assign(Re.detail,yield _I()),Re.detail.isBrowserSupported=o,Re.result=r&&o,Re.result||F.error(`${navigator.userAgent} ${da(Re.detail,!1)}`),ag(i),Q.addNumber({key:523800,value:Date.now()-t}),Re;if(Re.result&&Re.detail.isH264EncodeSupported&&Re.detail.isVp8EncodeSupported&&Re.detail.isH265EncodeSupported&&Re.detail.isH264DecodeSupported&&Re.detail.isVp8DecodeSupported&&Re.detail.isH265DecodeSupported)return Re;let s=Bm(),{encode:n,decode:a}=yield pI(),{h264:u,vp8:m}=n,{h264:p}=a,{h265:g}=n,{vp8:E,h265:A}=a;if(!u||!m){let C=yield Gm();F.warn(`detect encode again h264:${u} vp8:${m} result: ${JSON.stringify(C)}`),u=C.isH264EncodeSupported,m=C.isVp8EncodeSupported}if(u&&p&&it&&dr&&!rn&&!kr&&!(an&&er===115)){let{encode:C,decode:N}=yield EI();u=C,p=N}return Re.result=s&&e&&r&&(u||m)&&(p||E),Re.detail.isBrowserSupported=s,Re.detail.isWebRTCSupported=e,Re.detail.isH264EncodeSupported=u,Re.detail.isVp8EncodeSupported=m,Re.detail.isH265EncodeSupported=g,Re.detail.isH264DecodeSupported=p,Re.detail.isVp8DecodeSupported=E,Re.detail.isH265DecodeSupported=A,Re.result||F.error(`${navigator.userAgent} ${da(Re.detail,!1)}`),ag(),Q.addNumber({key:523800,value:Date.now()-t}),Re})),fI=function(){return Re.result},Pa=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},gI=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype,Hd=null;function EI(){return y(this,null,function*(){return Hd||(Hd=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=640,r.height=480;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*640),Math.floor(Math.random()*480))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(a),m.close(),p.close(),u.getTracks().forEach(N=>N.stop())},a=setTimeout(()=>{e(),i(t)},2*1e3);let u=r.captureStream(),m=new RTCPeerConnection({}),p=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});m.addEventListener("icecandidate",N=>p.addIceCandidate(N.candidate)),p.addEventListener("icecandidate",N=>m.addIceCandidate(N.candidate)),m.addTrack(u.getVideoTracks()[0],u);let g=yield m.createOffer();yield m.setLocalDescription(g),yield p.setRemoteDescription(g);let E=yield p.createAnswer(),A=$m.default.parse(E.sdp),C=A.media[0].rtp.findIndex(N=>N.codec==="H264");A.media[0].rtp=[A.media[0].rtp[C]],A.media[0].fmtp=A.media[0].fmtp.filter(N=>N.payload===A.media[0].rtp[0].payload),A.media[0].rtcpFb&&(A.media[0].rtcpFb=A.media[0].rtcpFb.filter(N=>N.payload===A.media[0].rtp[0].payload)),E.sdp=$m.default.write(A),yield p.setLocalDescription(E),yield m.setRemoteDescription(E),n=setInterval(()=>y(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let[N,D]=yield Promise.all([m.getSenders()[0].getStats(),p.getReceivers()[0].getStats()]);t.encode||N.forEach(x=>{x.type==="outbound-rtp"&&x.mediaType===O.VIDEO&&x.bytesSent>0&&(t.encode=!0)}),t.decode||D.forEach(x=>{x.type==="inbound-rtp"&&x.mediaType===O.VIDEO&&x.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),F.warn("detectH264Supported failed",r),i({encode:!0,decode:!0})}})).then(i=>(i.encode||(i.decode=!0),(!i.encode||!i.decode)&&F.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${Pr}`),i)),Hd)})}var Wd=null;function _I(){return y(this,null,function*(){return Wd||(Wd=new Promise(i=>y(this,null,function*(){let t={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!Hm()){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,a=()=>{!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 u=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(u.map(p=>y(this,null,function*(){let g={type:p.type,encodeSupported:!1,decodeSupported:!1},E;try{E=yield new Promise((A,C)=>y(this,null,function*(){try{let N=new VideoEncoder({output:x=>{A(x),g.encodeSupported=!0},error:C});N.configure(p.encodeConfig),a();let D=new VideoFrame(e,{timestamp:0});N.encode(D,{keyFrame:!0}),D.close(),yield N.flush(),N.close()}catch(N){C(N)}}))}catch(A){return F.warn(`${p.type} encoder error:`,A),g}try{yield new Promise((A,C)=>y(this,null,function*(){try{let N=new VideoDecoder({output:D=>{g.decodeSupported=!0,A(0),D.close()},error:C});N.configure(p.decodeConfig),N.decode(E),yield N.flush(),N.close()}catch(N){C(N)}}))}catch(A){F.warn(`${p.type} decoder error:`,A)}return g})))).forEach(p=>{p.type==="h264"?(t.isH264EncodeSupported=p.encodeSupported,t.isH264DecodeSupported=p.decodeSupported):p.type==="vp8"&&(t.isVp8EncodeSupported=p.encodeSupported,t.isVp8DecodeSupported=p.decodeSupported)}),s(),i(t)}catch(n){s(),F.warn("detectWebCodecsSupported failed:",n),i(t)}})),Wd)})}var TI=(i,t,e)=>{location.protocol==="http:"&&!Ur&&(i[t]=()=>{throw new de({code:q.INVALID_OPERATION,message:tr.NOT_SUPPORTED_HTTP})})},II=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(Qe(i.selected)&&!i.selected):!1};function mg(){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 hg(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function pg(){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 fg(){return"captureStream"in HTMLCanvasElement.prototype}function gg(){return on||tt||er&&er<63?!1:!!(Bm()&&fg())}function Eg(){return!(er<74||Xo||kt<11||md<46)}function zd(){return gg()||Eg()}var SI=function(){if(M(window.RTCRtpTransceiver)||!Jd()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:Fl}),i.addTransceiver(O.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function yI(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function _g(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function AI(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function Jd(){return kt===11&&!pm?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var bI=!(!Jd()||dr&&er<86);function RI(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ka="RTCRtpSender"in window;function vI(){return ka&&"replaceTrack"in window.RTCRtpSender.prototype}function CI(){return ka&&"setParameters"in window.RTCRtpSender.prototype&&_g()}var NI="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,fn=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,jm=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,qm=typeof InputDeviceInfo!="undefined"&&"getCapabilities"in InputDeviceInfo.prototype,ns=ka&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Nd()>=86,Tg="RTCRtpScriptTransform"in window,La=ka&&(ns||Tg),zm=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Xd(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return M(window.AudioDecoder)||(i.AudioDecoder=!0),M(window.AudioEncoder)||(i.AudioEncoder=!0),M(window.VideoDecoder)||(i.VideoDecoder=!0),M(window.VideoEncoder)||(i.VideoEncoder=!0),M(window.ImageDecoder)||(i.ImageDecoder=!0),i}function Ig(){return"mediaSession"in navigator&&!M(navigator.mediaSession.setActionHandler)}function Sg(){return!M(window.WebTransport)}function Jm(){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 DI(){let i={browser:`${Kr.name}/${Kr.version}`,os:un(),displayResolution:mg(),isScreenShareSupported:Pa(),isWebRTCSupported:zm(),isGetUserMediaSupported:hg(),isWebAudioSupported:pg(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Xd(),isMediaSessionSupported:Ig(),isWebTransportSupported:Sg()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var yg="checkResult";function ag(i=30){mn.setItem(yg+i,{ua:navigator.userAgent,checkResult:Re})}function Xm(i){wi();let t=mn.getItem(yg+i);t&&t.ua===navigator.userAgent&&t.checkResult&&wI(t.checkResult.detail,Re.detail)&&(Re=t.checkResult),qd(i)}function wI(i,t){return ar(i)?Object.keys(t).every(e=>e in i):!1}function Mi(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var MI="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function cg(i){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[i]}var dg=!1;function Qm(){return y(this,null,function*(){var i;try{if(dg||!((i=navigator==null?void 0:navigator.mediaCapabilities)!=null&&i.encodingInfo))return;let t=Ko(),e=gm();if(t===0||e===0)return;dg=!0;let r=["H264","VP8","VP9","AV1","H265"],[o,s]=yield Promise.all([Ag(r),bg(r)]);o&&Object.keys(o).forEach(n=>{let a=cg(n.toLowerCase());Q.addEnum({key:513707,value:+`${a}${+o[n].supported}${+o[n].powerEfficient}${t}${e}`,useUV:!1})}),s&&Object.keys(s).forEach(n=>{let a=cg(n.toLowerCase());Q.addEnum({key:514713,value:+`${a}${+s[n].supported}${+s[n].powerEfficient}${t}${e}`,useUV:!1})})}catch(t){F.info("detectVideoCodecCapabilities failed",t)}})}function Ag(i,t=1920,e=1080,r=30,o=3e3){return y(this,null,function*(){let s={};try{for(let n of i){let a=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:t,height:e,bitrate:o,framerate:r}});s[n]=a}}catch(n){}return s})}function bg(i,t=1920,e=1080,r=30,o=3e3){return y(this,null,function*(){let s={};try{for(let n of i){let a=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${n}`,width:t,height:e,bitrate:o,framerate:r}});s[n]=a}}catch(n){}return s})}function OI(){let i={sender:new Set,receiver:new Set,senderHex:new Set,receiverHex:new Set};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){let o=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(o&&o[1]){let s=o[1];i.senderHex.add(s);let n=parseInt(s,16);isNaN(n)||i.sender.add(n)}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){let o=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(o&&o[1]){let s=o[1];i.receiverHex.add(s);let n=parseInt(s,16);isNaN(n)||i.receiver.add(n)}}})}}catch(t){F.warn("get H264 profile levelId failed",t)}return i}var vg=pi(bi(),1);var Rg=Symbol("instance"),$R=Symbol("abortCtrl"),Qd=Symbol("cacheResult"),Ua=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,$a.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Va=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function xI(i){return typeof i=="object"&&i&&"then"in i}var Fa=new Map;function Ze(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let u=Fa.get(r)||[];Fa.has(r)||Fa.set(r,u),u.push({from:i,to:t,action:n})}let a=s.value;s.value=function(...u){let m=this;if(e.context&&(m=le.get(typeof e.context=="function"?e.context.call(this,...u):e.context)),m.state===t)return e.sync?m[Qd]:Promise.resolve(m[Qd]);m.state instanceof Ua&&m.state.action==e.abortAction&&m.state.abort(m);let p=null;Array.isArray(i)?i.length==0?m.state instanceof Ua&&m.state.abort(m):(typeof m.state!="string"||!i.includes(m.state))&&(p=new Va(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(p=new Va(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let g=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}else return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(p)return g(p);let E=m.state,A=new Ua(E,t,n);$a.call(m,A);let C=D=>{var x;return m[Qd]=D,A.aborted||($a.call(m,t),(x=e.success)===null||x===void 0||x.call(this,m[Qd])),D},N=D=>($a.call(m,E,D),g(D));try{let D=a.apply(this,u);return xI(D)?D.then(C).catch(N):e.sync?C(D):Promise.resolve(C(D))}catch(D){return N(new Va(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${D}`,D instanceof Error?D:new Error(String(D))))}}}}var PI=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 $a(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(le.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var le=class i extends vg.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[Rg];o?this.name=o.name+"-"+o.count++:r[Rg]={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,a=Object.getPrototypeOf(t);Fa.has(a)&&(a.stateDiagram.forEach(m=>r.add(m)),a.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:p,action:g})=>{typeof m=="string"?o.push({from:m,to:p,action:g}):m.length?m.forEach(E=>{o.push({from:E,to:p,action:g})}):s.push({to:p,action:g})}),o.forEach(({from:m,to:p,action:g})=>{n.add(m),n.add(p),n.add(g+"ing"),r.add(`${m} --> ${g}ing : ${g}`),r.add(`${g}ing --> ${p} : ${g} \u{1F7E2}`),r.add(`${g}ing --> ${m} : ${g} \u{1F534}`)}),s.forEach(({to:m,action:p})=>{r.add(`${p}ing --> ${m} : ${p} \u{1F7E2}`),n.forEach(g=>{g!==m&&r.add(`${g} --> ${p}ing : ${p}`)})});let u=[...r];return Object.defineProperties(t,{stateDiagram:{value:u},allStates:{value:n}}),u}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={}){PI(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){$a.call(this,t)}};le.STATECHANGED="stateChanged";le.UPDATEAFSM="updateAFSM";le.INIT="[*]";le.ON="on";le.OFF="off";le.instances=new Map;le.instances2=new WeakMap;var Zm=typeof window!="undefined",Cg=Zm&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},kI=Zm&&window.cancelIdleCallback||function(i){clearTimeout(i)},Ng=Zm&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),St=class St{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=ge(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,St.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){St.sharedWorker||(St.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
14
12
|
const timers = new Map();
|
|
15
13
|
self.onmessage = function(e) {
|
|
16
14
|
const { taskId, delay, type } = e.data;
|
|
@@ -23,15 +21,15 @@ Refer to: ${qm("en",a)}
|
|
|
23
21
|
timers.delete(taskId);
|
|
24
22
|
}
|
|
25
23
|
};
|
|
26
|
-
`],{type:"application/javascript"}))),
|
|
27
|
-
${t.stack}`));let s=pr.enable?Vi(r,2002,Number(this._configs.sdkAppId)):JSON.stringify(r);this.sendRequest(Ui(this._configs.sdkAppId,ar.LOG),s)}sendRequest(i,e){setTimeout(()=>Bi({url:i,body:e,priority:"low"}).catch(()=>{}),2e3)}},re=new tu;var Si=new WeakMap;function yt({settings:o={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,s,n){let a=pi({retryFunction:n.value,settings:o,onError({error:c,retry:l,reject:u,retryFuncArgs:h}){var m;i?i.call(this,c,()=>{var g;(g=Si.get(r))!=null&&g.has(s)?l():u(c)},u,h):(m=Si.get(r))!=null&&m.has(s)?l():u(c)},onRetrying(c,l){var u;mi(e)&&e.call(this,c,l),(u=Si.get(r))!=null&&u.has(s)&&(Si.get(r).get(s).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Si.get(r);return l?l.set(s,{args:c}):Si.set(r,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Si.get(r))==null?void 0:u.delete(s)})},n}}function fn({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=Si.get(t))!=null&&c.has(o)){let{stopRetry:u,args:h}=Si.get(t).get(o),m=!0;if(e){for(let g of h)if(!a.find(T=>T===g)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(l=Si.get(t))==null||l.delete(o))}return n.apply(this,a)},s}}var oi=class extends W{constructor(e,t){super(e.id,`${t}-player`);this.options=e;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,"_isPausedByUserCall",!1);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=Or,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=B({key:V.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new N({code:A.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){var t;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ot?this._delayDestroyTimeoutId||((t=this.element)==null||t.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(p.ENDED),this._interval>0&&ie.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),(e=this.element)==null||e.pause(),this._isPausedByUserCall=!0,this instanceof Ye&&Be&&We>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():fl?this.replay():(this.element&&this.track&&Be&&We>=128&&(this.element.srcObject=new MediaStream([this.track])),this.play().catch(()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return Fe(this.element,this.element).add(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);ri==null||ri.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(){I.on(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Ne(e)}unbindEvents(){this.element&&Ne(this.element),this.unbindTrackEvents(),I.off(C.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case p.PLAYING:_n()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(p.PLAYING),this._interval&&(ie.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),_e&&(this._interval=ie.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{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}`),re.uploadEvent({log:`stat-${this.kind}-${ze.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),ul||Xs?this.emit(ae.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case p.LOADEDDATA:this.kind===p.VIDEO&&this.emit(ae.LOADED_DATA);break;case p.LOADEDMETADATA:this.kind===p.VIDEO&&this.emit(ae.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),v.addSuccessEvent({key:this.kind===p.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),re.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),v.addFailedEvent({key:this.kind===p.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(ae.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{St(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)}),St(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.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(p.UNMUTE));break}})}handlePlaying(e){var t;return this._log.debug("handlePlaying",e),(t=this._playSuccessResolve)==null||t.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};d(oi,"PlayerEvent",ae),O([yt({settings:{retries:2,timeout:0},onError(e,t,r,s){s[0]=(s[0]||1e3)+1e3,t()}})],oi.prototype,"doReplayByRecreateMediaStream",1),O([Ie([],"PLAYING",{sync:!0,success(e){this.emit(ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],oi.prototype,"handlePlaying",1),O([Ie("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],oi.prototype,"handlePaused",1),O([Ie([],"STOPPED",{sync:!0,success(e){this.emit(ae.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],oi.prototype,"handleStopped",1);var Xi="trtc_autoplay",iu=`${Xi}_mask`,gn=`${Xi}_wrapper`,Ep=`${Xi}_header`,ru=`${Xi}_content`,dc=`${Xi}_action_wrapper`,ou=`${Xi}_question`,su=`${Xi}_collapse`,lc=`${Xi}_action_confirm`,Sp=`${Xi}_detail`,Ip="#2473E8",cu="dialog",RT=`${cu}-show`,yT=`${cu}-1`,bT=`${cu}-2`,Ap=!1,nu=!1,_n=()=>nu,Rp=`${li}/${$t()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Cp=`<br><a href='${Rp}' target='_blank'>${$t()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,vT=`${$t()?`\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${Cp}`:`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. ${Cp}`}`,au=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($t()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ap){let i=document.createElement("style");i.innerHTML=`.${iu}{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;}.${iu} div:not(.${dc}){display:block !important;}.${gn}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${gn} a{color:${Ip};}.${Ep}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${ru}{margin:8px 0;}.${dc}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${su}{margin-right:auto;cursor:pointer}.${ou}{height:100%;line-height:16px;cursor:pointer;}.${lc}{margin-left:8px;color:#fff;background:${Ip};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${lc}:hover{opacity:0.9;}.${su},.${lc},.${ru},.${ou}{font-size:14px;}@media screen and (max-width:750px){.${gn}{width:80vw;}}`,document.head.appendChild(i),Ap=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${iu}"><div class='${gn}'><div class='${Ep}'>${location.host}</div><div class='${ru}'>${this.content}</div><div class='${Sp}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${vT}</div><div class='${dc}'></div></div></div>`.trim();let e=document.createElement("button");e.className=lc,e.innerText=$t()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=ou,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
24
|
+
`],{type:"application/javascript"}))),St.sharedWorker.onmessage=e=>{var r;if(e.data.type==="tick"){let o=St.workerTasks.get(e.data.taskId);o&&(St.isBreakLoop(o)?((r=St.sharedWorker)==null||r.postMessage({type:"stop",taskId:o.taskID}),St.workerTasks.delete(o.taskID)):(o.callback(),o.loopCount+=1))}}),St.workerTasks.set(t.taskID,t),St.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!St.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=Ee(),r,o=()=>{if(r=Ee()-e,r>=t.delay&&(e=Ee()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!St.isBreakLoop(t))return t.ricID=Cg(o,{timeout:t.delay})};return t.ricID=Cg(o,{timeout:t.delay})}static raf(t){let e=Ee(),r,o=()=>{if(document.hidden&&t.backgroundTask)return r=Ee()-e,e=Ee(),t.callback(),t.loopCount+=1,St.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay));if(r=Ee()-e,r>=t.delay&&(e=Ee()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!St.isBreakLoop(t))return t.rafID=requestAnimationFrame(o)};if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let s=()=>{if(document.hidden){let n=Ee()-e;n>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-n)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:o,ricID:s,onVisibilitychange:n}=this.taskMap.get(t);return e&&clearInterval(e),r&&clearTimeout(r),o&&Ng&&Ng(o),s&&kI(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.hasTask(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};l(St,"taskMap",new Map),l(St,"currentTaskID",1),l(St,"sharedWorker",null),l(St,"workerTasks",new Map);var Ym=St,lt=Ym;var QR={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:O.SEI_MESSAGE,ERROR:"error"};var He={LOADED_DATA:O.LOADEDDATA,LOADED_META_DATA:O.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",RESIZE:O.RESIZE,TIME_UPDATE:"time-update"};var Fr={};hi(Fr,{create:()=>Rt,remove:()=>mt});var Ba=new WeakMap;function Rt(i,t){Ba.has(i)||Ba.set(i,[]);let e=Ba.get(i),o={add:(s,n)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,n)),t.addEventListener(s,n)):(e.push(t.off.bind(t,s,n)),t.on(s,n)),o)};return o}function mt(i){let t=Ba.get(i);t&&(t.forEach(e=>e()),Ba.delete(i))}var Km=class{constructor(){l(this,"_roomIdMap",new Map);l(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:dt,env:gi.QCLOUD,browserVersion:Kr.name+Kr.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:o}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(t){Ur||!F.isAbleToUpload||this._configs.env===gi.QCLOUD&&this.uploadEventToKibana(ge(X({},t),{result:"success"}))}logFailedEvent(t){if(Ur||!F.isAbleToUpload)return;let{eventType:e,code:r,error:o,userId:s}=t,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(o==null?void 0:o.extraCode)||(o==null?void 0:o.code)||q.UNKNOWN};this._configs.env===gi.QCLOUD&&this.uploadEventToKibana(ge(X({},n),{error:o}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let o={timestamp:Gc(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:dt,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+=`
|
|
25
|
+
${r.stack}`));let s=no.enable?Ii(o,2002,Number(this._configs.sdkAppId)):JSON.stringify(o);this.sendRequest(Ti(this._configs.sdkAppId,to.LOG),s)}sendRequest(t,e){setTimeout(()=>Si({url:t,body:e,priority:"low"}).catch(()=>{}),2e3)}},We=new Km;var as=new WeakMap;function cs({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let a=oo({retryFunction:n.value,settings:i,onError({error:u,retry:m,reject:p,retryFuncArgs:g}){var E;t?t.call(this,u,()=>{var A;(A=as.get(o))!=null&&A.has(s)?m():p(u)},p,g):(E=as.get(o))!=null&&E.has(s)?m():p(u)},onRetrying(u,m){var p;io(e)&&e.call(this,u,m),(p=as.get(o))!=null&&p.has(s)&&(as.get(o).get(s).stopRetry=m)},onRetryFailed:r});return n.value=function(...u){let m=as.get(o);return m?m.set(s,{args:u}):as.set(o,new Map([[s,{args:u}]])),a.apply(this,u).finally(()=>{var p;return(p=as.get(o))==null?void 0:p.delete(s)})},n}}var $r=class extends le{constructor(e,r){super(e.id,`${r}-player`);this.options=e;this.kind=r;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"mode");l(this,"muted");l(this,"_log");l(this,"_isPausedByUserCall",!1);l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_playSuccessResolve");l(this,"_isReplayByRecreateMediaStreamCalled",!1);l(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Bo,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=$e({key:Fe.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new de({code:q.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){var r;this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!_r?this._delayDestroyTimeoutId||((r=this.element)==null||r.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(O.ENDED),this._interval>0&<.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this._log.info("pause"),(e=this.element)==null||e.pause(),this._isPausedByUserCall=!0,this instanceof Lt&&dr&&er>=128&&this.setPoster(this.getVideoFrame())}resume(){return this._isPausedByUserCall=!1,this.doResume()}doResume(){return this._log.info("resume"),this._isPausedByUserCall||this.isPlaying?Promise.resolve():mm?this.replay():(this.element&&this.track&&dr&&er>=128&&(this.element.srcObject=new MediaStream([this.track])),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 Rt(this.element,this.element).add(O.PLAYING,e).add(O.ENDED,e).add(O.PAUSE,e).add(O.ERROR,e).add(O.LOADEDDATA,e).add(O.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Fr==null||Fr.create(e,e).add(O.ENDED,r).add(O.MUTE,r).add(O.UNMUTE,r),e.readyState===O.ENDED&&this.handleTrackEvent({type:O.ENDED}),e.muted&&this.handleTrackEvent({type:O.MUTE})}}bindAutoPlayEvent(){U.on($.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&mt(e)}unbindEvents(){this.element&&mt(this.element),this.unbindTrackEvents(),U.off($.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case O.PLAYING:Ha()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(O.PLAYING),this._interval&&(lt.clearTask(this._interval),this._interval=-1);break;case O.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(O.ENDED);break;case O.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(O.PAUSE),tt&&(this._interval=lt.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.doResume()},{delay:3e3}));break;case O.ERROR:if(this.element&&this.element.error){this.handlePaused(O.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}`),We.uploadEvent({log:`stat-${this.kind}-${gr.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),am||Ia?this.emit(He.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case O.LOADEDDATA:this.kind===O.VIDEO&&this.emit(He.LOADED_DATA);break;case O.LOADEDMETADATA:this.kind===O.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"),We.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Q.addSuccessEvent({key:this.kind===O.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),We.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Q.addFailedEvent({key:this.kind===O.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(He.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{zo(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var 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`),o((a=this.element)==null?void 0:a.error)}),zo(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 O.ENDED:this.handleStopped(O.ENDED);break;case O.MUTE:this.handlePaused(O.MUTE);break;case O.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.doResume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(O.UNMUTE));break}})}handlePlaying(e){var r;return this._log.debug("handlePlaying",e),(r=this._playSuccessResolve)==null||r.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};l($r,"PlayerEvent",He),te([cs({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],$r.prototype,"doReplayByRecreateMediaStream",1),te([Ze([],"PLAYING",{sync:!0,success(e){this.emit(He.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],$r.prototype,"handlePlaying",1),te([Ze("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(He.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],$r.prototype,"handlePaused",1),te([Ze([],"STOPPED",{sync:!0,success(e){this.emit(He.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],$r.prototype,"handleStopped",1);var Oi="trtc_autoplay",eh=`${Oi}_mask`,Wa=`${Oi}_wrapper`,Dg=`${Oi}_header`,th=`${Oi}_content`,Yd=`${Oi}_action_wrapper`,rh=`${Oi}_question`,ih=`${Oi}_collapse`,Zd=`${Oi}_action_confirm`,wg=`${Oi}_detail`,Mg="#2473E8",nh="dialog",UI=`${nh}-show`,VI=`${nh}-1`,FI=`${nh}-2`,Og=!1,oh=!1,Ha=()=>oh,Pg=`${Xr}/${Or()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,xg=`<br><a href='${Pg}' target='_blank'>${Or()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,$I=`${Or()?`\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${xg}`:`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. ${xg}`}`,sh=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(Or()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Og){let t=document.createElement("style");t.innerHTML=`.${eh}{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;}.${eh} div:not(.${Yd}){display:block !important;}.${Wa}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Wa} a{color:${Mg};}.${Dg}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${th}{margin:8px 0;}.${Yd}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${ih}{margin-right:auto;cursor:pointer}.${rh}{height:100%;line-height:16px;cursor:pointer;}.${Zd}{margin-left:8px;color:#fff;background:${Mg};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Zd}:hover{opacity:0.9;}.${ih},.${Zd},.${th},.${rh}{font-size:14px;}@media screen and (max-width:750px){.${Wa}{width:80vw;}}`,document.head.appendChild(t),Og=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${eh}"><div class='${Wa}'><div class='${Dg}'>${location.host}</div><div class='${th}'>${this.content}</div><div class='${wg}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${$I}</div><div class='${Yd}'></div></div></div>`.trim();let e=document.createElement("button");e.className=Zd,e.innerText=Or()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=rh,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
26
|
<svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
|
|
29
27
|
<path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
|
|
30
28
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
31
29
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
32
30
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=su,r.innerText=`${$t()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${dc}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){_n()||(nu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${gn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",y.info("show autoplay dialog"),re.uploadEvent({log:RT}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,nu=!1)}onConfirm(){y.warn("confirm clicked, try resume stream"),I.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Sp}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||re.uploadEvent({log:yT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Rp,"_blank"),this._isQuestionClicked||re.uploadEvent({log:bT}),this._isQuestionClicked=!0}},Yo=au;var Ye=class extends oi{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");d(this,"_preSize",{width:0,height:0});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,me&&(e.poster="noposter"),(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).add(p.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===p.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l,u,h;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=Or,this._log.info(`view container ${(s=this.container)==null?void 0:s.id} is recreated`)),this._pausedRetryCount>0&&!_n()&&!this._isPausedByUserCall&&(this._log.info(`[${Or-this._pausedRetryCount+1}/${Or}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let m=this.element.style.transform;t===p.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=m.replace("scaleX(-1)",""):t===p.LEAVE_PICTURE_IN_PICTURE&&!m.includes("scaleX")&&(this.element.style.transform=`${m} scaleX(-1)`)}t===p.RESIZE&&(this._preSize.height!==((n=this.element)==null?void 0:n.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info(`video size changed to ${(c=this.element)==null?void 0:c.videoWidth}x${(l=this.element)==null?void 0:l.videoHeight}`),this._preSize.height=((u=this.element)==null?void 0:u.videoHeight)||0,this._preSize.width=((h=this.element)==null?void 0:h.videoWidth)||0,this.emit(ae.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}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(ae.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(Xr()&&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 zi(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 Tn;typeof AudioContext!="undefined"?Tn=AudioContext:typeof webkitAudioContext!="undefined"?Tn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Tn=mozAudioContext);var hu=1500,Ze,yp=-1,uc=0,En=-1,uu=!1,bp=0,vp=-1,Np=-1;Dp();function Dp(){try{if(Ze)return;Ze=new Tn({sampleRate:48e3}),Ze.onstatechange=()=>{y.info(`context state: ${Ze.state}${Ze.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Zo()},clearTimeout(yp)}catch(o){y.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Tn}`),yp=setTimeout(Dp,1e3)}}var Zo=()=>{Ze.state==="suspended"?(uc=P(),NT(),gr(),document.addEventListener("click",Zo)):Ze.state==="interrupted"?gr():(uc&&(v.addNumber({key:507800,value:P()-uc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),uc=0),DT(),document.removeEventListener("visibilitychange",Zo),document.removeEventListener("click",Zo))},du=0,lu=-1;function gr(){return new Promise((o,i)=>{if(Ze.state==="running")return o();Date.now()-du<1e3?(clearTimeout(lu),lu=setTimeout(()=>{du=Date.now(),Ze.resume().then(o,i)},1e3)):(clearTimeout(lu),du=Date.now(),Ze.resume().then(o,i))}).catch(o=>{y.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",Zo)})}document.addEventListener("click",Zo);function NT(){En===-1&&(En=setTimeout(()=>{Ze.state==="suspended"&&(uu=!0,I.emit("155",{isSuspended:!0}))},hu))}function DT(){En!==-1&&(clearTimeout(En),En=-1,uu&&(uu=!1,I.emit("155",{isSuspended:!1})))}function Op(){if(!_e||Np!==-1)return;let o=()=>{P()-bp<500||(Ze&&Ze.state==="running"&&Ze.currentTime===vp&&(y.warn("context is fake running, auto resume"),Ze.suspend().catch(i=>{y.warn(`context suspend failed: ${i}`)})),vp=Ze.currentTime,bp=P())};Np=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var pe=o=>Ze;var Me=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(),v.addSuccessEvent({key:502701})}catch(r){y.error(r),v.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(),v.addSuccessEvent({key:502702})}catch(e){y.error(e),v.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}},hc=class extends Me{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}},Sn=class{constructor(){d(this,"source",new Me);d(this,"gain",new Me);d(this,"destination",new Me)}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(pe().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=In(i);e&&this.source.replaceNode(e)}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}},Ko=class extends Sn{constructor(e){super();this.context=e;d(this,"aec",new Me("aec"));d(this,"mixNode",new Me("mixNode"));d(this,"silentNode",new Me("silentNode"));d(this,"denoiser",new Me("denoiser"));d(this,"voiceChanger",new Me("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)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}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}},mc=class{constructor(){d(this,"audioContext",pe("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]}},Mp=new WeakMap;function In(o){try{let i=Mp.get(o);if(i)return i;let e=pe();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return Mp.set(o,i),i}catch(i){if(te&&i instanceof Error&&i.name==="NotSupportedError")y.warn(i);else throw i}}var bt=class bt{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,I.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-bt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!bt.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);';bt.workletReady=zi(bt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return bt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(bt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{bt.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}`),re.logFailedEvent({userId:this._log.userId,eventType:ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=pe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{bt.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,I.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(bt,"lastMessageTime",0),d(bt,"audioContext",pe("volume-meter")),d(bt,"workletReady");var pc=bt,An=class extends Me{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new pc(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()}}},zr=pc;var Lp=Ge(tt(),1);var wp=o=>i=>i.deviceId===o;var Cn=class{constructor(i,e){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&&ts(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(wp(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(wp(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)}},mu=class extends Lp.EventEmitter{constructor(){super();d(this,"audioInputs",new Cn(p.AUDIO,"Input"));d(this,"videoInputs",new Cn(p.VIDEO,"Input"));d(this,"audioOutputs",new Cn(p.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||ie.run("interval",()=>{this.update()},{delay:1e4}))}init(){es().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 es(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=pe())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},Ae=vs||go?null:new mu;function ts(o){return o.deviceId===o.groupId&&o.groupId===""}function es(){return f(this,arguments,function*(o=0){if(ji()||!tc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ts(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&&gr()}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&&pu.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function ft(o=!1){return Ae.update(o?1:0).then(i=>i.audioInputs.devices)}function _t(o=!1){return Ae.update(o?2:0).then(i=>i.videoInputs.devices)}var xp=!1;function Pp(){return f(this,null,function*(){try{xp||(xp=!0,y.info(`speakers:${(yield Tr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Tr(o=!1){return f(this,null,function*(){return(_e||ke)&&(o=!1),Ae.update(o?1:0).then(i=>i.audioOutputs.devices)})}var pu=new Set;function Up(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!!pu.has(t)}function Vp(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!!pu.has(t)}function fu(o,i){return f(this,null,function*(){let t=(yield ft()).find(r=>r.deviceId===Mr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function Bp(s){return f(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===p.AUDIO&&o===Mr?yield fu(e,t):!0})}var fc,_u=class extends Sn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new hc);this.volumeMeter=new An({log:this.log}),this.volumeMeterAfter3A=new An({log:this.log}),this.volumeDestination=new Me,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},is=class o extends oi{constructor(e){super(e,p.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",pe("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new _u(this._log)}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ut==="15.2"||ut==="15.3"||ut==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=fc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,X(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===fc&&(fc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ae.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return f(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&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(pe("player").createAnalyser()),Pp(),Ue(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=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()}},_c=class extends is{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ae.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},gc=class extends is{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new Me);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(pe("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(ae.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){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!_e)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(_e)if(this.enableVolumeControlInIOS)Op();else return;if(te&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Ne(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&&Ot&&(fc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Qr=class extends W{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?gc:Ye}){var a;super();d(this,"id",Ks());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 si?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof si}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ae.PLAYER_STATE_CHANGED,c=>{I.emit(C.PLAYER_STATE_CHANGED,D({track:this},c)),this.emit("player-state-changed",c)}),this.kind===p.VIDEO&&(this.player.on(ae.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ae.LOADED_DATA),I.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ae.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ae.LOADED_META_DATA)}),this.player.on(ae.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ae.RESIZE,c=>{this.emitFirstVideoFrameEvent(ae.RESIZE),this.emit("video-size-changed",D({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ae.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||y}get kind(){return this.mediaType===1?p.AUDIO:p.VIDEO}get isAudio(){return this.kind===p.AUDIO}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=Ce(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 Ye&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ce(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 Ye&&(this.player.setObjectFit(this.objectFit),t&&!E(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof Ye&&this.player.setContainer(r)),I.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),Ce(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 Ye({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(sl(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),I.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){Fe(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){Ne(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(sl(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 Yo;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 Ye?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===ae.RESIZE&&!r&&!s||e===ae.LOADED_META_DATA&&!r&&!s||(e===ae.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,It(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`)}};O([Ie([],W.INIT,{sync:!0})],Qr.prototype,"close",1);var OT=Object.prototype.hasOwnProperty,{toString:Qy}=Object.prototype;function MT(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(rt(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(OT.call(o,i))return!1;return!0}}return!1}var Ii=MT;var kT=function(o){return f(this,null,function*(){let i=xT(o);y.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield ft(),y.info(`microphones: ${lt(e.map(s=>x(D({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield _t(),y.info(`cameras: ${lt(t,{keysToInclude:r})}`));try{let s=yield navigator.mediaDevices.getUserMedia(i);return jl&&s.getTracks().forEach(n=>{y.info(`${n.kind} capabilities: ${lt(n.getCapabilities(),{keysToInclude:da})}`)}),i.audio&&gr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=B({key:V.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=B({key:V.MICROPHONE_NOT_FOUND}))),new N({code:A.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},wT=pi({retryFunction:kT,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"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!ke||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&&Fp(t[0].microphoneId,!1),t[0].cameraId&&Fp(t[0].cameraId,!0)},onRetrying:o=>{y.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{re.logFailedEvent({eventType:ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{re.logSuccessEvent({eventType:ze.GET_USER_MEDIA_RETRY}),re.uploadEvent({log:`stat-${ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function Fp(o,i){return f(this,null,function*(){let t=(i?yield _t():yield ft()).find(r=>r.deviceId===o);t&&ne(t.getCapabilities)&&y.warn(lt(t.getCapabilities(),{keysToInclude:da}))})}function xT(o){return{audio:LT(o),video:PT(o)}}function LT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!Ii(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(X(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),Ii(i)?!0:i)}function PT(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&&!Ii(e)?e:(o.width&&(e.width={ideal:o.width},i&&!te&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!te&&(e.height.max=o.height)),te&&zt&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),Ii(e)?!0:e)}var Hp=wT;function Tc(o){return Q((i,e)=>function(...t){return f(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function gt(o){return Q((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Ec(o){return Q((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var $p=(()=>{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 UT=0,Sc=class{constructor(){d(this,"log",y.createLogger({id:`fq${++UT}`}));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=D({},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()})}},Rn=new WeakMap,Ic=new WeakMap;function kt(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Rn.get(this)||new Sc;return Rn.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Gp(o){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Rn.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 N({code:A.API_CALL_ABORTED,message:o})),!1):!0});n.queue=a}return r.apply(this,s)},t}}function Ac(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Rn.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=Ic.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new N({code:A.API_CALL_ABORTED,message:o}))}),Rn.delete(this),Ic.delete(this),r.apply(this,s)},t}}function Qi(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=Ic.get(this)||new Map,c=a.get(s(n))||new Sc;return a.set(s(n),c),Ic.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Tt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=P();return hr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:P()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var rh={};Mi(rh,{Events:()=>De,Inspect:()=>wt,LastSink:()=>Yr,Sink:()=>J,Subscribe:()=>Zr,TimeoutError:()=>yn,audit:()=>SE,bindCallback:()=>sE,bindNodeCallback:()=>nE,buffer:()=>qT,bufferCount:()=>JT,bufferTime:()=>BE,call:()=>Wp,catchError:()=>Ku,combineLatest:()=>qp,concat:()=>FT,concatMap:()=>ME,concatMapTo:()=>kE,count:()=>dE,create:()=>se,debounce:()=>IE,debounceTime:()=>AE,defer:()=>jp,delay:()=>FE,deliver:()=>j,dispose:()=>Cc,elementAt:()=>CE,empty:()=>Dn,every:()=>NE,exhaustMap:()=>LE,exhaustMapTo:()=>PE,expand:()=>HE,filter:()=>xt,find:()=>RE,findIndex:()=>yE,first:()=>bE,fromAnimationFrame:()=>rE,fromArray:()=>YT,fromEvent:()=>ue,fromEventPattern:()=>ZT,fromFetch:()=>KT,fromIterable:()=>eE,fromPromise:()=>Qp,fromReadableStream:()=>iE,fromReader:()=>tE,groupBy:()=>UE,identity:()=>VT,ignoreElements:()=>mE,iif:()=>$T,inspect:()=>Jp,interval:()=>Cu,last:()=>vE,map:()=>On,mapTo:()=>OE,max:()=>lE,merge:()=>bn,mergeMap:()=>wE,mergeMapTo:()=>xE,min:()=>uE,never:()=>aE,nothing:()=>he,of:()=>QT,pairwise:()=>DE,pipe:()=>le,race:()=>Iu,range:()=>oE,reduce:()=>Ru,retry:()=>JE,scan:()=>Zu,setAsapScheduler:()=>zT,share:()=>Yi,shareReplay:()=>HT,skip:()=>fE,skipUntil:()=>_E,skipWhile:()=>Nc,startWith:()=>vn,subject:()=>ct,subscribe:()=>Re,sum:()=>hE,switchMap:()=>os,switchMapTo:()=>io,take:()=>Zi,takeLast:()=>pE,takeUntil:()=>Le,takeWhile:()=>Yp,tap:()=>ih,throttle:()=>TE,throwError:()=>cE,timeInterval:()=>VE,timeout:()=>WE,timer:()=>Nn,toPromise:()=>$E,toReadableStream:()=>GE,withLatestFrom:()=>WT,zip:()=>GT});function he(...o){}var Wp=o=>o(),VT=o=>o;function Cc(){this.dispose()}var Jp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",BT=1,wt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new gu(i,this,this.streamId++);return De.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Yr=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=he,this.error=he,this.next=he,this.dispose=he,this.subscribe=he,this.doDefer()}subscribe(i){return i instanceof wt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Wp),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}},J=class extends Yr{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)}},Zr=class extends Yr{constructor(i,e=he,t=he,r=he){if(super(),this._next=e,this._error=t,this._complete=r,this.then=he,i instanceof wt){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{De.defer(s,0)}),De.create(s),De.pipe(s),this.sourceId=s.id,this.subscribe(i),De.subscribe({id:s.id,end:!0}),e==he?this._next=n=>De.next(s,0,n):this.next=n=>{De.next(s,0,n),e(n)},r==he?this._complete=()=>De.complete(s,0):this.complete=()=>{this.dispose(),De.complete(s,0),r()},t==he?this._error=n=>De.complete(s,0,n):this.error=n=>{this.dispose(),De.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function le(o,...i){return i.reduce((e,t)=>t(e),o)}function se(o,i,e){if(Jp()){let t=Object.defineProperties(Object.setPrototypeOf(o,wt.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}});De.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof wt&&De.addSource(t,s)}return t}return o}function j(o,i){return function(...e){return t=>{if(t instanceof wt){let r=se(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,De.pipe(r),r}else return r=>t(new o(r,...e))}}}function Er(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var gu=class extends J{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{De.defer(this.source,this.id)})}next(i){De.next(this.source,this.id,i),this.sink.next(i)}complete(){De.complete(this.source,this.id),this.sink.complete()}error(i){De.complete(this.source,this.id,i),this.sink.error(i)}},De={addSource(o,i){Er("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Er("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Er("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Er("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Er("defer",{id:o.id,streamId:i})},pipe(o){Er("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Er("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=BT++),Er("create",{name:o.toString(),id:o.id})}},yn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Rc=class extends Yr{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 Yi(){return o=>{let i=new Rc(o);if(o instanceof wt){let e=se(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,De.pipe(e),e}return se(i.add.bind(i),"share",arguments)}}function bn(...o){return se(i=>{let e=new J(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function Iu(...o){return se(i=>{let e=new Map;o.forEach(t=>{let r=new J(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 FT(...o){return se(i=>{let e=0,t=o.length,r=new J(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function HT(o){return i=>{let e=new Rc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},se(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function $T(o,i,e){return se(t=>o()?i(t):e(t),"iif",arguments)}function qp(...o){return se(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new J(i);u.next=h=>{t--,u.next=m=>{s[l]=m,t===0&&i.next(s)},u.next(h)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function GT(...o){return se(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new J(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 vn(...o){return i=>se((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Tu=class extends J{constructor(i,...e){super(i);let t=new J(this.sink);t.next=r=>this.buffer=r,t.complete=he,t.subscribe(qp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},WT=j(Tu,"withLatestFrom"),Eu=class extends J{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()}},JT=j(Eu,"bufferCount"),Su=class extends J{constructor(i,e){super(i),this.buffer=[];let t=new J(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=he,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},qT=j(Su,"buffer");var jT=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 ct(o){let i=arguments,e=Yi()(se(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=he,e.complete=he,e.error=he,e}function jp(o){return se(i=>i.subscribe(o()),"defer",arguments)}var rs={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},XT=()=>typeof Promise!="undefined"?rs.promise:rs.setImmediate?rs.setImmediate:rs.setTimeout,Au=XT(),Xp=o=>i=>{Au(()=>o(i))},zT=o=>{typeof o=="function"?Au=o:rs[o]&&(Au=rs[o])};var zp=o=>Xp(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function QT(...o){return se(zp(o),"of",arguments)}function YT(o){return se(zp(o),"fromArray",arguments)}function Cu(o){return se(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Nn(o,i){return se(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 yc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function ZT(o,i){return se(yc(o,i),"fromEventPattern",arguments)}function ue(o,i){if("on"in o&&"off"in o)return se(yc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return se(yc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return se(yc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Qp(o){return se(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function KT(o,i){return se(jp(()=>Qp(fetch(o,i))),"fromFetch",arguments)}function eE(o){return se(Xp(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function tE(o){let i=e=>jT(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 se(e=>{i(e)},"fromReader",arguments)}function iE(o){return se(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 rE(){return se(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function oE(o,i){return se((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function sE(o,i,...e){return se(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function nE(o,i,...e){return se(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function aE(){return se(()=>{},"never",arguments)}function cE(o){return se(i=>i.error(o),"throwError",arguments)}function Dn(){return se(o=>o.complete(),"empty",arguments)}var Kr=class extends J{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)}},Ru=j(Kr,"reduce"),dE=o=>j(Kr,"count")((i,e)=>o(e)?i+1:i,0),lE=()=>j(Kr,"max")(Math.max),uE=()=>j(Kr,"min")(Math.min),hE=()=>j(Kr,"sum")((o,i)=>o+i,0);var yu=class extends J{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},xt=j(yu,"filter"),bu=class extends J{next(i){}},mE=j(bu,"ignoreElements"),vu=class extends J{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},Zi=j(vu,"take"),Nu=class extends J{constructor(i,e){super(i);let t=new J(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=Cc,t.subscribe(e)}},Le=j(Nu,"takeUntil"),Du=class extends J{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},Yp=j(Du,"takeWhile"),pE=o=>Ru((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),Ou=class extends J{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},fE=j(Ou,"skip"),Mu=class extends J{constructor(i,e){super(i),i.next=he;let t=new J(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=Cc,t.subscribe(e)}},_E=j(Mu,"skipUntil"),ku=class extends J{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Nc=j(ku,"skipWhile"),gE={leading:!0,trailing:!1},wu=class extends J{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},bc=class extends J{constructor(i,e,t=gE){super(i),this.durationSelector=e,this.config=t,this._throttle=new wu(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=he,this._throttle.complete(),super.complete()}},TE=j(bc,"throttle"),EE={leading:!1,trailing:!0},SE=o=>j(bc,"audit")(o,EE),xu=class extends J{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},vc=class extends J{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new xu(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()}},IE=j(vc,"debounce"),AE=o=>j(vc,"debounceTime")(i=>Nn(o)),Lu=class extends J{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),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()}},CE=j(Lu,"elementAt"),RE=o=>i=>Zi(1)(Nc(e=>!o(e))(i)),Pu=class extends J{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},yE=j(Pu,"findIndex"),Uu=class extends J{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.doDefer(),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()}},bE=j(Uu,"first"),Vu=class extends J{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()}},vE=j(Vu,"last"),Bu=class extends J{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.doDefer(),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()}},NE=j(Bu,"every");var Fu=class extends J{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))}},Zu=j(Fu,"scan"),Hu=class extends J{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},DE=j(Hu,"pairwise"),Dc=class extends J{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},On=j(Dc,"map"),OE=o=>j(Dc,"mapTo")(i=>o),eo=class extends J{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()}},to=class o extends J{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===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Oc=class extends eo{},Mc=class extends to{next(i){this.subInner(i,Oc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Oc)}}},os=j(Mc,"switchMap");function Lc(o){return(i,e)=>o(()=>i,e)}var io=Lc(j(Mc,"switchMapTo")),$u=class extends eo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},kc=class extends to{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()}},ME=j(kc,"concatMap"),kE=Lc(j(kc,"concatMapTo")),Gu=class extends eo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},wc=class extends to{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()}},wE=j(wc,"mergeMap"),xE=Lc(j(wc,"mergeMapTo")),Wu=class extends eo{dispose(){this.context.resetNext(),super.dispose()}},xc=class extends to{next(i){this.next=he,this.subInner(i,Wu)}},LE=j(xc,"exhaustMap"),PE=Lc(j(xc,"exhaustMapTo")),Ju=class extends J{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=ct(),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)}},UE=j(Ju,"groupBy"),qu=class extends J{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}},VE=j(qu,"timeInterval"),ju=class extends J{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()}},BE=j(ju,"bufferTime"),Xu=class extends J{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)}},FE=j(Xu,"delay"),zu=class extends J{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Ku=j(zu,"catchError"),Qu=class extends eo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},Yu=class extends to{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new Qu(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},HE=j(Yu,"expand");var $E=()=>o=>new Promise((i,e)=>{let t;new Zr(o,r=>t=r,e,()=>i(t))}),GE=()=>o=>{let i;return new ReadableStream({start(e){i=new Zr(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Re=(o=he,i=he,e=he)=>t=>new Zr(t,o,i,e),eh=class extends J{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)}))}},ih=j(eh,"tap"),th=class extends J{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new yn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},WE=j(th,"timeout"),JE=(o=1/0)=>i=>{if(i instanceof wt){let e=se(t=>{let r=o,s=new J(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,De.pipe(e),e}else return e=>{let t=o,r=new J(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ss=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ss||{}),ro=class ro extends Qr{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,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Fe(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){Ne(e)}setStateToReady(){}capture(e,t=!1){return f(this,null,function*(){var s;let r=this.sourceTrack;try{let n=P();I.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield Hp(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),I.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:P()-n}),a}catch(n){throw I.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Wt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}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),Promise.all([t,new Promise((r,s)=>f(this,null,function*(){var a,c;this.hasFlag?r():le(ue(e,"local-publish-flag-changed"),xt(()=>this.hasFlag),Le(bn(ue(this,W.INIT),ue(this,"ready"))),Re(r)),!((((c=(a=this.room)==null?void 0:a.networkQuality)==null?void 0:c.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>f(this,null,function*(){var u,h,m,g,T,_;if(!((((h=(u=this.room)==null?void 0:u.networkQuality)==null?void 0:h.uplinkNetworkQuality)||0)>3)&&(this.isPublished||this.isPublishing)&&this.isMediaTrackActive){let S=this.kind===p.AUDIO,R=this.stat.bytesSent>0;if(v[R?"addSuccessEvent":"addFailedEvent"]({key:S?503700:513702}),!S){let q=((g=(m=this.room)==null?void 0:m.videoCodec)==null?void 0:g.toUpperCase())||"H264",H={H264:513704,H265:513705,VP8:513706}[q];H&&v[R?"addSuccessEvent":"addFailedEvent"]({key:H})}if(!R){if(v.addEnum({key:S?503701:513703,value:Fr()}),re.uploadEvent({log:`stat-encode-failed-${this.kind}-${Gi()||Wi()}`,userId:this.userId}),this.log.warn(S?"encode failed":`${(_=(T=this.room)==null?void 0:T.videoCodec)==null?void 0:_.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield St(5e3),this.stat.bytesSent>0||this.hasFlag)))return;this.emit("6",this),s(new N({message:`${this.strMediaType} encode failed`,code:S?A.AUDIO_ENCODE_FAILED:A.VIDEO_ENCODE_FAILED}))}}}),5e3))}))])}unpublish(){this.room&&this.room.localTracks.delete(this),I.emit(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.sourceTrack&&Ti){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield Bp({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),es().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===p.AUDIO&&!Vp(this.sourceTrack)||this.kind===p.VIDEO&&!Up(this.sourceTrack)||this._isRecapturing||e&&zt&&ke)}onTrackMuted(){if(super.onTrackMuted(),$p(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<So){setTimeout(()=>this.onTrackMuted(),So);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((_e||me)&&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(Ue(ro.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<So){setTimeout(()=>this.onTrackEnded(),So);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return f(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield ft():yield _t()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),I.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),I.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof qe;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Mn.get(t)||0)+1;if(Mn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield _t()).find(n=>!Mn.has(n.deviceId)):(yield ft()).find(n=>!Mn.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()}};O([Ie(W.INIT,"ready",{ignoreError:!0,sync:!0})],ro.prototype,"setStateToReady",1),O([kt()],ro.prototype,"capture",1),O([Ie("ready","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),I.emit(C.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let t="error";if(e.cause instanceof N){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===A.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),Tt(521714,!1)],ro.prototype,"publish",1),O([Q(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)})}),Ie([],"ready",{sync:!0})],ro.prototype,"unpublish",1);var si=ro,Mn=new Map;I.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Mn.delete(o.track.deviceId)});var vt=class o extends si{constructor(e){super(1,_c);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 Me);d(this,"_output",new Me);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);this.manager=e,this.pipeline=new Ko(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),I.on(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return zr.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||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.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 Ue(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return f(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Ue(o.prototype,this,"capture").call(this,{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},n);return gr(),c})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Mr){if(yield fu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),I.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(){Ae&&!Ae.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Ae.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ss[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ye(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield ft();r[0]?this.recapture(r[0].deviceId):t=!0}t&&Ae.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Ae.off("audioInputAdded",this.handleMicrophoneAdded,this),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&&(te||ke?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),_e&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(pe().createGain()),this._output.setNode(pe().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(ke||_e))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(We<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.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=In(e);if(!r)return;let s=new Me,n=pe().createGain();n.gain.value=1;let a=new Me;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){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Ae.off("audioInputAdded",this.handleMicrophoneAdded,this),Ae.off("audioInputRemoved",this.handleMicrophoneRemoved,this),I.off(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return f(this,null,function*(){try{yield Ue(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield ft()).find(n=>n.deviceId!==e);if(s)yield Ue(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:ki()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${hu/1e3} seconds, change to source audio${Ot?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};var Ki=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 Pc=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 Ki(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,g)=>m+g.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 g=0;g<n[m].dataView.byteLength;g++)l.setInt8(h++,n[m].dataView.getInt8(g));for(let m=0;m<i.data.byteLength;m++)l.setInt8(h++,u.getInt8(m));return i.data=c,n.length}return 0}};var Sr=class Sr extends si{constructor(e,t=4){super(t,Ye);d(this,"profile",D({},cr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Pc);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(x(D({},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(!(!Ti||!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(ee(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,Ue(Sr.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Ue(Sr.prototype,this,"setMute").call(this,e)})}capture(a){return f(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={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};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Ue(Sr.prototype,this,"capture").call(this,c)})}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(x(D({},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&&(Qe===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 Ti&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Do(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)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),I.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}})}getDeviceIdWhenUsingBackCamera(){return f(this,null,function*(){let e;try{if(Xs&&!Ho&&Xl){let r=(yield _t(!0)).map(n=>{var a;return x(D({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,h,m,g;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((h=a.height)!=null&&h.max)?a.width.max*a.height.max:0,l=(m=s.capabilities.width)!=null&&m.max&&((g=s.capabilities.height)!=null&&g.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}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=D({},e);return e.width*e.height<=160*120&&me&&Be&&(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&&_l&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),Ys(ut,"14.3")&&pl(ut,"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&&(Be||te)&&!Zs()&&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(){Ae&&!Ae.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Ae.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ss[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ye(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield _t();r[0]?this.recapture(r[0].deviceId):t=!0}t&&Ae.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Ae.off("videoInputAdded",this.handleCameraAdded,this),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(){Ae.off("videoInputAdded",this.handleCameraAdded,this),Ae.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ue(Sr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield _t()).find(s=>s.deviceId!==e);if(r)yield Ue(Sr.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))}};O([gt(function(e){this.setContentHint(e.contentHint||"motion")})],Sr.prototype,"capture",1);var qe=Sr;var sh={};Mi(sh,{REPORT_TYPE:()=>Oo,buildSSOPackage:()=>Vi,bytes2ms:()=>pm,calculateScaleResolutionDownNumber:()=>Do,concatArrayBuffers:()=>Ea,convertObjectNumberToInt:()=>Vs,copyProperties:()=>mm,deepClone:()=>kr,deepCloneBasic:()=>ma,deepMerge:()=>Jt,delay:()=>St,fibonacci:()=>xr,formatedTime:()=>Cm,getConstructorName:()=>Ro,getContainerFromElement:()=>Am,getEnv:()=>um,getFirst16Bits:()=>ym,getInternalVersion:()=>Sm,getLast16Bits:()=>Sa,getLoggerUrl:()=>Ui,getMediaStreamTrackInfo:()=>Ta,getMuteStateFromFlag:()=>Wt,getNetworkType:()=>Zd,getNumNetworkType:()=>wr,getReconnectionTimeout:()=>Gt,getStringByteLength:()=>Us,getTurnServer:()=>Im,getUint32Version:()=>fa,getValueType:()=>ve,getViewListFromView:()=>vo,glog:()=>tl,ipv4ToUint32:()=>bo,isArray:()=>Ce,isAudioWorkletSupported:()=>Tm,isBoolean:()=>de,isConstructor:()=>Lr,isEmpty:()=>yo,isFunction:()=>ne,isLangChinese:()=>$t,isMediaStreamTrack:()=>_m,isNumber:()=>X,isObject:()=>Et,isOverseaSdkAppId:()=>Pi,isPlainObject:()=>rt,isPortrait:()=>il,isPromise:()=>hr,isRemoteTrack:()=>gm,isRotate90Or270:()=>It,isSetSinkIdSupported:()=>Em,isString:()=>ee,isUndefined:()=>E,loadImage:()=>No,loadVideo:()=>Rm,ms2bytes:()=>fm,ms2samples:()=>el,normalizeUrl:()=>ga,performanceNow:()=>P,promiseAny:()=>Pr,samples2ms:()=>Kd,setNetworkType:()=>pa,stringify:()=>lt,stringifyIncludeValue:()=>Ps,throttlePromise:()=>_a});var XE=[-1,-1,1,-1,-1,1,1,1],zE=[0,0,1,0,0,1,1,1];var Ir=class Ir extends W{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 je){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&Qe!==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(zE),this.positionBuffer=this.createBuffer(XE),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.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 N({code:A.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 Pe&&this.render(e)||this.context instanceof je&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Pe){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),this.emit(Ir.RENDER,this.ctx2d.canvas)):(h?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(Ir.RENDER,e)),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},D({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.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(Ir,"RENDER","render"),O([Ie(W.INIT,"connected",{sync:!0})],Ir.prototype,"connect",1),O([Ie("connected",W.INIT,{ignoreError:!0,sync:!0})],Ir.prototype,"disconnect",1),O([Ie([],"closed",{sync:!0})],Ir.prototype,"close",1);var He=Ir;var QE=le(Cu(250),On(()=>performance.now()),Yi());var Zp=o=>i=>{let e=performance.now();le(QE,Nc(t=>t-e<o),Zi(1))(i)};var ZE=[0,1,1,1,0,0,1,0],oo=class extends He{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 je?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(ZE)}start(e){this.log.info(`${this.name} start render ${e} fps`),ie.clearTask(this._intervalId),this._intervalId=ie.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(ie.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Pe){let r=this.context.ctx.getError();r&&this.context.destroy(new N({code:A.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(),this.emit(He.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(ie.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),ie.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),ie.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},ns=class extends oo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ue(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Hi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ue(this._videoTrack,"mute"),le(ue(this._videoTrack,"ended"),Le(this._closedOb),Re(()=>{this.context.destroy(new N({code:A.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=le(this._muteOb,Le(this._closedOb),io(Zp(5e3)),xt(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Re(()=>{this.context.destroy(new N({code:A.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()}},Uc=class extends ns{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Vc=class extends ns{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 kn=class extends He{constructor(e,t){super(e,D({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,Qe===16&&(this._canvasRendered=ct(),le(this._canvasRendered,vn(this._image),os(r=>r instanceof HTMLCanvasElement?ue(r,"rendered"):Dn()),Le(ue(this,"closed")),Re(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Xr()&&!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!0}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)}},wn=class extends kn{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",le(ue(this._player,ae.PLAYER_STATE_CHANGED),Le(ue(this,"closed")),xt(({state:s})=>s==="PLAYING"),Re(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Lt=class extends wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new Ye({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()}},Bc=class extends He{constructor(e,t,r){super(e,x(D({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
|
|
31
|
+
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=ih,o.innerText=`${Or()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${Yd}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Ha()||(oh=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Wa}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",F.info("show autoplay dialog"),We.uploadEvent({log:UI}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,oh=!1)}onConfirm(){F.warn("confirm clicked, try resume stream"),U.emit($.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${wg}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||We.uploadEvent({log:VI}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Pg,"_blank"),this._isQuestionClicked||We.uploadEvent({log:FI}),this._isQuestionClicked=!0}},gn=sh;var Lt=class extends $r{constructor(e){super(e,O.VIDEO);l(this,"stat",{});l(this,"_calculateTimeout",-1);l(this,"viewMirror",!1);l(this,"objectFit");l(this,"container");l(this,"canvas");l(this,"_preSize",{width:0,height:0});this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,M(e.viewMirror)||(this.viewMirror=e.viewMirror),M(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(O.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,it&&(e.poster="noposter"),(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(O.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(O.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(O.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var r;return e.type===O.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var o,s,n,a,u,m,p,g;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===O.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=Bo,this._log.info(`view container ${(s=this.container)==null?void 0:s.id} is recreated`)),this._pausedRetryCount>0&&!Ha()&&!this._isPausedByUserCall&&(this._log.info(`[${Bo-this._pausedRetryCount+1}/${Bo}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let E=this.element.style.transform;r===O.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=E.replace("scaleX(-1)",""):r===O.LEAVE_PICTURE_IN_PICTURE&&!E.includes("scaleX")&&(this.element.style.transform=`${E} scaleX(-1)`)}r===O.RESIZE&&(this._preSize.height!==((n=this.element)==null?void 0:n.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info(`video size changed to ${(u=this.element)==null?void 0:u.videoWidth}x${(m=this.element)==null?void 0:m.videoHeight}`),this._preSize.height=((p=this.element)==null?void 0:p.videoHeight)||0,this._preSize.width=((g=this.element)==null?void 0:g.videoWidth)||0,this.emit(He.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,r=1){var o,s,n,a;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&&((a=this.container)==null||a.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(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(Mi()&&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 a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function xi(i,t){return y(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),F.info("worklet addModule success")}catch(e){throw F.info(`worklet addModule catch error. ${e.message}`),e}})}var Ga;typeof AudioContext!="undefined"?Ga=AudioContext:typeof webkitAudioContext!="undefined"?Ga=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Ga=mozAudioContext);var uh=1500,Ut,kg=-1,Kd=0,ja=-1,dh=!1,Lg=0,Ug=-1,Vg=-1;Fg();function Fg(){try{if(Ut)return;Ut=new Ga({sampleRate:48e3}),Ut.onstatechange=()=>{F.info(`context state: ${Ut.state}${Ut.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),En()},clearTimeout(kg)}catch(i){F.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof Ga}`),kg=setTimeout(Fg,1e3)}}var En=()=>{Ut.state==="suspended"?(Kd=Ee(),BI(),lo(),document.addEventListener("click",En)):Ut.state==="interrupted"?lo():(Kd&&(Q.addNumber({key:507800,value:Ee()-Kd,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Kd=0),HI(),document.removeEventListener("visibilitychange",En),document.removeEventListener("click",En))},ah=0,ch=-1;function lo(){return new Promise((i,t)=>{if(Ut.state==="running")return i();Date.now()-ah<1e3?(clearTimeout(ch),ch=setTimeout(()=>{ah=Date.now(),Ut.resume().then(i,t)},1e3)):(clearTimeout(ch),ah=Date.now(),Ut.resume().then(i,t))}).catch(i=>{F.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",En)})}document.addEventListener("click",En);function BI(){ja===-1&&(ja=setTimeout(()=>{Ut.state==="suspended"&&(dh=!0,U.emit("155",{isSuspended:!0}))},uh))}function HI(){ja!==-1&&(clearTimeout(ja),ja=-1,dh&&(dh=!1,U.emit("155",{isSuspended:!1})))}function $g(){if(!tt||Vg!==-1)return;let i=()=>{Ee()-Lg<500||(Ut&&Ut.state==="running"&&Ut.currentTime===Ug&&(F.warn("context is fake running, auto resume"),Ut.suspend().catch(t=>{F.warn(`context suspend failed: ${t}`)})),Ug=Ut.currentTime,Lg=Ee())};Vg=setInterval(()=>{i()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&i()})}var Ge=i=>Ut;var _t=class{constructor(t){this.name=t;l(this,"node");l(this,"node2");l(this,"pre",new Set);l(this,"next",new Set);l(this,"context");l(this,"connectedNodes",new Set);l(this,"nextInputChannelMap",new Map);l(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(e=>e.channelCount=t)}setChannelCount(t,e){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=e||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var e;if(t!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){F.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),Q.addSuccessEvent({key:502701})}catch(o){F.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){F.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}},eu=class extends _t{constructor(e=256){super();this.fftSize=e;l(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 a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},qa=class{constructor(){l(this,"source",new _t);l(this,"gain",new _t);l(this,"destination",new _t)}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(Ge().createGain()),this.gain.node.gain.value=t}replaceSource(t){let e=za(t);e&&this.source.replaceNode(e)}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}},_n=class extends qa{constructor(e){super();this.context=e;l(this,"aec",new _t("aec"));l(this,"mixNode",new _t("mixNode"));l(this,"silentNode",new _t("silentNode"));l(this,"denoiser",new _t("denoiser"));l(this,"voiceChanger",new _t("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)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}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}},tu=class{constructor(){l(this,"audioContext",Ge("audio-mixer"));l(this,"destination",this.audioContext.createMediaStreamDestination());l(this,"inputs",new Set);l(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]}},Bg=new WeakMap;function za(i){try{let t=Bg.get(i);if(t)return t;let e=Ge();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Bg.set(i,t),t}catch(t){if(ft&&t instanceof Error&&t.name==="NotSupportedError")F.warn(t);else throw t}}var ur=class ur{constructor(t){l(this,"_volume",0);l(this,"_volumeDb",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=t;this._log=e,U.on($.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ur.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ur.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);';ur.workletReady=xi(ur.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return ur.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ur.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{ur.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}`),We.logFailedEvent({userId:this._log.userId,eventType:gr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ge("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{ur.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,U.off($.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})}};l(ur,"lastMessageTime",0),l(ur,"audioContext",Ge("volume-meter")),l(ur,"workletReady");var ru=ur,Ja=class extends _t{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new ru(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()}}},iu=ru;var jg=pi(bi(),1);var Wg=i=>t=>t.deviceId===i;var Xa=class{constructor(t,e){l(this,"kind");l(this,"type");l(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&&In(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(Wg(o.deviceId))){let s=`${this.kind}${this.type}Added`;F.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(Wg(o.deviceId))){let s=`${this.kind}${this.type}Removed`;F.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},lh=class extends jg.EventEmitter{constructor(){super();l(this,"audioInputs",new Xa(O.AUDIO,"Input"));l(this,"videoInputs",new Xa(O.VIDEO,"Input"));l(this,"audioOutputs",new Xa(O.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||lt.run("interval",()=>{this.update()},{delay:1e4}))}init(){Tn().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 Tn(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}hasBlueTooth(){var r;if(((r=Ge())==null?void 0:r.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(s=>o.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(o=>e.some(s=>o.label.toLowerCase().includes(s)))}},ot=Zn||Fs?null:new lh;function In(i){return i.deviceId===i.groupId&&i.groupId===""}function Tn(){return y(this,arguments,function*(i=0){if(wi()||!jd())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{In(r)&&(r.kind===O.AUDIO_INPUT?e.audio=!0:r.kind===O.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&&lo()}catch(o){F.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&mh.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function rr(i=!1){return ot.update(i?1:0).then(t=>t.audioInputs.devices)}function ir(i=!1){return ot.update(i?2:0).then(t=>t.videoInputs.devices)}var Gg=!1;function qg(){return y(this,null,function*(){try{Gg||(Gg=!0,F.info(`speakers:${(yield mo()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function mo(i=!1){return y(this,null,function*(){return(tt||It)&&(i=!1),ot.update(i?1:0).then(t=>t.audioOutputs.devices)})}var mh=new Set;function zg(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}_${O.VIDEO_INPUT}`;return!!mh.has(r)}function Jg(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}_${O.AUDIO_INPUT}`;return!!mh.has(r)}function hh(i,t){return y(this,null,function*(){let r=(yield rr()).find(o=>o.deviceId===Ho);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function Xg(s){return y(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===O.AUDIO&&i===Ho?yield hh(e,r):!0})}var ou,ph=class extends qa{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeMeterAfter3A");l(this,"volumeDestination");l(this,"analyser",new eu);this.volumeMeter=new Ja({log:this.log}),this.volumeMeterAfter3A=new Ja({log:this.log}),this.volumeDestination=new _t,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Sn=class i extends $r{constructor(e){super(e,O.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",Ge("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");l(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new ph(this._log)}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tr==="15.2"||Tr==="15.3"||Tr==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=ou||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,ke(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===ou&&(ou=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(He.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return y(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&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(Ge("player").createAnalyser()),qg(),Pt(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._volume=e,this.element&&(this.element.volume=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()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},su=class extends Sn{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(He.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}},nu=class extends Sn{constructor(e){super(e);l(this,"_sourceElement");l(this,"_output",new _t);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(Ge("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(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){if(this._volume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!tt)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(tt)if(this.enableVolumeControlInIOS)$g();else return;if(ft&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),mt(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&&_r&&(ou=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var ds=class extends le{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?nu:Lt}){var a;super();l(this,"id",Ra());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"rotation");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");l(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=F.createLogger({id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Br?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Br}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(He.PLAYER_STATE_CHANGED,u=>{U.emit($.PLAYER_STATE_CHANGED,X({track:this},u)),this.emit("player-state-changed",u)}),this.kind===O.VIDEO&&(this.player.on(He.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(He.LOADED_DATA),U.emit($.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,u=>{var m;(m=this.subVideoPlayerMap)==null||m.forEach(p=>p.setTrack(u))}),this.player.on(He.RESIZE,u=>{this.emitFirstVideoFrameEvent(He.RESIZE),this.emit("video-size-changed",X({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},u))})),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||F}get kind(){return this.mediaType===1?O.AUDIO:O.VIDEO}get isAudio(){return this.kind===O.AUDIO}get strMediaType(){return this.mediaType===4?O.VIDEO:this.mediaType===2?O.SCREEN:O.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=at(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!M(r.muted)&&this.setPlayerMute(r.muted),r&&!M(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Lt&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),at(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!M(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===O.VIDEO)&&this.setPlayerMute(!0),r&&!M(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof Lt&&(this.player.setObjectFit(this.objectFit),r&&!M(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Lt&&this.player.setContainer(o)),U.emit($.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),at(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!==O.VIDEO||M(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(Qe(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===O.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(u=>n===u)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?r&&(M(r.objectFit)||a.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new Lt({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(tm(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),U.emit(e?$.TRACK_MUTED:$.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){Rt(e,e).add(O.MUTE,this.onTrackMuted).add(O.UNMUTE,this.onTrackUnmuted).add(O.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===O.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(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(tm(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 gn;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 Lt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,u;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(r==null?void 0:r.height)||((u=this.player.element)==null?void 0:u.videoHeight)||0;e===He.RESIZE&&!o&&!s||e===He.LOADED_META_DATA&&!o&&!s||(e===He.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,cr(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`)}};te([Ze([],le.INIT,{sync:!0})],ds.prototype,"close",1);var WI=Object.prototype.hasOwnProperty,{toString:CN}=Object.prototype;function GI(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(jt(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(WI.call(i,t))return!1;return!0}}return!1}var Qa=GI;var jI=function(i){return y(this,null,function*(){let t=zI(i);F.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];if(t.audio&&(e=yield rr(),F.info(`microphones: ${Er(e.map(s=>ge(X({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield ir(),F.info(`cameras: ${Er(r,{keysToInclude:o})}`),t.video.facingMode==="user"&&!t.video.deviceId)){let n=r.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(t.video.deviceId=n.deviceId,F.info(`exclude infrared camera: ${JSON.stringify(t)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(t);return jm&&s.getTracks().forEach(n=>{var u;let a=n.getCapabilities();F.info(`${n.kind} capabilities: ${Er(a,{keysToInclude:Zc})}`),!M(i.echoCancellation)&&((u=a.echoCancellation)==null?void 0:u.indexOf(i.echoCancellation))===-1&&F.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${i.echoCancellation}'`)}),t.audio&&lo(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=$e({key:Fe.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=$e({key:Fe.MICROPHONE_NOT_FOUND}))),new de({code:q.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},qI=oo({retryFunction:jI,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"||i.name==="AbortError"?(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&&Qg(r[0].microphoneId,!1),r[0].cameraId&&Qg(r[0].cameraId,!0)},onRetrying:i=>{F.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{We.logFailedEvent({eventType:gr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{We.logSuccessEvent({eventType:gr.GET_USER_MEDIA_RETRY}),We.uploadEvent({log:`stat-${gr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function Qg(i,t){return y(this,null,function*(){let r=(t?yield ir():yield rr()).find(o=>o.deviceId===i);r&&je(r.getCapabilities)&&F.warn(Er(r.getCapabilities(),{keysToInclude:Zc}))})}function zI(i){return{audio:JI(i),video:XI(i)}}function JI(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!Qa(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(ke(i.channelCount)&&(t.channelCount=i.channelCount),(Qe(i.echoCancellation)||i.echoCancellation==="remote-only"||i.echoCancellation==="all")&&(t.echoCancellation=i.echoCancellation),Qe(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),Qe(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),Qa(t)?!0:t)}function XI(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&&!Qa(e)?e:(i.width&&(e.width={ideal:i.width},t&&!ft&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!ft&&(e.height.max=i.height)),ft&&Lr&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),Qa(e)?!0:e)}var Yg=qI;function ho(i){return Me((t,e)=>function(...r){return y(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function Zg(i){return Me((t,e)=>function(...r){return y(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Kg=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&F.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{F.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var QI=0,au=class{constructor(){l(this,"log",F.createLogger({id:`fq${++QI}`}));l(this,"isRunning",!1);l(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((a,u)=>{r.resolve=a,r.reject=u});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()})}},eE=new WeakMap,tE=new WeakMap;function us(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=eE.get(this)||new au;return eE.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function rE(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let a=tE.get(this)||new Map,u=a.get(s(n))||new au;return a.set(s(n),u),tE.set(this,a),u.push({fn:o,args:n,context:this})},r}}function cu(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),a=Ee();return ro(n)?n.then(u=>(t?Q.addSuccessEvent({key:s,cost:Ee()-a}):Q.addSuccessEvent({key:s}),u)).catch(u=>{throw Q.addFailedEvent({key:s,error:u}),u}):(Q.addSuccessEvent({key:s}),n)}catch(n){throw Q.addFailedEvent({key:s,error:n}),n}})}var tp={};hi(tp,{Events:()=>ht,Inspect:()=>Sr,LastSink:()=>ls,Sink:()=>pe,Subscribe:()=>ms,TimeoutError:()=>Ya,audit:()=>xS,bindCallback:()=>_S,bindNodeCallback:()=>TS,buffer:()=>sS,bufferCount:()=>oS,bufferTime:()=>ZS,call:()=>iE,catchError:()=>Yh,combineLatest:()=>sE,concat:()=>KI,concatMap:()=>GS,concatMapTo:()=>jS,count:()=>yS,create:()=>xe,debounce:()=>PS,debounceTime:()=>kS,defer:()=>nE,delay:()=>KS,deliver:()=>_e,dispose:()=>du,elementAt:()=>LS,empty:()=>tc,every:()=>BS,exhaustMap:()=>JS,exhaustMapTo:()=>XS,expand:()=>ey,filter:()=>Qt,find:()=>US,findIndex:()=>VS,first:()=>FS,fromAnimationFrame:()=>gS,fromArray:()=>uS,fromEvent:()=>be,fromEventPattern:()=>lS,fromFetch:()=>mS,fromIterable:()=>hS,fromPromise:()=>dE,fromReadableStream:()=>fS,fromReader:()=>pS,groupBy:()=>QS,identity:()=>YI,ignoreElements:()=>vS,iif:()=>tS,inspect:()=>oE,interval:()=>Sh,last:()=>$S,map:()=>fo,mapTo:()=>WS,max:()=>AS,merge:()=>Za,mergeMap:()=>qS,mergeMapTo:()=>zS,min:()=>bS,never:()=>IS,nothing:()=>Be,of:()=>dS,pairwise:()=>HS,pipe:()=>Ae,race:()=>Th,range:()=>ES,reduce:()=>yh,retry:()=>iy,scan:()=>Qh,setAsapScheduler:()=>cS,share:()=>Pi,shareReplay:()=>eS,skip:()=>NS,skipUntil:()=>DS,skipWhile:()=>pu,startWith:()=>Ka,subject:()=>vt,subscribe:()=>Le,sum:()=>RS,switchMap:()=>go,switchMapTo:()=>ki,take:()=>Hr,takeLast:()=>CS,takeUntil:()=>ze,takeWhile:()=>uE,tap:()=>rc,throttle:()=>MS,throwError:()=>SS,timeInterval:()=>YS,timeout:()=>ep,timer:()=>ec,toPromise:()=>ty,toReadableStream:()=>ry,withLatestFrom:()=>iS,zip:()=>rS});function Be(...i){}var iE=i=>i(),YI=i=>i;function du(){this.dispose()}var oE=()=>typeof __FASTRX_DEVTOOLS__!="undefined",ZI=1,Sr=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new fh(t,this,this.streamId++);return ht.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ls=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Be,this.error=Be,this.next=Be,this.dispose=Be,this.subscribe=Be,this.doDefer()}subscribe(t){return t instanceof Sr?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(iE),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}},pe=class extends ls{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)}},ms=class extends ls{constructor(t,e=Be,r=Be,o=Be){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Be,t instanceof Sr){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{ht.defer(s,0)}),ht.create(s),ht.pipe(s),this.sourceId=s.id,this.subscribe(t),ht.subscribe({id:s.id,end:!0}),e==Be?this._next=n=>ht.next(s,0,n):this.next=n=>{ht.next(s,0,n),e(n)},o==Be?this._complete=()=>ht.complete(s,0):this.complete=()=>{this.dispose(),ht.complete(s,0),o()},r==Be?this._error=n=>ht.complete(s,0,n):this.error=n=>{this.dispose(),ht.complete(s,0,n),r(n)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function Ae(i,...t){return t.reduce((e,r)=>r(e),i)}function xe(i,t,e){if(oE()){let r=Object.defineProperties(Object.setPrototypeOf(i,Sr.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}});ht.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof Sr&&ht.addSource(r,s)}return r}return i}function _e(i,t){return function(...e){return r=>{if(r instanceof Sr){let o=xe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,ht.pipe(o),o}else return o=>r(new i(o,...e))}}}function po(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var fh=class extends pe{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{ht.defer(this.source,this.id)})}next(t){ht.next(this.source,this.id,t),this.sink.next(t)}complete(){ht.complete(this.source,this.id),this.sink.complete()}error(t){ht.complete(this.source,this.id,t),this.sink.error(t)}},ht={addSource(i,t){po("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){po("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){po("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){po("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){po("defer",{id:i.id,streamId:t})},pipe(i){po("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){po("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=ZI++),po("create",{name:i.toString(),id:i.id})}},Ya=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var uu=class extends ls{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 Pi(){return i=>{let t=new uu(i);if(i instanceof Sr){let e=xe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,ht.pipe(e),e}return xe(t.add.bind(t),"share",arguments)}}function Za(...i){return xe(t=>{let e=new pe(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function Th(...i){return xe(t=>{let e=new Map;i.forEach(r=>{let o=new pe(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 KI(...i){return xe(t=>{let e=0,r=i.length,o=new pe(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function eS(i){return t=>{let e=new uu(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},xe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function tS(i,t,e){return xe(r=>i()?t(r):e(r),"iif",arguments)}function sE(...i){return xe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},a=(u,m)=>{let p=new pe(t);p.next=g=>{r--,p.next=E=>{s[m]=E,r===0&&t.next(s)},p.next(g)},p.complete=n,p.subscribe(u)};i.forEach(a)},"combineLatest",arguments)}function rS(...i){return xe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(a,u)=>{let m=new pe(t),p=[];o[u]=p,m.next=g=>{p.push(g),o.every(E=>E.length)&&t.next(o.map(E=>E.shift()))},m.complete=s,m.subscribe(a)};i.forEach(n)},"zip",arguments)}function Ka(...i){return t=>xe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var gh=class extends pe{constructor(t,...e){super(t);let r=new pe(this.sink);r.next=o=>this.buffer=o,r.complete=Be,r.subscribe(sE(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},iS=_e(gh,"withLatestFrom"),Eh=class extends pe{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()}},oS=_e(Eh,"bufferCount"),_h=class extends pe{constructor(t,e){super(t),this.buffer=[];let r=new pe(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Be,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},sS=_e(_h,"buffer");var nS=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 a(p){try{m(r.next(p))}catch(g){n(g)}}function u(p){try{m(r.throw(p))}catch(g){n(g)}}function m(p){p.done?s(p.value):o(p.value).then(a,u)}m((r=r.apply(i,t||[])).next())})};function vt(i){let t=arguments,e=Pi()(xe(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Be,e.complete=Be,e.error=Be,e}function nE(i){return xe(t=>t.subscribe(i()),"defer",arguments)}var yn={promise:i=>{Promise.resolve().then(i)},setImmediate:typeof setImmediate!="undefined"?i=>setImmediate(i):null,setTimeout:i=>setTimeout(i,0)},aS=()=>typeof Promise!="undefined"?yn.promise:yn.setImmediate?yn.setImmediate:yn.setTimeout,Ih=aS(),aE=i=>t=>{Ih(()=>i(t))},cS=i=>{typeof i=="function"?Ih=i:yn[i]&&(Ih=yn[i])};var cE=i=>aE(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function dS(...i){return xe(cE(i),"of",arguments)}function uS(i){return xe(cE(i),"fromArray",arguments)}function Sh(i){return xe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function ec(i,t){return xe(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 lu(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function lS(i,t){return xe(lu(i,t),"fromEventPattern",arguments)}function be(i,t){if("on"in i&&"off"in i)return xe(lu(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return xe(lu(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return xe(lu(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function dE(i){return xe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function mS(i,t){return xe(nE(()=>dE(fetch(i,t))),"fromFetch",arguments)}function hS(i){return xe(aE(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function pS(i){let t=e=>nS(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 xe(e=>{t(e)},"fromReader",arguments)}function fS(i){return xe(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 gS(){return xe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ES(i,t){return xe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function _S(i,t,...e){return xe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function TS(i,t,...e){return xe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function IS(){return xe(()=>{},"never",arguments)}function SS(i){return xe(t=>t.error(i),"throwError",arguments)}function tc(){return xe(i=>i.complete(),"empty",arguments)}var hs=class extends pe{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)}},yh=_e(hs,"reduce"),yS=i=>_e(hs,"count")((t,e)=>i(e)?t+1:t,0),AS=()=>_e(hs,"max")(Math.max),bS=()=>_e(hs,"min")(Math.min),RS=()=>_e(hs,"sum")((i,t)=>i+t,0);var Ah=class extends pe{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Qt=_e(Ah,"filter"),bh=class extends pe{next(t){}},vS=_e(bh,"ignoreElements"),Rh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},Hr=_e(Rh,"take"),vh=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=du,r.subscribe(e)}},ze=_e(vh,"takeUntil"),Ch=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):(this.doDefer(),this.complete())}},uE=_e(Ch,"takeWhile"),CS=i=>yh((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),Nh=class extends pe{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},NS=_e(Nh,"skip"),Dh=class extends pe{constructor(t,e){super(t),t.next=Be;let r=new pe(t);r.next=()=>{r.doDefer(),t.resetNext()},r.complete=du,r.subscribe(e)}},DS=_e(Dh,"skipUntil"),wh=class extends pe{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},pu=_e(wh,"skipWhile"),wS={leading:!0,trailing:!1},Mh=class extends pe{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)}},mu=class extends pe{constructor(t,e,r=wS){super(t),this.durationSelector=e,this.config=r,this._throttle=new Mh(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Be,this._throttle.complete(),super.complete()}},MS=_e(mu,"throttle"),OS={leading:!1,trailing:!0},xS=i=>_e(mu,"audit")(i,OS),Oh=class extends pe{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},hu=class extends pe{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Oh(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()}},PS=_e(hu,"debounce"),kS=i=>_e(hu,"debounceTime")(t=>ec(i)),xh=class extends pe{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.doDefer(),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()}},LS=_e(xh,"elementAt"),US=i=>t=>Hr(1)(pu(e=>!i(e))(t)),Ph=class extends pe{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},VS=_e(Ph,"findIndex"),kh=class extends pe{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.doDefer(),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()}},FS=_e(kh,"first"),Lh=class extends pe{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()}},$S=_e(Lh,"last"),Uh=class extends pe{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.doDefer(),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()}},BS=_e(Uh,"every");var Vh=class extends pe{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))}},Qh=_e(Vh,"scan"),Fh=class extends pe{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},HS=_e(Fh,"pairwise"),fu=class extends pe{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},fo=_e(fu,"map"),WS=i=>_e(fu,"mapTo")(t=>i),ps=class extends pe{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()}},fs=class i extends pe{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===i.prototype.complete&&(this.complete=this.tryComplete),r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},gu=class extends ps{},Eu=class extends fs{next(t){this.subInner(t,gu),this.next=e=>{this.currentSink.dispose(),this.subInner(e,gu)}}},go=_e(Eu,"switchMap");function Su(i){return(t,e)=>i(()=>t,e)}var ki=Su(_e(Eu,"switchMapTo")),$h=class extends ps{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},_u=class extends fs{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(),$h),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},GS=_e(_u,"concatMap"),jS=Su(_e(_u,"concatMapTo")),Bh=class extends ps{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Tu=class extends fs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Bh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},qS=_e(Tu,"mergeMap"),zS=Su(_e(Tu,"mergeMapTo")),Hh=class extends ps{dispose(){this.context.resetNext(),super.dispose()}},Iu=class extends fs{next(t){this.next=Be,this.subInner(t,Hh)}},JS=_e(Iu,"exhaustMap"),XS=Su(_e(Iu,"exhaustMapTo")),Wh=class extends pe{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=vt(),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)}},QS=_e(Wh,"groupBy"),Gh=class extends pe{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}},YS=_e(Gh,"timeInterval"),jh=class extends pe{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()}},ZS=_e(jh,"bufferTime"),qh=class extends pe{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)}},KS=_e(qh,"delay"),zh=class extends pe{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},Yh=_e(zh,"catchError"),Jh=class extends ps{tryComplete(){let t=this.context.inners.delete(this);super.dispose(),t&&this.context.checkComplete()}next(t){this.sink.next(t),this.context.expandValue(t)}},Xh=class extends fs{constructor(t,e){super(t,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(t){this.sink.next(t),this.expandValue(t)}expandValue(t){let e=new Jh(this.sink,t,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(t,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},ey=_e(Xh,"expand");var ty=()=>i=>new Promise((t,e)=>{let r;new ms(i,o=>r=o,e,()=>t(r))}),ry=()=>i=>{let t;return new ReadableStream({start(e){t=new ms(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},Le=(i=Be,t=Be,e=Be)=>r=>new ms(r,i,t,e),Zh=class extends pe{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)}))}},rc=_e(Zh,"tap"),Kh=class extends pe{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new Ya(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},ep=_e(Kh,"timeout"),iy=(i=1/0)=>t=>{if(t instanceof Sr){let e=xe(r=>{let o=i,s=new pe(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,ht.pipe(e),e}else return e=>{let r=i,o=new pe(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var An=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(An||{}),gs=class gs extends ds{constructor(e,r){super({mediaType:e,PlayerClass:r});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"sourceTrack");l(this,"enableAutoSwitchWhenRecapturing",!0);l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"recaptureMode",0);l(this,"profile");l(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){Rt(e,e).add(O.MUTE,this.onTrackMuted).add(O.UNMUTE,this.onTrackUnmuted).add(O.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===O.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){mt(e)}setStateToReady(){}capture(e,r=!1){return y(this,null,function*(){var s;let o=this.sourceTrack;try{let n=Ee();U.emit($.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(r||(s=this.sourceTrack)==null||s.stop(),a=yield Yg(e));let u=a.getTracks()[0];return yield this.setInputMediaStreamTrack(u),e.customSource||(this.sourceTrack=u,this.updateDeviceIdInUse(),this.listenDeviceChange()),U.emit($.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ee()-n}),a}catch(n){throw U.emit($.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{r&&(o==null||o.stop())}})}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}get hasFlag(){var r,o;let e=qo(((r=this.room)==null?void 0:r.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}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),Promise.all([r,new Promise((o,s)=>y(this,null,function*(){var a,u;this.hasFlag?o():Ae(be(e,"local-publish-flag-changed"),Qt(()=>this.hasFlag),ze(Za(be(this,le.INIT),be(this,"ready"))),Le(o)),!((((u=(a=this.room)==null?void 0:a.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>y(this,null,function*(){var p,g,E,A,C,N;if(!((((g=(p=this.room)==null?void 0:p.networkQuality)==null?void 0:g.uplinkNetworkQuality)||0)>3)&&(this.isPublished||this.isPublishing)&&this.isMediaTrackActive){let D=this.kind===O.AUDIO,x=this.stat.bytesSent>0;if(Q[x?"addSuccessEvent":"addFailedEvent"]({key:D?503700:513702}),!D){let Z=((A=(E=this.room)==null?void 0:E.videoCodec)==null?void 0:A.toUpperCase())||"H264",ue={H264:513704,H265:513705,VP8:513706}[Z];ue&&Q[x?"addSuccessEvent":"addFailedEvent"]({key:ue})}if(!x){if(Q.addEnum({key:D?503701:513703,value:Ko()}),We.uploadEvent({log:`stat-encode-failed-${this.kind}-${Zo()||es()}`,userId:this.userId}),this.log.warn(D?"encode failed":`${(N=(C=this.room)==null?void 0:C.videoCodec)==null?void 0:N.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield zo(5e3),this.stat.bytesSent>0||this.hasFlag)))return;this.emit("6",this),s(new de({message:`${this.strMediaType} encode failed`,code:D?q.AUDIO_ENCODE_FAILED:q.VIDEO_ENCODE_FAILED}))}}}),5e3))}))])}unpublish(){this.room&&this.room.localTracks.delete(this),U.emit($.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return y(this,null,function*(){if(this.sourceTrack&&fn){let{deviceId:e,groupId:r}=this.sourceTrack.getSettings(),{label:o}=this.sourceTrack;(yield Xg({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),Tn().then(n=>{let a=n.find(u=>{let m=u.deviceId===e;return r&&(m=m&&u.groupId===r),m});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===O.AUDIO&&!Jg(this.sourceTrack)||this.kind===O.VIDEO&&!zg(this.sourceTrack)||this._isRecapturing||e&&Lr&&It)}onTrackMuted(){if(super.onTrackMuted(),Kg(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Hs){setTimeout(()=>this.onTrackMuted(),Hs);return}this._onMuteTimeoutId=setTimeout(()=>y(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((tt||it)&&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(Pt(gs.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<Hs){setTimeout(()=>this.onTrackEnded(),Hs);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,r=!1){return y(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let o=this.sourceTrack;r||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield rr():yield ir()).find(m=>m.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),U.emit($.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),U.emit($.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{r&&(o==null||o.stop())})})}getRecoverCaptureDeviceId(){return y(this,null,function*(){let e=this instanceof lr;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(ic.get(r)||0)+1;if(ic.set(r,o),o>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield ir()).find(n=>!ic.has(n.deviceId)):(yield rr()).find(n=>!ic.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.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};te([Ze(le.INIT,"ready",{ignoreError:!0,sync:!0})],gs.prototype,"setStateToReady",1),te([us()],gs.prototype,"capture",1),te([Ze("ready","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),U.emit($.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},fail(e){let r="error";if(e.cause instanceof de){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})}}),cu(521714,!1)],gs.prototype,"publish",1),te([Me(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)})}),Ze([],"ready",{sync:!0})],gs.prototype,"unpublish",1);var Br=gs,ic=new Map;U.on($.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&ic.delete(i.track.deviceId)});var ri=class i extends Br{constructor(e){super(1,su);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"earMonitorGainNode",new _t);l(this,"_output",new _t);l(this,"codecPipeline",[]);l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});l(this,"mixedAudioReferenceMap",new Map);l(this,"isAudioContextLongSuspended",!1);this.manager=e,this.pipeline=new _n(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),U.on($.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return iu.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 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 Pt(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return y(this,arguments,function*({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s},n=!1){let u=yield Pt(i.prototype,this,"capture").call(this,{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},n);return lo(),u})}switchDevice(e){return y(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Ho){if(yield hh(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),U.emit($.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(){ot&&!ot.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ot.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){let r=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${An[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ct(this.userId,{eventId:2003,param1:6,streamType:1});let o=yield rr();o[0]?this.recapture(o[0].deviceId):r=!0}r&&ot.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(ot.off("audioInputAdded",this.handleMicrophoneAdded,this),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 a=n.getConstraints(),u=!1;!M(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,u=!0),!M(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,a.noiseSuppression=r,u=!0),!M(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,a.autoGainControl=o,u=!0),u&&(ft||It?yield n.applyConstraints(a).catch(m=>this._log.warn("update3A failed: ",m)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}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),tt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ge().createGain()),this._output.setNode(Ge().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(It||tt))return this.update3A({echoCancellation:e})}addDenoiser(e){var r;if(er<=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=za(e);if(!o)return;let s=new _t,n=Ge().createGain();n.gain.value=1;let a=new _t;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(o),a.setNode(n),this.mixedAudioReferenceMap.set(r,[s,a])}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){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(r),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,r])=>{e.deleteNode(),r.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),ot.off("audioInputAdded",this.handleMicrophoneAdded,this),ot.off("audioInputRemoved",this.handleMicrophoneRemoved,this),U.off($.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,r=!1){return y(this,null,function*(){try{yield Pt(i.prototype,this,"recapture").call(this,e,r)}catch(o){let s=(yield rr()).find(n=>n.deviceId!==e);if(s)yield Pt(i.prototype,this,"recapture").call(this,s.deviceId);else throw o}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r,ntp:fi()}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${uh/1e3} seconds, change to source audio${_r?"":", non-Safari"}`);let r=this.sourceTrack||this.mediaTrack;r&&this.setOutputMediaStreamTrack(r)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let r=this.sourceTrack||this.mediaTrack;r&&(e=r)}super.setOutputMediaStreamTrack(e)}};var Es=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 a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),a==0?o++:o=0,r.push(a);break;default:o=0,r.push(a);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 yu=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(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 a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Es(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)),a=n.reduce((E,A)=>E+A.dataView.byteLength,0),u=new ArrayBuffer(a+t.data.byteLength),m=new DataView(u),p=new DataView(t.data),g=0;for(let E=0;E<n.length;E++)for(let A=0;A<n[E].dataView.byteLength;A++)m.setInt8(g++,n[E].dataView.getInt8(A));for(let E=0;E<t.data.byteLength;E++)m.setInt8(g++,p.getInt8(E));return t.data=u,n.length}return 0}};var Eo=class Eo extends Br{constructor(e,r=4){super(r,Lt);l(this,"profile",X({},ea));l(this,"avoidCropping",!1);l(this,"_scaleResolutionDownBy");l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new yu);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(ge(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(!(!fn||!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(Ne(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,Pt(Eo.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pt(Eo.prototype,this,"setMute").call(this,e)})}capture(a){return y(this,arguments,function*({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){let u={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};if(u.facingMode==="environment"){let m=yield this.getDeviceIdWhenUsingBackCamera();m&&(u.cameraId=m)}return Pt(Eo.prototype,this,"capture").call(this,u)})}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(ge(X({},this.profile),{width:1920,height:1080})))}applyProfile(){return y(this,null,function*(){var a;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&&(kt===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:u=0,height:m=0}=(this.sourceTrack||this.mediaTrack).getSettings(),p=u*m;if(n&&p&&o&&p===o){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:O.VIDEO,videoType:O.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},r=this.sourceTrack||this.mediaTrack;return fn&&r&&Object.assign(e,r.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:cd(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)&&!this.isUseCustomSource)return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(r),U.emit($.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}})}getDeviceIdWhenUsingBackCamera(){return y(this,null,function*(){let e;try{if(Ia&&!cn&&qm){let o=(yield ir(!0)).map(n=>{var a;return ge(X({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,u;return(u=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:u.includes("environment")}),s=o[0];o.forEach(n=>{var p,g,E,A;let{capabilities:a}=n,u=(p=a.width)!=null&&p.max&&((g=a.height)!=null&&g.max)?a.width.max*a.height.max:0,m=(E=s.capabilities.width)!=null&&E.max&&((A=s.capabilities.height)!=null&&A.max)?s.capabilities.width.max*s.capabilities.height.max:0;u>m&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(r){this._log.warn("get max res camera failed",r)}return e})}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&&it&&dr&&(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&&hm&&(s.width=o?1280:720,s.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),um(Tr,"14.3")&&lm(Tr,"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&&(dr||ft)&&!Aa()&&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(){ot&&!ot.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ot.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return y(this,null,function*(){if(e.deviceId===this.deviceId){let r=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${An[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){ct(this.userId,{eventId:2003,param1:7,streamType:2});let o=yield ir();o[0]?this.recapture(o[0].deviceId):r=!0}r&&ot.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return y(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(ot.off("videoInputAdded",this.handleCameraAdded,this),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 M(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){ot.off("videoInputAdded",this.handleCameraAdded,this),ot.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return y(this,null,function*(){try{yield Pt(Eo.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield ir()).find(s=>s.deviceId!==e);if(o)yield Pt(Eo.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||M(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};te([ho(function(e){this.setContentHint(e.contentHint||"motion")})],Eo.prototype,"capture",1);var lr=Eo;var op={};hi(op,{REPORT_TYPE:()=>Ys,buildSSOPackage:()=>Ii,bytes2ms:()=>hf,calculateScaleResolutionDownNumber:()=>cd,concatArrayBuffers:()=>Rf,convertObjectNumberToInt:()=>ua,copyProperties:()=>mf,deepClone:()=>Wo,deepCloneBasic:()=>rd,deepMerge:()=>xr,delay:()=>zo,fibonacci:()=>Go,formatedTime:()=>od,getConstructorName:()=>qs,getContainerFromElement:()=>yf,getEnv:()=>df,getFirst16Bits:()=>Cf,getInternalVersion:()=>If,getLast16Bits:()=>vf,getLoggerUrl:()=>Ti,getMediaStreamTrackInfo:()=>ad,getMuteStateFromFlag:()=>qo,getNetworkType:()=>na,getNumNetworkType:()=>id,getReconnectionTimeout:()=>ff,getStringByteLength:()=>Af,getTurnServer:()=>Sf,getUint32Version:()=>sd,getValueType:()=>ut,getViewListFromView:()=>Xs,glog:()=>aa,ipv4ToUint32:()=>Js,isArray:()=>at,isAudioWorkletSupported:()=>_f,isBoolean:()=>Qe,isConstructor:()=>jo,isEmpty:()=>zs,isFunction:()=>je,isLangChinese:()=>Or,isMediaStreamTrack:()=>gf,isNumber:()=>ke,isObject:()=>ar,isOverseaSdkAppId:()=>_i,isPlainObject:()=>jt,isPortrait:()=>Zl,isPromise:()=>ro,isRemoteTrack:()=>Ef,isRotate90Or270:()=>cr,isSetSinkIdSupported:()=>Tf,isString:()=>Ne,isUndefined:()=>M,loadImage:()=>Qs,loadVideo:()=>bf,ms2bytes:()=>pf,ms2samples:()=>Yl,normalizeUrl:()=>Jo,performanceNow:()=>Ee,promiseAny:()=>ca,samples2ms:()=>Ql,setNetworkType:()=>lf,stringify:()=>Er,stringifyIncludeValue:()=>da,throttlePromise:()=>nd});var sy=[-1,-1,1,-1,-1,1,1,1],ny=[0,0,1,0,0,1,1,1];var _o=class _o extends le{constructor(e,r){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(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 Mt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&kt!==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(ny),this.positionBuffer=this.createBuffer(sy),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.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 de({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 yt&&this.render(e)||this.context instanceof Mt&&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 yt){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,a,u,m,p){let g=!M(a)&&!M(u)&&!M(m)&&!M(p);return this.ctx2d&&e?(e instanceof ImageData?(g?this.ctx2d.putImageData(e,r,o,a,u,m,p):this.ctx2d.putImageData(e,r,o),this.emit(_o.RENDER,this.ctx2d.canvas)):(g?this.ctx2d.drawImage(e,a,u,m,p,r,o,s,n):this.ctx2d.drawImage(e,r,o,s,n),this.emit(_o.RENDER,e)),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 g;let{totalFrames:e,x:r,y:o,width:s,height:n,name:a,cost:u}=this,m=Date.now(),p=(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:p,name:a,cost:u},X({parent:(g=this.input)==null?void 0:g.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.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};l(_o,"RENDER","render"),te([Ze(le.INIT,"connected",{sync:!0})],_o.prototype,"connect",1),te([Ze("connected",le.INIT,{ignoreError:!0,sync:!0})],_o.prototype,"disconnect",1),te([Ze([],"closed",{sync:!0})],_o.prototype,"close",1);var Ct=_o;var mE=Ae(Sh(250),fo(()=>performance.now()),Pi()),hE=i=>t=>{let e=0,r=performance.now();Ae(mE,fo(o=>(o-r)/i>>0),Qt(o=>o!=e?(e=o,!0):!1))(t)},Au=i=>t=>{let e=performance.now();Ae(mE,pu(r=>r-e<i),Hr(1))(t)};var cy=[0,1,1,1,0,0,1,0],_s=class extends Ct{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);l(this,"checkVisibilityChange");e instanceof Mt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(cy)}start(e){this.log.info(`${this.name} start render ${e} fps`),lt.clearTask(this._intervalId),this._intervalId=lt.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(lt.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof yt){let o=this.context.ctx.getError();o&&this.context.destroy(new de({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(Ct.RENDER,this.context._canvas),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(lt.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),lt.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),lt.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},bn=class extends _s{constructor(e,r){super(e,r);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",be(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(yi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=be(this._videoTrack,"mute"),Ae(be(this._videoTrack,"ended"),ze(this._closedOb),Le(()=>{this.context.destroy(new de({code:q.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=Ae(this._muteOb,ze(this._closedOb),ki(Au(5e3)),Qt(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Le(()=>{this.context.destroy(new de({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()}},bu=class extends bn{render(t){var r;let e=!!((r=this.input)!=null&&r.requestFrame(t));if(this.context._canvas2d){let o=this.context._canvas2d.getContext("2d");o.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),o.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Ru=class extends bn{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 oc=class extends Ct{constructor(e,r){super(e,X({name:"imageSource"},r));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);l(this,"_canvasRendered");l(this,"videoCallbackId",0);l(this,"waitingFirstFrame",!0);l(this,"shouldUpdate",!0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,kt===16&&(this._canvasRendered=vt(),Ae(this._canvasRendered,Ka(this._image),go(o=>o instanceof HTMLCanvasElement?be(o,"rendered"):tc()),ze(be(this,"closed")),Le(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Mi()&&!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 a;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!0}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,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let u=this.context.ctx;u.texSubImage2D(u.TEXTURE_2D,0,0,0,u.RGBA,u.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let u=this.context.ctx;u.texImage2D(u.TEXTURE_2D,0,u.RGBA,u.RGBA,u.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)}},sc=class extends oc{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",Ae(be(this._player,He.PLAYER_STATE_CHANGED),ze(be(this,"closed")),Qt(({state:s})=>s==="PLAYING"),Le(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},yr=class extends sc{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,e,r){super(t,new Lt({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()}},vu=class extends Ct{constructor(e,r,o){super(e,ge(X({name:"textSource"},o),{create2d:!0}));l(this,"hasChange",!0);l(this,"content","");this.ctx2d.textBaseline="top",this.content=r.content||"",r.font&&(this.font=r.font),r.color&&(this.color=r.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,r){if(!this.ctx2d)return;let{color:o,font:s}=this;super.resize(e,r),this.color=o,this.font=s}drawMultilineText(e=0,r=0,o=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);r+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),u=(n?parseInt(n[1],10):16)*o,m=this.content.split(`
|
|
32
|
+
`);for(let p=0;p<m.length;p++)this.ctx2d.fillText(m[p],e,r+p*u)}};var uy=`
|
|
35
33
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
36
34
|
attribute vec4 a_position;
|
|
37
35
|
attribute vec2 a_texCoord;
|
|
@@ -41,7 +39,7 @@ void main() {
|
|
|
41
39
|
gl_Position = a_position;
|
|
42
40
|
v_texCoord = a_texCoord;
|
|
43
41
|
}
|
|
44
|
-
`,
|
|
42
|
+
`,ly=`
|
|
45
43
|
// \u7247\u5143\u7740\u8272\u5668
|
|
46
44
|
precision mediump float;
|
|
47
45
|
varying vec2 v_texCoord;
|
|
@@ -49,32 +47,66 @@ uniform sampler2D u_texture;
|
|
|
49
47
|
|
|
50
48
|
void main() {
|
|
51
49
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var so=class extends W{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}get canvas(){return this._canvas}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 Lt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new ns(this,e)}createVideoImageSource(e,t){return new kn(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Bc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(so,"_ids",0);var iS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},as=class as extends so{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${so._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",iS),!this.ctx)throw new N({code:A.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,eS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,tS),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new N({code:A.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=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(as,"UNAVAILABLE","unavailable"),O([Ie(W.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],as.prototype,"create",1),O([Ie("created",W.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(as.UNAVAILABLE,e),this.removeAllListeners()}})],as.prototype,"destroy",1);var Pe=as,je=class extends so{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${so._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new N({code:A.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,v.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(),v.addSuccessEvent({key:512703})}};O([Ie(W.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],je.prototype,"create",1),O([Ie("created",W.INIT,{ignoreError:!0,sync:!0})],je.prototype,"destroy",1);function rS(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 ah=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}},cs=class extends He{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,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 ah(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(T=>T.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(T=>T.layout.zIndex===l&&T.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let g=this.inputs[r];E(s)||(g.layout.x=s),E(n)||(g.layout.y=n),E(a)||(g.layout.width=a),E(c)||(g.layout.height=c),E(h)||(g.layout.rotation=h),E(m)||(g.layout.hidden=m),u&&(g.layout.fillMode=u),!E(l)&&l!==g.layout.zIndex&&(g.layout.zIndex=l,this.inputs.sort((T,_)=>T.layout.zIndex-_.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 Pe&&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){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=rS(r.node.width,r.node.height,r.width,r.height,r.fillMode,It(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.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},D({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 Pe)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var oS=[1,0,0,0,1,1,0,1],Pt=class extends He{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 Pe)try{this.setTexBuffer(oS)}catch(n){e.destroy(new N({code:A.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}resize(e,t){It(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var no=class extends si{constructor(e,t=4){super(t,Ye);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,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(He.RENDER,r=>{this.emit("render",r)}),this.mixNode=new cs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=ie.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new je({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)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}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*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ot&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){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");t.recaptureMode=1,Fe(this,Ae).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;Qe===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(Qe===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Lt){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 Lt)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 Pt(this.videoContext,this.log,s,n);a=e.connect(a),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 Pt&&(E(r)||(n.mirror=r),E(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Pt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Pt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Pt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Pt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Pt&&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(),ie.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.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Ne(this);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 Fc=Ks();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Fc,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var sS=function(o){return f(this,null,function*(){let i=null,e=cS(o);y.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Go&&We<74||ke||te)&&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 nS(r,o.captureElement))}if(o.audio){let s=aS(o);y.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function nS(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)===Fc))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){y.warn(`cropTo target failed ${t}`)}})}function aS(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 cS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:ke?{max:o.width}:{ideal:o.width,max:o.width},height:ke?{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 Kp=sS;var st=class extends qe{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 Fc===((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 Kp({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 N?h:new N({code:A.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};O([gt(function(e){this.setContentHint(e.contentHint||"detail")})],st.prototype,"capture",1);var Ci=class extends vt{constructor(i){super(i),this._log.id=`s-${this._log.id}`}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var dS='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}});',ch;function xn(o,i=48e3,e=1,t){return f(this,null,function*(){let r=pe("dump");ch||(ch=zi(r,URL.createObjectURL(new Blob([dS],{type:"application/javascript"})))),yield ch;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 Hc=class extends mc{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 g=URL.createObjectURL(new Blob(n[m])),T=document.createElement("a");T.href=g,T.download=`${r[m]}.pcm`,T.style.display="none",document.body.appendChild(T),T.click(),URL.revokeObjectURL(g),T.remove()}clearTimeout(a),s.abort("download")},l=xn(t).then(m=>m.pipeTo(new WritableStream({write(g){g.forEach((T,_)=>n[_]=n[_]?n[_].concat(T[0]):[T[0]])}}),s).catch(g=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var R,q,H;if(typeof WritableStream=="undefined"){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,g=0,T=new AbortController,_=t===""?(R=this._localAudioTrack)==null?void 0:R.mediaTrack:(H=(q=this.room)==null?void 0:q.remotePublishedUserMap.get(t))==null?void 0:H.remoteAudioTrack.mediaTrack;if(!_){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let S=pe().createMediaStreamSource(new MediaStream([_]));return xn([S],s,n,a).then(Ee=>Ee.pipeTo(new WritableStream({write(fe){fe[0][0]&&(g+fe[0][0].length>c?(l.set(fe[0][0].subarray(0,c-g),g),h=fe[0][0].subarray(c-g),fe[0][1]&&(u.set(fe[0][1].subarray(0,c-g),g),m=fe[0][1].subarray(c-g)),g+=c-g):(h&&(l.set(h,g),g+=h.length,h=void 0),m&&(u.set(m,g),m=void 0),l.set(fe[0][0],g),fe[0][1]&&u.set(fe[0][1],g),g+=fe[0][0].length),g>=c&&(g=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),T).catch(fe=>this.log.warn(`stop getPCM reason:${fe}`))),T}get hasScreenAudioTrack(){return!E(this._localScreenAudioTrack)}get hasAudioTrack(){return!E(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof Ci)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof vt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof ni)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 Ci?delete this._localScreenAudioTrack:e instanceof vt?delete this._localAudioTrack:e instanceof ni}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0: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){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}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(){I.on("113",this.handleLocalTrackStarted,this),I.on("114",this.handleLocalTrackStopped,this),I.on("115",this.handleRemoteTrackStarted,this),I.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){I.off("113",this.handleLocalTrackStarted),I.off("114",this.handleLocalTrackStopped),I.off("115",this.handleRemoteTrackStarted),I.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 $c(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new N({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||y).warn(c),i===2?n(c):i===1&&s()},o*1e3);e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a)})})})}var Ri=class Ri extends Qr{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",ct(ue(this,Ri.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new W(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new W(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),le(bn(ue(this,W.STATECHANGED),ue(this.remotePublishState,W.STATECHANGED)),On(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Re(c=>{this.availableState.state!==(c?W.ON:W.OFF)&&(this.availableState.state=c?W.ON:W.OFF),this.updatePlayingState(c)}));let s=le(ue(this.player,ae.ERROR),xt(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=le(Nn(5e3),xt(()=>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=le(Iu(s,n),Le(ue(this,W.INIT)));le(this._triggerCheckDecodeSubject,xt(()=>!this.ignoreDecodeError),io(a),Re(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===Ri.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===W.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(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:Xo[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Fr()}),re.uploadEvent({log:`stat-decode-failed-${this.kind}-${Gi()||Wi()}`,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?W.ON:W.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Ri,"STATE_SUBSCRIBE","subscribe"),O([$c(5,1)],Ri.prototype,"waitHasMediaTrack",1),O([Ie(W.INIT,Ri.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),I.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Tt(521716,!1)],Ri.prototype,"subscribe",1),O([Ie(Ri.STATE_SUBSCRIBE,W.INIT,{sync:!0,success(){this.log.info("unsubscribed"),I.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Ri.prototype,"unsubscribe",1);var ds=Ri;var ni=class extends ds{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 zr.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&nc().AudioDecoder&&ii:!1}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};function uS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var yi=class extends ds{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:Qe===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new je({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new oo(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Xr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=uS(t);if(!X(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)}},ls=class extends yi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var us=new Map;I.on(C.JOIN_SUCCESS,({room:o})=>{ye(o.userId,{eventId:32788})});I.on(C.LEAVE_START,({room:o})=>{ye(o.userId,{eventId:32789})});I.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),ye(o.room.userId,{eventId:i})}});I.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),ye(o.room.userId,{eventId:i})}});I.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ye(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):ye(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});I.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===p.AUDIO?ye(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):ye(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});I.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ye(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&ye(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&ye(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});I.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&ye(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&ye(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&ye(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});I.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&ye(o.room.userId,{eventId:o.kind===p.VIDEO?32780:32781})});I.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&ye(o.room.userId,{eventId:o.kind===p.VIDEO?32782:32783})});I.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&&ye(o.userId,{eventId:t})});I.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&&ye(o.userId,{eventId:s,remoteUserId:t})});I.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),ye(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});I.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)),ye(o.userId,e)}});function ye(o,i){let e=x(D({},i),{timestamp:ki()});us.has(o)?us.get(o).push(e):us.set(o,[e])}function ef(o){if(us.has(o)){let i=us.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 us.delete(o),i}return[]}function tf(...o){return Q((i,e)=>function(...t){return hS.call(this,o,t,e,this._name),i.apply(this,t)})}function hS(o,i,e,t){try{if(Ce(o))for(let r=0;r<o.length;r++)Gc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Gc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw y.error(r),r}}function Gc({rule:o,value:i,key:e,fnName:t,className:r}){if(E(i)){if(o.required)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.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),ee(o.type[c])&&ve(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>Lr(c)?Ro(c):ee(c)?c:ve(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!E(o.type)&&ve(i)!==o.type)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=X(i)&&(i===0||Number.isNaN(i)),c=ee(i)&&i.trim()==="";if(a||c)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&X(i)&&i<0)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.min)&&X(i)&&i<o.min)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!E(o.max)&&X(i)&&i>o.max)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ee(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.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 N({code:A.INVALID_PARAMETER,message:B({key:V.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 N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;rt(s)&&Et(i)&&Object.keys(s).forEach(a=>{Gc.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;rt(n)&&Ce(i)&&i.forEach((a,c)=>{Gc.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 rf=Ge(tt(),1);var Wc=class extends rf.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+=`:${Hd[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){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Wt(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:Wt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function dh({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return I.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 N({code:A.INVALID_OPERATION,message:B({key:V.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 mS="2025-10-14 17:54:52",of=!0,sf=function(){var o;if(of){of=!1,y.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${li}/en/index.html`),console.info(`* Changelog: ${li}/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:",Ve),Qt||y.debug("Build Time:",mS);let i=`UA: ${navigator.userAgent}
|
|
53
|
-
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Tl()}`,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":""}`),Br().then(t=>{t&&y.info(qt)})}};var ao={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},Nt=(b=>(b[b.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",b[b.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",b[b.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",b[b.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",b[b.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",b[b.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",b[b.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",b[b.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",b[b.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",b[b.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",b[b.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",b[b.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",b[b.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",b[b.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",b[b.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",b[b.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",b[b.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",b[b.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",b[b.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",b[b.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",b[b.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",b[b.INVALID_OPERATION=5100]="INVALID_OPERATION",b[b.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",b[b.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",b[b.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",b[b.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",b[b.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",b[b.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",b[b.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",b[b.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",b[b.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",b[b.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",b[b.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",b[b.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",b[b.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",b[b.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",b[b.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",b[b.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",b[b.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",b[b.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",b[b.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",b[b.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",b[b.DEVICE_ERROR=5300]="DEVICE_ERROR",b[b.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",b[b.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",b[b.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",b[b.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",b[b.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",b[b.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",b[b.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",b[b.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",b[b.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",b[b.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",b[b.SERVER_ERROR=5400]="SERVER_ERROR",b[b.NEED_TO_BUY=5401]="NEED_TO_BUY",b[b.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",b[b.OPERATION_FAILED=5500]="OPERATION_FAILED",b[b.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",b[b.REJOIN_FAILED=5502]="REJOIN_FAILED",b[b.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",b[b.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",b[b.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",b[b.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",b[b.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",b[b.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",b[b.OPERATION_ABORT=5998]="OPERATION_ABORT",b[b.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",b))(Nt||{});function af({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=Nt[o];try{r=nf[s]}catch(n){r=nf.UNKNOWN_ERROR}return ne(r)?t=r(i):ee(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var nf=x(D({},Je),{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: ${ve(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: ${ve(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=co(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=co(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=co(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=co(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=co(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=co(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=co(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 co(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var lh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=af({code:e===U.SERVER_ERROR?e:t||e,params:D({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=Nt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},g=document.createElement("a");Vr?g.href=`ms-settings:privacy-${m[this.functionName]}`:zt&&(g.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),g.href.length>0&&g.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof N){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===A.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Je.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case A.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case A.SERVER_TIMEOUT:case A.SWITCH_ROLE_FAILED:case A.SWITCH_ROOM_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case A.DEVICE_NOT_FOUND:case A.DEVICE_AUTO_RECOVER_FAILED:case A.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=pS(e.name));break;case A.VIDEO_ENCODE_FAILED:a.extraCode=5505;case A.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=U.OPERATION_FAILED;break;case A.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 pS(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 L=lh;function bi(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function Ln(o){return o===ao.QOS_PREFERENCE_CLEAR?"detail":o===ao.QOS_PREFERENCE_SMOOTH?"motion":""}function hs(o,i){let e=i?wd:cr;return nl(o)?D(D({},e),o):Ft[o]?Ft[o]:e}var cf={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}}},df={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}}},ms={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ee(o)&&!document.getElementById(o))throw new L({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},lf={name:"userId",required:!0,type:"string"},uf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function ps(o,i){if(!o)throw new L({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function hf(o,i,e){if(!o)throw new L({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function mf(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new L({code:U.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function pf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new L({code:U.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Zw={type:"number",notLessThanZero:!0},fS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function ff(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!sc()){y.warn("small stream is not supported"),delete o.option.small;return}let i=hs(o.option.profile),e=hs(o.option.small,!0);if(!fS(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 _S={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 L({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ee(o.roomId))throw new L({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});mf(o.roomId,e,i)}else if(o.strRoomId)pf(o.strRoomId,e,i);else throw new L({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:ms,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:cf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&ji())throw new L({code:U.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&ff(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:x(D({},ms),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:cf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&ff(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:uf},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&ji())throw new L({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:uf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ms,publish:{type:"boolean"},option:df},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(ji())throw new L({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!nn())throw new L({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ms,publish:{type:"boolean"},option:df}},muteRemoteAudio:[lf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[lf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ms,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){ps(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(hf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:x(D({},ms),{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){ps(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(hf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({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 L({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){ps(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(!dn)throw new L({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new L({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new L({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new L({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});ps(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 L({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 L({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new L({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(ps(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new L({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(ps(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new L({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 L({code:U.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)mf(o.roomId,e,i);else if(o.strRoomId)pf(o.strRoomId,e,i);else throw new L({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}}}},$e={TRTC:_S};var nt=class extends Error{};function gS(o,i){let e=kr(o);for(let t=0;t<i.length;t++)Jt(e[t],i[t]);return e}function TS(o){this._resolve=Promise.resolve(o)}function ES(o){this._reject=Promise.reject(o)}var Ar=class Ar{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",gS);let t=Ar.instances.get(i);t?t.set(e,this):Ar.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Ar.instances.get(i);return t&&t.get(e)||new Ar(i,e)}static gets(i,e){let t=Ar.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 nt("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:TS,reject:ES};try{switch(this.state){case 1:if(i===0)throw new nt("already started");break;case 4:if(i===2)throw new nt("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 nt("already start");break;case 3:switch(i.type){case 2:throw new nt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new nt("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new nt("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 nt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new nt("start not allowed after update");case 0:throw new nt("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new nt("keep start")),new nt("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(Ar,"instances",new WeakMap);var er=Ar;var qc=new WeakMap,jc=(o,i)=>{if(i instanceof nt){let{stack:e}=i;i=new L({code:U.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
|
-
|
|
56
|
-
|
|
50
|
+
} `;var Ts=class extends le{constructor(e){super();l(this,"frameRate");l(this,"_canvas");l(this,"log");l(this,"hasAlpha",!1);l(this,"name");l(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}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 yr(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new bn(this,e)}createVideoImageSource(e,r){return new oc(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new sc(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}createTextSource(e,r){return new vu(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};l(Ts,"_ids",0);var my={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Rn=class Rn extends Ts{constructor(){super(...arguments);l(this,"defaultProgam");l(this,"defaultVShader");l(this,"defaultFShader");l(this,"ctx");l(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ts._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",my),!this.ctx)throw new de({code:q.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,uy),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ly),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new de({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,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,r),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=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}};l(Rn,"UNAVAILABLE","unavailable"),te([Ze(le.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})}})],Rn.prototype,"create",1),te([Ze("created",le.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Rn.UNAVAILABLE,e),this.removeAllListeners()}})],Rn.prototype,"destroy",1);var yt=Rn,Mt=class extends Ts{constructor(){super(...arguments);l(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Ts._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new de({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})}};te([Ze(le.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})}})],Mt.prototype,"create",1),te([Ze("created",le.INIT,{ignoreError:!0,sync:!0})],Mt.prototype,"destroy",1);function hy(i,t,e,r,o,s=!1){s&&([e,r]=[r,e]);let n={sWidth:i,sHeight:t,dWidth:e,dHeight:r,sx:0,sy:0,dx:0,dy:0};if(i===0||t===0)return n;switch(o){case void 0:case"fill":break;case"contain":{let a=Math.min(e/i,r/t);n.dWidth=i*a,n.dHeight=t*a,n.dx=(e-n.dWidth)/2,n.dy=(r-n.dHeight)/2;break}case"cover":{let a=Math.max(e/i,r/t),u=e/a,m=r/a;n.sx=(i-u)/2,n.sy=(t-m)/2,n.sWidth=u,n.sHeight=m;break}}return n}var np=class{constructor(t,e){this.node=t;this.layout=e;l(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},vn=class extends Ct{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});l(this,"inputs",[]);l(this,"backgroundColor","black")}addInput(e,r){let o=0,s=this.inputs.length;for(;o<s;){let a=Math.floor((o+s)/2);if(this.inputs[a].layout.zIndex<r.zIndex)o=a+1;else if(this.inputs[a].layout.zIndex>r.zIndex)s=a;else throw new Error(`input already exists at zIndex ${r.zIndex}`)}let n=new np(e,r);this.inputs.splice(o,0,n)}changeInputLayout(e,r){let o=this.inputs.findIndex(C=>C.node===e);if(o<0)return;let{x:s,y:n,width:a,height:u,zIndex:m,fillMode:p,rotation:g,hidden:E}=r;if(!M(m)&&this.inputs.some(C=>C.layout.zIndex===m&&C.node!==e))throw new Error(`input already exists at zIndex ${r.zIndex}`);let A=this.inputs[o];M(s)||(A.layout.x=s),M(n)||(A.layout.y=n),M(a)||(A.layout.width=a),M(u)||(A.layout.height=u),M(g)||(A.layout.rotation=g),M(E)||(A.layout.hidden=E),p&&(A.layout.fillMode=p),!M(m)&&m!==A.layout.zIndex&&(A.layout.zIndex=m,this.inputs.sort((C,N)=>C.layout.zIndex-N.layout.zIndex))}hasInput(e){return this.inputs.some(r=>r.node===e)}hasNoInput(){return this.inputs.length===0}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 yt&&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.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(r=>r.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>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.forEach(r=>r.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];if(o.hidden)continue;let s=hy(o.node.width,o.node.height,o.width,o.height,o.fillMode,cr(o.rotation));this.draw2d(o.node.image,o.x+s.dx,o.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,r,o,s,n=!1){this.ctx2d&&(n&&([o,s]=[s,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,r,o,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:a}=this,u=Date.now(),m=(e-this.lastInfo.totalFrames)/((u-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:u,fps:m,name:a},X({parent:this.inputs.filter(p=>p).map(p=>p.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var r;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof yt)try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}close(){super.close(),this.removeAllInputs()}};var py=[1,0,0,0,1,1,0,1],Ar=class extends Ct{constructor(e,r,o,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:r});l(this,"mirror",!1);l(this,"rotation",0);if(o&&(this.mirror=o),s&&(this.rotation=s),e instanceof yt)try{this.setTexBuffer(py)}catch(n){e.destroy(new de({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.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,r,o,s,n);return this.ctx2d.restore(),a}return!1}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,r){cr(this.rotation)&&([e,r]=[r,e]),super.resize(e,r)}};var Is=class extends Br{constructor(e,r=4){super(r,Lt);l(this,"inputLocalVideoTracks",new Map);l(this,"inputLocalScreenTracks",new Map);l(this,"cameraNodeMap",new Map);l(this,"screenNodeMap",new Map);l(this,"textNodeMap",new Map);l(this,"imageNodeMap",new Map);l(this,"videoNodeMap",new Map);l(this,"endedIds",new Set);l(this,"videoContext");l(this,"mixNode");l(this,"destination");l(this,"manager");l(this,"stat");l(this,"_checkId",0);l(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ct.RENDER,o=>{this.emit("render",o)}),this.mixNode=new vn(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=lt.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Mt({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let r of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])r.shouldUpdate=!1;setTimeout(()=>{var r;return(r=this.destination)==null?void 0:r.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,r=0,o=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>r){if(this.endedIds.has(n)){let u=this.cameraNodeMap.get(n);u&&u.image.cancelVideoFrameCallback(u.videoCallbackId);continue}r=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>r){if(this.endedIds.has(n)){let u=this.screenNodeMap.get(n);u&&u.image.cancelVideoFrameCallback(u.videoCallbackId);continue}r=a.profile.frameRate,e=n,o=!1}if(e!==null){let n=o?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",r)}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,r){var o;(o=this.mixNode)==null||o.resize(e,r)}startMix(){return y(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),_r&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,r,o){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}=r;if(!s)throw new Error("no mediaTrack, add cameraSource failed");r.recaptureMode=1,Rt(this,ot).add("videoInputRemoved",a=>{a.deviceId===r.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),r.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,o,r.mediaTrack)});let n;kt===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(r.settings.width,r.settings.height),n.shouldUpdate=!1,this._connectMix(n,o,"cover"),this.inputLocalVideoTracks.set(e,r),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,r,o){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}=r;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(r.settings.width,r.settings.height),n.shouldUpdate=!1,this._connectMix(n,o),this.inputLocalScreenTracks.set(e,r),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:r,content:o="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(r))throw new Error(`There is already a textSource with the same ID: ${r}`);let u=this.videoContext.createTextSource({content:o,font:s,color:n});u.resize(a.width,a.height),this._connectMix(u,a),this.textNodeMap.set(r,u)}addImageSource(e,r,o){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(r,{autoResize:!1,logger:this.log});s.resize(r.width,r.height),this._connectMix(s,o),this.imageNodeMap.set(e,s)}addVideoSource(e,r,o){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(r,{autoResize:!1,logger:this.log});s.resize(r.videoWidth,r.videoHeight),s.shouldUpdate=!1,this._connectMix(s,o),this.videoNodeMap.set(e,s)}updateCameraSource(e,r,o=null,s){let n=this.cameraNodeMap.get(e);if(n){if(o){if(kt===16&&o instanceof CanvasCaptureMediaStreamTrack)if(n instanceof yr){let m=n.output;n.close(),n=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(m),this.cameraNodeMap.set(e,n)}else n.image=o.canvas;else if(n instanceof yr)n.replaceTrack(o);else{let m=n.output;n.close(),n=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),n.connect(m),this.cameraNodeMap.set(e,n)}let{width:a,height:u}=o.getSettings();a&&u&&n.resize(a,u)}s&&n.resize(s.width,s.height),(s||o)&&this.setFpsAuto(),this._changeMixLayout(n,r)}}updateScreenSource(e,r){let o=this.screenNodeMap.get(e);o&&this._changeMixLayout(o,r)}updateTextSource(e){let{id:r,content:o,font:s,color:n,layout:a}=e,u=this.textNodeMap.get(r);u&&(M(o)||(u.content=o),M(s)||(u.font=s),M(n)||(u.color=n),u.resize(a.width,a.height),this._changeMixLayout(u,a))}updateImageSource(e,r,o){let s=this.imageNodeMap.get(e);s&&(o&&(s.image=o,s.resize(o.width,o.height)),this._changeMixLayout(s,r))}updateVideoSource(e,r,o){let s=this.videoNodeMap.get(e);if(s){if(o){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=o,s.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(s,r)}}_connectMix(e,r,o="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=r;e.disconnect();let a=new Ar(this.videoContext,this.log,s,n);a=e.connect(a),r.fillMode||(r.fillMode=o),a.connect(this.mixNode,r)}_changeMixLayout(e,r){if(!this.mixNode)return;let{mirror:o,rotation:s}=r,n=e.output||e;n instanceof Ar&&(M(o)||(n.mirror=o),M(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,r)}removeCameraSource(e){let r=this.inputLocalVideoTracks.get(e);if(!r)return;r.close(),this.inputLocalVideoTracks.delete(e);let o=this.cameraNodeMap.get(e);o&&(o.output instanceof Ar&&o.output.close(),o.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let r=this.inputLocalScreenTracks.get(e);if(!r)return;r.close(),this.inputLocalScreenTracks.delete(e);let o=this.screenNodeMap.get(e);o&&(o.output instanceof Ar&&o.output.close(),o.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let r=this.textNodeMap.get(e);r&&(r.output instanceof Ar&&r.output.close(),r.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let r=this.imageNodeMap.get(e);r&&(r.output instanceof Ar&&r.output.close(),r.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let r=this.videoNodeMap.get(e);r&&(r.output instanceof Ar&&r.output.close(),r.image instanceof HTMLVideoElement&&this.stopVideoElement(r.image),r.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(),lt.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let r of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])r.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),mt(this);for(let r of this.videoNodeMap.values())r.image instanceof HTMLVideoElement&&this.stopVideoElement(r.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var Cu=Ra();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Cu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var fy=function(i){return y(this,null,function*(){let t=null,e=_y(i);F.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(dn&&er<74||It||ft)&&F.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){F.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield gy(o,i.captureElement))}if(i.audio){let s=Ey(i);F.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function gy(i,t){return y(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&je(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===Cu))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){F.warn(`cropTo target failed ${r}`)}})}function Ey(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return M(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function _y(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 pE=fy;var ii=class extends lr{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,r;try{return Cu===((r=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:r.handle)}catch(o){return}}capture(p){return y(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:u,preferDisplaySurface:m}){try{let g;return a||n?(g=new MediaStream,a&&g.addTrack(a),n&&g.addTrack(n)):(g=yield pE({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:u,preferDisplaySurface:m}),this.sourceTrack=g.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(g.getVideoTracks()[0]),g}catch(g){throw this.log.error(`getDisplayMedia error observed ${g}`),g instanceof de?g:new de({code:q.INITIALIZE_FAILED,name:g.name,message:g.message})}})}switchDevice(e){return y(this,null,function*(){throw new Error("Method not implemented.")})}};te([ho(function(e){this.setContentHint(e.contentHint||"detail")})],ii.prototype,"capture",1);var Ss=class extends ri{constructor(t){super(t),this._log.id=`s-${this._log.id}`}addAudioProcessor(t,e,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(t),this.enableTrackAEC(!1)}removeAudioProcessor(t){this.pipeline.aec.node===t&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var Ty='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}});',ap;function nc(i,t=48e3,e=1,r){return y(this,null,function*(){let o=Ge("dump");ap||(ap=xi(o,URL.createObjectURL(new Blob([Ty],{type:"application/javascript"})))),yield ap;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((a,u)=>a.connect(n,0,u)),new ReadableStream({start(a){n.port.onmessage=u=>{a.enqueue(u.data)}},cancel(){i.forEach(a=>a.disconnect(n)),n.port.close()}})})}var Nu=class extends tu{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",F.createLogger({id:"am"}));l(this,"denoiser");l(this,"voiceChanger");l(this,"mixChangedDebounce");l(this,"audioProcessor");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);l(this,"getPCMAbortCtrlMap",new Map);l(this,"audioFrameEventConfigMap",new Map);l(this,"audioReferenceMap",new Map);l(this,"isLocalAudioNeedAudioProcess",!1);l(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 p,g;if(!this._localAudioTrack)return;let r=[],o=[];(p=this._localAudioPipline)!=null&&p.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(g=this._localAudioPipline)!=null&&g.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=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),u=()=>{for(let E=0;E<o.length;E++){let A=URL.createObjectURL(new Blob(n[E])),C=document.createElement("a");C.href=A,C.download=`${o[E]}.pcm`,C.style.display="none",document.body.appendChild(C),C.click(),URL.revokeObjectURL(A),C.remove()}clearTimeout(a),s.abort("download")},m=nc(r).then(E=>E.pipeTo(new WritableStream({write(A){A.forEach((C,N)=>n[N]=n[N]?n[N].concat(C[0]):[C[0]])}}),s).catch(A=>u));return{then:m.then.bind(m),download:u}}getPCM(e,r){var x,Z,ue;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:o,sampleRate:s=48e3,channelCount:n=1,port:a}=(r===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(r)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info(`getPCM ${r||"local"}`);let u=Math.floor(s*.04),m=new Float32Array(u),p=new Float32Array(u),g,E,A=0,C=new AbortController,N=r===""?(x=this._localAudioTrack)==null?void 0:x.mediaTrack:(ue=(Z=this.room)==null?void 0:Z.remotePublishedUserMap.get(r))==null?void 0:ue.remoteAudioTrack.mediaTrack;if(!N){this.log.info(`getPCM failed: ${r||"local"} has no audio track`);return}let D=Ge().createMediaStreamSource(new MediaStream([N]));return nc([D],s,n,a).then(Se=>Se.pipeTo(new WritableStream({write(Ye){Ye[0][0]&&(A+Ye[0][0].length>u?(m.set(Ye[0][0].subarray(0,u-A),A),g=Ye[0][0].subarray(u-A),Ye[0][1]&&(p.set(Ye[0][1].subarray(0,u-A),A),E=Ye[0][1].subarray(u-A)),A+=u-A):(g&&(m.set(g,A),A+=g.length,g=void 0),E&&(p.set(E,A),E=void 0),m.set(Ye[0][0],A),Ye[0][1]&&p.set(Ye[0][1],A),A+=Ye[0][0].length),A>=u&&(A=0,e({userId:r,sampleRate:s,channelCount:n,data:n===1?m:[m,p]}),m=new Float32Array(u),p=new Float32Array(u)))}}),C).catch(Ye=>this.log.warn(`stop getPCM reason:${Ye}`))),C}get hasScreenAudioTrack(){return!M(this._localScreenAudioTrack)}get hasAudioTrack(){return!M(this._localAudioTrack)}changeInput(e){var r,o;if(e instanceof Ss)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof ri)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((o=this.audioProcessor)!=null&&o.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof Li)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 Ss?delete this._localScreenAudioTrack:e instanceof ri?delete this._localAudioTrack:e instanceof Li}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}addAudioProcessor(e,r,o,s){var n;this.audioProcessor={localAudioWorkletNode:o,mixNode:e,silentNode:r,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,e,r),this.audioReferenceMap.forEach((a,u)=>{var m;(m=this._localAudioTrack)==null||m.mixAudioReference(a,u)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,r),this.audioReferenceMap.forEach((a,u)=>{var m;(m=this._localScreenAudioTrack)==null||m.mixAudioReference(a,u)}))}removeDenoiser(e){var r;return delete this.denoiser,(r=this._localAudioTrack)==null?void 0: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){var o,s;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(r)}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 a;(a=this.room)==null||a.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(a=>{var u;(u=this.room)==null||u.emit("audio-frame",a)},""),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(){U.on("113",this.handleLocalTrackStarted,this),U.on("114",this.handleLocalTrackStopped,this),U.on("115",this.handleRemoteTrackStarted,this),U.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){U.off("113",this.handleLocalTrackStarted),U.off("114",this.handleLocalTrackStopped),U.off("115",this.handleRemoteTrackStarted),U.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||M(s))return;this.setAudioReferenceVolume(o,s)}}};function fE(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let a=setTimeout(()=>{let u=new de({code:q.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});(this.log||this._log||F).warn(u),t===2?n(u):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(a)})})})}var oi=class oi extends ds{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"availableState");l(this,"remotePublishState");l(this,"_triggerCheckDecodeSubject",vt(be(this,oi.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new le(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new le(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),Ae(Za(be(this,le.STATECHANGED),be(this.remotePublishState,le.STATECHANGED)),fo(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Le(u=>{this.availableState.state!==(u?le.ON:le.OFF)&&(this.availableState.state=u?le.ON:le.OFF),this.updatePlayingState(u)}));let s=Ae(be(this.player,He.ERROR),Qt(u=>u.code===MediaError.MEDIA_ERR_DECODE)),n=Ae(ec(5e3),Qt(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===O.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=Ae(Th(s,n),ze(be(this,le.INIT)));Ae(this._triggerCheckDecodeSubject,Qt(()=>!this.ignoreDecodeError),ki(a),Le(u=>{this.reportDecodeResult(!1,u)}))}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===oi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===le.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){var s,n;let o=this.kind===O.AUDIO;if(Q[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),!o){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";Q[e?"addSuccessEvent":"addFailedEvent"]({key:pn[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(Q.addEnum({key:o?504701:514703,value:Ko()}),We.uploadEvent({log:`stat-decode-failed-${this.kind}-${Zo()||es()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===O.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?le.ON:le.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};l(oi,"STATE_SUBSCRIBE","subscribe"),te([fE(5,1)],oi.prototype,"waitHasMediaTrack",1),te([Ze(le.INIT,oi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),U.emit($.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),cu(521716,!1)],oi.prototype,"subscribe",1),te([Ze(oi.STATE_SUBSCRIBE,le.INIT,{sync:!0,success(){this.log.info("unsubscribed"),U.emit($.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],oi.prototype,"unsubscribe",1);var Cn=oi;var Li=class extends Cn{constructor(e,r){super(e,r,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return iu.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,r;return this.manager?this.manager.decodePipeline.some(o=>o)||((r=(e=this.player.element)==null?void 0:e.error)==null?void 0:r.code)===MediaError.MEDIA_ERR_DECODE&&Xd().AudioDecoder&&ns:!1}decodeFrame(e){if(!this.manager)return e;let r=e;for(let[o,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:u,hasLeavingTag:m})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:u,hasLeavingTag:m})}),r=s(n),!r)return}return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};function Sy(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var To=class extends Cn{constructor(e,r,o=4){super(e,r,o);l(this,"mediaType",4);l(this,"source");l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,r){return(Qe(r==null?void 0:r.canvasRender)?r.canvasRender:kt===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 Mt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new _s(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),Mi()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=Sy(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(a=>a.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(a=>a.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)}},Du=class extends To{constructor(e,r){super(e,r,2);l(this,"mediaType",2);l(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Nn=new Map;U.on($.JOIN_SUCCESS,({room:i})=>{ct(i.userId,{eventId:32788})});U.on($.LEAVE_START,({room:i})=>{ct(i.userId,{eventId:32789})});U.on($.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),ct(i.room.userId,{eventId:t})}});U.on($.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),ct(i.room.userId,{eventId:t})}});U.on($.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===O.AUDIO?ct(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):ct(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});U.on($.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===O.AUDIO?ct(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):ct(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});U.on($.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&ct(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&ct(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&ct(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});U.on($.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&ct(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&ct(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&ct(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});U.on($.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&ct(i.room.userId,{eventId:i.kind===O.VIDEO?32780:32781})});U.on($.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&ct(i.room.userId,{eventId:i.kind===O.VIDEO?32782:32783})});U.on($.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&&ct(i.userId,{eventId:r})});U.on($.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&&ct(i.userId,{eventId:s,remoteUserId:r})});U.on($.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let a=o?1:0;s||(a=o?3:2);let u={H264:0,H265:1,VP8:2}[r.toUpperCase()],m={eventId:4004,param1:a,param2:u,streamType:n||2};e&&(m.remoteUserId=e,m.eventId=4005),ct(t,m),Q.addEnum({key:e?514701:513701,value:a}),Q.addEnum({key:e?514700:513700,value:u})});U.on($.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===O.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),ct(i.userId,e)}});function ct(i,t){let e=ge(X({},t),{timestamp:fi()});Nn.has(i)?Nn.get(i).push(e):Nn.set(i,[e])}function gE(i){if(Nn.has(i)){let t=Nn.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 Nn.delete(i),t}return[]}function EE(...i){return Me((t,e)=>function(...r){return yy.call(this,i,r,e,this._name),t.apply(this,r)})}function yy(i,t,e,r){try{if(at(i))for(let o=0;o<i.length;o++)wu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else wu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}catch(o){throw F.error(o),o}}function wu({rule:i,value:t,key:e,fnName:r,className:o}){if(M(t)){if(i.required)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(M(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let a=!1;for(let u=0;u<i.type.length;u++)i.type[u]===null&&t===null&&(a=!0),je(i.type[u])&&t instanceof i.type[u]&&(a=!0),Ne(i.type[u])&&ut(t)===i.type[u].toLowerCase()&&(a=!0);if(!a)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:i.type.map(u=>jo(u)?qs(u):Ne(u)?u:ut(u))},fnName:r,value:t},link:{className:o,fnName:r}})})}else if(!M(i.type)&&ut(t)!==i.type)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_TYPE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.allowEmpty===!1){let a=ke(t)&&(t===0||Number.isNaN(t)),u=Ne(t)&&t.trim()==="";if(a||u)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_EMPTY,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}if(i.notLessThanZero&&ke(t)&&t<0)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!M(i.min)&&ke(t)&&t<i.min)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_MIN,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!M(i.max)&&ke(t)&&t>i.max)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_MAX,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(Ne(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}else if(je(i.instanceOf)&&!(t instanceof i.instanceOf))throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.values&&!i.values.includes(t))throw new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_RANGE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});let{properties:s}=i;jt(s)&&ar(t)&&Object.keys(s).forEach(a=>{wu.call(this,{rule:s[a],value:t&&t[a],key:`${e}.${a}`,fnName:r,className:o})});let{arrayItem:n}=i;jt(n)&&at(t)&&t.forEach((a,u)=>{wu.call(this,{rule:n,value:a,key:`${e}[${u}]`,fnName:r,className:o})}),je(i.validate)&&i.validate.call(this,t,e,r,o,this)}var Ay=pi(bi(),1);var by=Object.create,ku=Object.defineProperty,Ry=Object.defineProperties,SE=Object.getOwnPropertyDescriptor,vy=Object.getOwnPropertyDescriptors,yE=Object.getOwnPropertyNames,_E=Object.getOwnPropertySymbols,Cy=Object.getPrototypeOf,AE=Object.prototype.hasOwnProperty,Ny=Object.prototype.propertyIsEnumerable,up=(i,t,e)=>t in i?ku(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Ou=(i,t)=>{for(var e in t||(t={}))AE.call(t,e)&&up(i,e,t[e]);if(_E)for(var e of _E(t))Ny.call(t,e)&&up(i,e,t[e]);return i},xu=(i,t)=>Ry(i,vy(t)),Dy=(i,t)=>function(){return t||(0,i[yE(i)[0]])((t={exports:{}}).exports,t),t.exports},wy=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of yE(t))AE.call(i,o)||o===e||ku(i,o,{get:()=>t[o],enumerable:!(r=SE(t,o))||r.enumerable});return i},My=(i,t,e)=>(e=i!=null?by(Cy(i)):{},wy(!t&&i&&i.__esModule?e:ku(e,"default",{value:i,enumerable:!0}),i)),Ui=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?SE(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&&ku(t,e,s),s},Wr=(i,t,e)=>up(i,typeof t!="symbol"?t+"":t,e),Oy=Dy({"../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,p,g){this.fn=m,this.context=p,this.once=g||!1}function n(m,p,g,E,A){if(typeof g!="function")throw new TypeError("The listener must be a function");var C=new s(g,E||m,A),N=r?r+p:p;return m._events[N]?m._events[N].fn?m._events[N]=[m._events[N],C]:m._events[N].push(C):(m._events[N]=C,m._eventsCount++),m}function a(m,p){--m._eventsCount==0?m._events=new o:delete m._events[p]}function u(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),u.prototype.eventNames=function(){var m,p,g=[];if(this._eventsCount===0)return g;for(p in m=this._events)e.call(m,p)&&g.push(r?p.slice(1):p);return Object.getOwnPropertySymbols?g.concat(Object.getOwnPropertySymbols(m)):g},u.prototype.listeners=function(m){var p=r?r+m:m,g=this._events[p];if(!g)return[];if(g.fn)return[g.fn];for(var E=0,A=g.length,C=new Array(A);E<A;E++)C[E]=g[E].fn;return C},u.prototype.listenerCount=function(m){var p=r?r+m:m,g=this._events[p];return g?g.fn?1:g.length:0},u.prototype.emit=function(m,p,g,E,A,C){var N=r?r+m:m;if(!this._events[N])return!1;var D,x,Z=this._events[N],ue=arguments.length;if(Z.fn){switch(Z.once&&this.removeListener(m,Z.fn,void 0,!0),ue){case 1:return Z.fn.call(Z.context),!0;case 2:return Z.fn.call(Z.context,p),!0;case 3:return Z.fn.call(Z.context,p,g),!0;case 4:return Z.fn.call(Z.context,p,g,E),!0;case 5:return Z.fn.call(Z.context,p,g,E,A),!0;case 6:return Z.fn.call(Z.context,p,g,E,A,C),!0}for(x=1,D=new Array(ue-1);x<ue;x++)D[x-1]=arguments[x];Z.fn.apply(Z.context,D)}else{var Se,Ye=Z.length;for(x=0;x<Ye;x++)switch(Z[x].once&&this.removeListener(m,Z[x].fn,void 0,!0),ue){case 1:Z[x].fn.call(Z[x].context);break;case 2:Z[x].fn.call(Z[x].context,p);break;case 3:Z[x].fn.call(Z[x].context,p,g);break;case 4:Z[x].fn.call(Z[x].context,p,g,E);break;default:if(!D)for(Se=1,D=new Array(ue-1);Se<ue;Se++)D[Se-1]=arguments[Se];Z[x].fn.apply(Z[x].context,D)}}return!0},u.prototype.on=function(m,p,g){return n(this,m,p,g,!1)},u.prototype.once=function(m,p,g){return n(this,m,p,g,!0)},u.prototype.removeListener=function(m,p,g,E){var A=r?r+m:m;if(!this._events[A])return this;if(!p)return a(this,A),this;var C=this._events[A];if(C.fn)C.fn!==p||E&&!C.once||g&&C.context!==g||a(this,A);else{for(var N=0,D=[],x=C.length;N<x;N++)(C[N].fn!==p||E&&!C[N].once||g&&C[N].context!==g)&&D.push(C[N]);D.length?this._events[A]=D.length===1?D[0]:D:a(this,A)}return this},u.prototype.removeAllListeners=function(m){var p;return m?(p=r?r+m:m,this._events[p]&&a(this,p)):(this._events=new o,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=r,u.EventEmitter=u,t!==void 0&&(t.exports=u)}}),xy=My(Oy(),1),TE=Symbol("instance"),_P=Symbol("abortCtrl"),Mu=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,dc.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Pu=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function Py(i){return typeof i=="object"&&i&&"then"in i}var cc=new Map;function Io(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let u=cc.get(r)||[];cc.has(r)||cc.set(r,u),u.push({from:i,to:t,action:n})}let a=s.value;s.value=function(...u){let m=this;if(e.context&&(m=Yt.get(typeof e.context=="function"?e.context.call(this,...u):e.context)),m.state===t)return e.sync?m[Mu]:Promise.resolve(m[Mu]);m.state instanceof cp&&m.state.action==e.abortAction&&m.state.abort(m);let p=null;Array.isArray(i)?i.length==0?m.state instanceof cp&&m.state.abort(m):typeof m.state=="string"&&i.includes(m.state)||(p=new Pu(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i.join("|")}`)):i!==m.state&&(p=new Pu(m._state,`${m.name} ${n} to ${t} failed: current state ${m._state} not from ${i}`));let g=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(p)return g(p);let E=m.state,A=new cp(E,t,n);dc.call(m,A);let C=D=>{var x;return m[Mu]=D,A.aborted||(dc.call(m,t),(x=e.success)===null||x===void 0||x.call(this,m[Mu])),D},N=D=>(dc.call(m,E,D),g(D));try{let D=a.apply(this,u);return Py(D)?D.then(C).catch(N):e.sync?C(D):Promise.resolve(C(D))}catch(D){return N(new Pu(m._state,`${m.name} ${n} from ${i} to ${t} failed: ${D}`,D instanceof Error?D:new Error(String(D))))}}}}function ky(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new Pu(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var Ly=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 dc(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Yt.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var Yt=class br extends xy.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=br.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[TE];o?this.name=o.name+"-"+o.count++:r[TE]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=cc.get(t)||[],r=new Set,o=[],s=[],n=new Set,a=Object.getPrototypeOf(t);cc.has(a)&&(a.stateDiagram.forEach(m=>r.add(m)),a.allStates.forEach(m=>n.add(m))),e.forEach(({from:m,to:p,action:g})=>{typeof m=="string"?o.push({from:m,to:p,action:g}):m.length?m.forEach(E=>{o.push({from:E,to:p,action:g})}):s.push({to:p,action:g})}),o.forEach(({from:m,to:p,action:g})=>{n.add(m),n.add(p),n.add(g+"ing"),r.add(`${m} --> ${g}ing : ${g}`),r.add(`${g}ing --> ${p} : ${g} \u{1F7E2}`),r.add(`${g}ing --> ${m} : ${g} \u{1F534}`)}),s.forEach(({to:m,action:p})=>{r.add(`${p}ing --> ${m} : ${p} \u{1F7E2}`),n.forEach(g=>{g!==m&&r.add(`${g} --> ${p}ing : ${p}`)})});let u=[...r];return Object.defineProperties(t,{stateDiagram:{value:u},allStates:{value:n}}),u}static get(t){let e;return typeof t=="string"?(e=br.instances.get(t),e||br.instances.set(t,e=new br(t,void 0,Object.create(br.prototype)))):(e=br.instances2.get(t),e||br.instances2.set(t,e=new br(t.constructor.name,void 0,Object.create(br.prototype)))),e}static getState(t){var e;return(e=br.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){Ly(br.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){dc.call(this,t)}};Yt.STATECHANGED="stateChanged",Yt.UPDATEAFSM="updateAFSM",Yt.INIT="[*]",Yt.ON="on",Yt.OFF="off",Yt.instances=new Map,Yt.instances2=new WeakMap;var Dn=class extends Yt{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(xu(Ou({},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 Uy(){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,a=0,u={wasmBinary:o,postRun:()=>{i=new u.VideoDecoder({videoInfo(m,p){n=m,a=p,console.log("video info",m,p)},yuvData(m,p){let g=n*a,E=g>>2,A=u.HEAPU32[m>>2],C=u.HEAPU32[1+(m>>2)],N=u.HEAPU32[2+(m>>2)],D=u.HEAPU8.subarray(A,A+g),x=u.HEAPU8.subarray(C,C+E),Z=u.HEAPU8.subarray(N,N+E),ue=new Uint8Array(g+E+E);ue.set(D),ue.set(x,g),ue.set(Z,g+E);let Se=new VideoFrame(ue,{codedWidth:n,codedHeight:a,format:"I420",timestamp:p});e?(s==null||s.drawImage(Se,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:Se},[Se])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(u)}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:"")}}}Ui([Io([Yt.INIT,"closed"],"initialized")],Dn.prototype,"initialize",1),Ui([Io("initialized","configured",{sync:!0})],Dn.prototype,"configure",1),Ui([ky("configured")],Dn.prototype,"decode",1),Ui([Io([],Yt.INIT,{sync:!0})],Dn.prototype,"reset",1),Ui([Io([],"closed",{ignoreError:!0,sync:!0})],Dn.prototype,"close",1);var ac=class extends Yt{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(Uy.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=a=>{if(a.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(a.data.type==="yuvData"){let{videoFrame:u}=a.data;this.emit("videoFrame",u)}}})}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)],a=this.module.HEAPU8.subarray(o,o+e),u=this.module.HEAPU8.subarray(s,s+r),m=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",{y:a,u,v:m,timestamp:t});let p=new Uint8Array(e+r+r);p.set(a),p.set(u,e),p.set(m,e+r),this.emit("videoFrame",new VideoFrame(p,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};Ui([Io([Yt.INIT,"closed"],"initialized")],ac.prototype,"initialize",1),Ui([Io("initialized","configured",{sync:!0})],ac.prototype,"configure",1),Ui([Io([],Yt.INIT,{sync:!0})],ac.prototype,"reset",1),Ui([Io([],"closed",{sync:!0})],ac.prototype,"close",1);var Vy=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((c,d)=>{e=c,r=d});var s,n,a,u=Object.assign({},o),m="./this.program",p=typeof window=="object",g=typeof importScripts=="function",E=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(p||g)&&(g?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),i&&(E=i),E=E.indexOf("blob:")!==0?E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=c=>{var d=new XMLHttpRequest;return d.open("GET",c,!1),d.send(null),d.responseText},g&&(a=c=>{var d=new XMLHttpRequest;return d.open("GET",c,!1),d.responseType="arraybuffer",d.send(null),new Uint8Array(d.response)}),n=(c,d,h)=>{var f=new XMLHttpRequest;f.open("GET",c,!0),f.responseType="arraybuffer",f.onload=()=>{f.status==200||f.status==0&&f.response?d(f.response):h()},f.onerror=h,f.send(null)});var A,C=o.print||console.log.bind(console),N=o.printErr||console.error.bind(console);Object.assign(o,u),u=null,o.arguments&&o.arguments,o.thisProgram&&(m=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(A=o.wasmBinary);var D,x;o.noExitRuntime,typeof WebAssembly!="object"&&jr("no native wasm support detected");var Z,ue,Se,Ye,H,Pe,Ln,Un,Vn,Fn=!1,Gr=[],Ns=[],Bi=[],hr=0,ci=null,di=null;function ie(c){hr++,o.monitorRunDependencies&&o.monitorRunDependencies(hr)}function No(c){if(hr--,o.monitorRunDependencies&&o.monitorRunDependencies(hr),hr==0&&(ci!==null&&(clearInterval(ci),ci=null),di)){var d=di;di=null,d()}}function jr(c){o.onAbort&&o.onAbort(c),N(c="Aborted("+c+")"),Fn=!0,c+=". Build with -sASSERTIONS for more info.";var d=new WebAssembly.RuntimeError(c);throw r(d),d}var ui,$n,Te,Ke;function $t(c){return c.startsWith("data:application/octet-stream;base64,")}function J(c){if(c==ui&&A)return new Uint8Array(A);if(a)return a(c);throw"both async and sync fetching of the wasm failed"}function qr(c,d,h){return function(f){return A||!p&&!g||typeof fetch!="function"?Promise.resolve().then(()=>J(f)):fetch(f,{credentials:"same-origin"}).then(I=>{if(!I.ok)throw"failed to load wasm binary file at '"+f+"'";return I.arrayBuffer()}).catch(()=>J(f))}(c).then(f=>WebAssembly.instantiate(f,d)).then(f=>f).then(h,f=>{N("failed to asynchronously prepare wasm: "+f),jr(f)})}$t(ui="videodec.wasm")||($n=ui,ui=o.locateFile?o.locateFile($n,E):E+$n);var Hi=c=>{for(;c.length>0;)c.shift()(o)};function Wi(c){this.excPtr=c,this.ptr=c-24,this.set_type=function(d){Pe[this.ptr+4>>2]=d},this.get_type=function(){return Pe[this.ptr+4>>2]},this.set_destructor=function(d){Pe[this.ptr+8>>2]=d},this.get_destructor=function(){return Pe[this.ptr+8>>2]},this.set_caught=function(d){d=d?1:0,Z[this.ptr+12|0]=d},this.get_caught=function(){return Z[this.ptr+12|0]!=0},this.set_rethrown=function(d){d=d?1:0,Z[this.ptr+13|0]=d},this.get_rethrown=function(){return Z[this.ptr+13|0]!=0},this.init=function(d,h){this.set_adjusted_ptr(0),this.set_type(d),this.set_destructor(h)},this.set_adjusted_ptr=function(d){Pe[this.ptr+16>>2]=d},this.get_adjusted_ptr=function(){return Pe[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Jn(this.get_type()))return Pe[this.excPtr>>2];var d=this.get_adjusted_ptr();return d!==0?d:this.excPtr}}var me={isAbs:c=>c.charAt(0)==="/",splitPath:c=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(c).slice(1),normalizeArray:(c,d)=>{for(var h=0,f=c.length-1;f>=0;f--){var I=c[f];I==="."?c.splice(f,1):I===".."?(c.splice(f,1),h++):h&&(c.splice(f,1),h--)}if(d)for(;h;h--)c.unshift("..");return c},normalize:c=>{var d=me.isAbs(c),h=c.substr(-1)==="/";return(c=me.normalizeArray(c.split("/").filter(f=>!!f),!d).join("/"))||d||(c="."),c&&h&&(c+="/"),(d?"/":"")+c},dirname:c=>{var d=me.splitPath(c),h=d[0],f=d[1];return h||f?(f&&(f=f.substr(0,f.length-1)),h+f):"."},basename:c=>{if(c==="/")return"/";var d=(c=(c=me.normalize(c)).replace(/\/$/,"")).lastIndexOf("/");return d===-1?c:c.substr(d+1)},join:function(){var c=Array.prototype.slice.call(arguments);return me.normalize(c.join("/"))},join2:(c,d)=>me.normalize(c+"/"+d)},Bn=c=>(Bn=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return d=>crypto.getRandomValues(d);jr("initRandomDevice")})())(c),Zt={resolve:function(){for(var c="",d=!1,h=arguments.length-1;h>=-1&&!d;h--){var f=h>=0?arguments[h]:_.cwd();if(typeof f!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!f)return"";c=f+"/"+c,d=me.isAbs(f)}return(d?"/":"")+(c=me.normalizeArray(c.split("/").filter(I=>!!I),!d).join("/"))||"."},relative:(c,d)=>{function h(L){for(var ee=0;ee<L.length&&L[ee]==="";ee++);for(var ae=L.length-1;ae>=0&&L[ae]==="";ae--);return ee>ae?[]:L.slice(ee,ae-ee+1)}c=Zt.resolve(c).substr(1),d=Zt.resolve(d).substr(1);for(var f=h(c.split("/")),I=h(d.split("/")),b=Math.min(f.length,I.length),R=b,v=0;v<b;v++)if(f[v]!==I[v]){R=v;break}var V=[];for(v=R;v<f.length;v++)V.push("..");return(V=V.concat(I.slice(R))).join("/")}},Gi=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Bt=(c,d,h)=>{for(var f=d+h,I=d;c[I]&&!(I>=f);)++I;if(I-d>16&&c.buffer&&Gi)return Gi.decode(c.subarray(d,I));for(var b="";d<I;){var R=c[d++];if(128&R){var v=63&c[d++];if((224&R)!=192){var V=63&c[d++];if((R=(240&R)==224?(15&R)<<12|v<<6|V:(7&R)<<18|v<<12|V<<6|63&c[d++])<65536)b+=String.fromCharCode(R);else{var L=R-65536;b+=String.fromCharCode(55296|L>>10,56320|1023&L)}}else b+=String.fromCharCode((31&R)<<6|v)}else b+=String.fromCharCode(R)}return b},Hn=[],Do=c=>{for(var d=0,h=0;h<c.length;++h){var f=c.charCodeAt(h);f<=127?d++:f<=2047?d+=2:f>=55296&&f<=57343?(d+=4,++h):d+=3}return d},wo=(c,d,h,f)=>{if(!(f>0))return 0;for(var I=h,b=h+f-1,R=0;R<c.length;++R){var v=c.charCodeAt(R);if(v>=55296&&v<=57343&&(v=65536+((1023&v)<<10)|1023&c.charCodeAt(++R)),v<=127){if(h>=b)break;d[h++]=v}else if(v<=2047){if(h+1>=b)break;d[h++]=192|v>>6,d[h++]=128|63&v}else if(v<=65535){if(h+2>=b)break;d[h++]=224|v>>12,d[h++]=128|v>>6&63,d[h++]=128|63&v}else{if(h+3>=b)break;d[h++]=240|v>>18,d[h++]=128|v>>12&63,d[h++]=128|v>>6&63,d[h++]=128|63&v}}return d[h]=0,h-I};function Ds(c,d,h){var f=h>0?h:Do(c)+1,I=new Array(f),b=wo(c,I,0,I.length);return d&&(I.length=b),I}var Rr={ttys:[],init:function(){},shutdown:function(){},register:function(c,d){Rr.ttys[c]={input:[],output:[],ops:d},_.registerDevice(c,Rr.stream_ops)},stream_ops:{open:function(c){var d=Rr.ttys[c.node.rdev];if(!d)throw new _.ErrnoError(43);c.tty=d,c.seekable=!1},close:function(c){c.tty.ops.fsync(c.tty)},fsync:function(c){c.tty.ops.fsync(c.tty)},read:function(c,d,h,f,I){if(!c.tty||!c.tty.ops.get_char)throw new _.ErrnoError(60);for(var b=0,R=0;R<f;R++){var v;try{v=c.tty.ops.get_char(c.tty)}catch(V){throw new _.ErrnoError(29)}if(v===void 0&&b===0)throw new _.ErrnoError(6);if(v==null)break;b++,d[h+R]=v}return b&&(c.node.timestamp=Date.now()),b},write:function(c,d,h,f,I){if(!c.tty||!c.tty.ops.put_char)throw new _.ErrnoError(60);try{for(var b=0;b<f;b++)c.tty.ops.put_char(c.tty,d[h+b])}catch(R){throw new _.ErrnoError(29)}return f&&(c.node.timestamp=Date.now()),b}},default_tty_ops:{get_char:function(c){return(()=>{if(!Hn.length){var d=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(d=window.prompt("Input: "))!==null&&(d+=`
|
|
51
|
+
`):typeof readline=="function"&&(d=readline())!==null&&(d+=`
|
|
52
|
+
`),!d)return null;Hn=Ds(d,!0)}return Hn.shift()})()},put_char:function(c,d){d===null||d===10?(C(Bt(c.output,0)),c.output=[]):d!=0&&c.output.push(d)},fsync:function(c){c.output&&c.output.length>0&&(C(Bt(c.output,0)),c.output=[])},ioctl_tcgets:function(c){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(c,d,h){return 0},ioctl_tiocgwinsz:function(c){return[24,80]}},default_tty1_ops:{put_char:function(c,d){d===null||d===10?(N(Bt(c.output,0)),c.output=[]):d!=0&&c.output.push(d)},fsync:function(c){c.output&&c.output.length>0&&(N(Bt(c.output,0)),c.output=[])}}},Wn=c=>{jr()},j={ops_table:null,mount:c=>j.createNode(null,"/",16895,0),createNode(c,d,h,f){if(_.isBlkdev(h)||_.isFIFO(h))throw new _.ErrnoError(63);j.ops_table||(j.ops_table={dir:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr,lookup:j.node_ops.lookup,mknod:j.node_ops.mknod,rename:j.node_ops.rename,unlink:j.node_ops.unlink,rmdir:j.node_ops.rmdir,readdir:j.node_ops.readdir,symlink:j.node_ops.symlink},stream:{llseek:j.stream_ops.llseek}},file:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr},stream:{llseek:j.stream_ops.llseek,read:j.stream_ops.read,write:j.stream_ops.write,allocate:j.stream_ops.allocate,mmap:j.stream_ops.mmap,msync:j.stream_ops.msync}},link:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr,readlink:j.node_ops.readlink},stream:{}},chrdev:{node:{getattr:j.node_ops.getattr,setattr:j.node_ops.setattr},stream:_.chrdev_stream_ops}});var I=_.createNode(c,d,h,f);return _.isDir(I.mode)?(I.node_ops=j.ops_table.dir.node,I.stream_ops=j.ops_table.dir.stream,I.contents={}):_.isFile(I.mode)?(I.node_ops=j.ops_table.file.node,I.stream_ops=j.ops_table.file.stream,I.usedBytes=0,I.contents=null):_.isLink(I.mode)?(I.node_ops=j.ops_table.link.node,I.stream_ops=j.ops_table.link.stream):_.isChrdev(I.mode)&&(I.node_ops=j.ops_table.chrdev.node,I.stream_ops=j.ops_table.chrdev.stream),I.timestamp=Date.now(),c&&(c.contents[d]=I,c.timestamp=I.timestamp),I},getFileDataAsTypedArray:c=>c.contents?c.contents.subarray?c.contents.subarray(0,c.usedBytes):new Uint8Array(c.contents):new Uint8Array(0),expandFileStorage(c,d){var h=c.contents?c.contents.length:0;if(!(h>=d)){d=Math.max(d,h*(h<1048576?2:1.125)>>>0),h!=0&&(d=Math.max(d,256));var f=c.contents;c.contents=new Uint8Array(d),c.usedBytes>0&&c.contents.set(f.subarray(0,c.usedBytes),0)}},resizeFileStorage(c,d){if(c.usedBytes!=d)if(d==0)c.contents=null,c.usedBytes=0;else{var h=c.contents;c.contents=new Uint8Array(d),h&&c.contents.set(h.subarray(0,Math.min(d,c.usedBytes))),c.usedBytes=d}},node_ops:{getattr(c){var d={};return d.dev=_.isChrdev(c.mode)?c.id:1,d.ino=c.id,d.mode=c.mode,d.nlink=1,d.uid=0,d.gid=0,d.rdev=c.rdev,_.isDir(c.mode)?d.size=4096:_.isFile(c.mode)?d.size=c.usedBytes:_.isLink(c.mode)?d.size=c.link.length:d.size=0,d.atime=new Date(c.timestamp),d.mtime=new Date(c.timestamp),d.ctime=new Date(c.timestamp),d.blksize=4096,d.blocks=Math.ceil(d.size/d.blksize),d},setattr(c,d){d.mode!==void 0&&(c.mode=d.mode),d.timestamp!==void 0&&(c.timestamp=d.timestamp),d.size!==void 0&&j.resizeFileStorage(c,d.size)},lookup(c,d){throw _.genericErrors[44]},mknod:(c,d,h,f)=>j.createNode(c,d,h,f),rename(c,d,h){if(_.isDir(c.mode)){var f;try{f=_.lookupNode(d,h)}catch(b){}if(f)for(var I in f.contents)throw new _.ErrnoError(55)}delete c.parent.contents[c.name],c.parent.timestamp=Date.now(),c.name=h,d.contents[h]=c,d.timestamp=c.parent.timestamp,c.parent=d},unlink(c,d){delete c.contents[d],c.timestamp=Date.now()},rmdir(c,d){var h=_.lookupNode(c,d);for(var f in h.contents)throw new _.ErrnoError(55);delete c.contents[d],c.timestamp=Date.now()},readdir(c){var d=[".",".."];for(var h in c.contents)c.contents.hasOwnProperty(h)&&d.push(h);return d},symlink(c,d,h){var f=j.createNode(c,d,41471,0);return f.link=h,f},readlink(c){if(!_.isLink(c.mode))throw new _.ErrnoError(28);return c.link}},stream_ops:{read(c,d,h,f,I){var b=c.node.contents;if(I>=c.node.usedBytes)return 0;var R=Math.min(c.node.usedBytes-I,f);if(R>8&&b.subarray)d.set(b.subarray(I,I+R),h);else for(var v=0;v<R;v++)d[h+v]=b[I+v];return R},write(c,d,h,f,I,b){if(!f)return 0;var R=c.node;if(R.timestamp=Date.now(),d.subarray&&(!R.contents||R.contents.subarray)){if(b)return R.contents=d.subarray(h,h+f),R.usedBytes=f,f;if(R.usedBytes===0&&I===0)return R.contents=d.slice(h,h+f),R.usedBytes=f,f;if(I+f<=R.usedBytes)return R.contents.set(d.subarray(h,h+f),I),f}if(j.expandFileStorage(R,I+f),R.contents.subarray&&d.subarray)R.contents.set(d.subarray(h,h+f),I);else for(var v=0;v<f;v++)R.contents[I+v]=d[h+v];return R.usedBytes=Math.max(R.usedBytes,I+f),f},llseek(c,d,h){var f=d;if(h===1?f+=c.position:h===2&&_.isFile(c.node.mode)&&(f+=c.node.usedBytes),f<0)throw new _.ErrnoError(28);return f},allocate(c,d,h){j.expandFileStorage(c.node,d+h),c.node.usedBytes=Math.max(c.node.usedBytes,d+h)},mmap(c,d,h,f,I){if(!_.isFile(c.node.mode))throw new _.ErrnoError(43);var b,R,v=c.node.contents;if(2&I||v.buffer!==Z.buffer){if((h>0||h+d<v.length)&&(v=v.subarray?v.subarray(h,h+d):Array.prototype.slice.call(v,h,h+d)),R=!0,!(b=Wn()))throw new _.ErrnoError(48);Z.set(v,b)}else R=!1,b=v.byteOffset;return{ptr:b,allocated:R}},msync:(c,d,h,f,I)=>(j.stream_ops.write(c,d,0,f,h,!1),0)}},Tl=(c,d,h,f)=>{var I=f?"":`al ${c}`;n(c,b=>{var R;R=`Loading data file "${c}" failed (no arrayBuffer).`,b||jr(R),d(new Uint8Array(b)),I&&No()},b=>{if(!h)throw`Loading data file "${c}" failed.`;h()}),I&&ie()},Il=o.preloadPlugins||[];function li(c,d){var h=0;return c&&(h|=365),d&&(h|=146),h}var _={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(c,d={})=>{if(!(c=Zt.resolve(c)))return{path:"",node:null};if((d=Object.assign({follow_mount:!0,recurse_count:0},d)).recurse_count>8)throw new _.ErrnoError(32);for(var h=c.split("/").filter(L=>!!L),f=_.root,I="/",b=0;b<h.length;b++){var R=b===h.length-1;if(R&&d.parent)break;if(f=_.lookupNode(f,h[b]),I=me.join2(I,h[b]),_.isMountpoint(f)&&(!R||R&&d.follow_mount)&&(f=f.mounted.root),!R||d.follow)for(var v=0;_.isLink(f.mode);){var V=_.readlink(I);if(I=Zt.resolve(me.dirname(I),V),f=_.lookupPath(I,{recurse_count:d.recurse_count+1}).node,v++>40)throw new _.ErrnoError(32)}}return{path:I,node:f}},getPath:c=>{for(var d;;){if(_.isRoot(c)){var h=c.mount.mountpoint;return d?h[h.length-1]!=="/"?`${h}/${d}`:h+d:h}d=d?`${c.name}/${d}`:c.name,c=c.parent}},hashName:(c,d)=>{for(var h=0,f=0;f<d.length;f++)h=(h<<5)-h+d.charCodeAt(f)|0;return(c+h>>>0)%_.nameTable.length},hashAddNode:c=>{var d=_.hashName(c.parent.id,c.name);c.name_next=_.nameTable[d],_.nameTable[d]=c},hashRemoveNode:c=>{var d=_.hashName(c.parent.id,c.name);if(_.nameTable[d]===c)_.nameTable[d]=c.name_next;else for(var h=_.nameTable[d];h;){if(h.name_next===c){h.name_next=c.name_next;break}h=h.name_next}},lookupNode:(c,d)=>{var h=_.mayLookup(c);if(h)throw new _.ErrnoError(h,c);for(var f=_.hashName(c.id,d),I=_.nameTable[f];I;I=I.name_next){var b=I.name;if(I.parent.id===c.id&&b===d)return I}return _.lookup(c,d)},createNode:(c,d,h,f)=>{var I=new _.FSNode(c,d,h,f);return _.hashAddNode(I),I},destroyNode:c=>{_.hashRemoveNode(c)},isRoot:c=>c===c.parent,isMountpoint:c=>!!c.mounted,isFile:c=>(61440&c)==32768,isDir:c=>(61440&c)==16384,isLink:c=>(61440&c)==40960,isChrdev:c=>(61440&c)==8192,isBlkdev:c=>(61440&c)==24576,isFIFO:c=>(61440&c)==4096,isSocket:c=>!(49152&~c),flagsToPermissionString:c=>{var d=["r","w","rw"][3&c];return 512&c&&(d+="w"),d},nodePermissions:(c,d)=>_.ignorePermissions||(!d.includes("r")||292&c.mode)&&(!d.includes("w")||146&c.mode)&&(!d.includes("x")||73&c.mode)?0:2,mayLookup:c=>{var d=_.nodePermissions(c,"x");return d||(c.node_ops.lookup?0:2)},mayCreate:(c,d)=>{try{return _.lookupNode(c,d),20}catch(h){}return _.nodePermissions(c,"wx")},mayDelete:(c,d,h)=>{var f;try{f=_.lookupNode(c,d)}catch(b){return b.errno}var I=_.nodePermissions(c,"wx");if(I)return I;if(h){if(!_.isDir(f.mode))return 54;if(_.isRoot(f)||_.getPath(f)===_.cwd())return 10}else if(_.isDir(f.mode))return 31;return 0},mayOpen:(c,d)=>c?_.isLink(c.mode)?32:_.isDir(c.mode)&&(_.flagsToPermissionString(d)!=="r"||512&d)?31:_.nodePermissions(c,_.flagsToPermissionString(d)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var c=0;c<=_.MAX_OPEN_FDS;c++)if(!_.streams[c])return c;throw new _.ErrnoError(33)},getStreamChecked:c=>{var d=_.getStream(c);if(!d)throw new _.ErrnoError(8);return d},getStream:c=>_.streams[c],createStream:(c,d=-1)=>(_.FSStream||(_.FSStream=function(){this.shared={}},_.FSStream.prototype={},Object.defineProperties(_.FSStream.prototype,{object:{get(){return this.node},set(h){this.node=h}},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(h){this.shared.flags=h}},position:{get(){return this.shared.position},set(h){this.shared.position=h}}})),c=Object.assign(new _.FSStream,c),d==-1&&(d=_.nextfd()),c.fd=d,_.streams[d]=c,c),closeStream:c=>{_.streams[c]=null},chrdev_stream_ops:{open:c=>{var d=_.getDevice(c.node.rdev);c.stream_ops=d.stream_ops,c.stream_ops.open&&c.stream_ops.open(c)},llseek:()=>{throw new _.ErrnoError(70)}},major:c=>c>>8,minor:c=>255&c,makedev:(c,d)=>c<<8|d,registerDevice:(c,d)=>{_.devices[c]={stream_ops:d}},getDevice:c=>_.devices[c],getMounts:c=>{for(var d=[],h=[c];h.length;){var f=h.pop();d.push(f),h.push.apply(h,f.mounts)}return d},syncfs:(c,d)=>{typeof c=="function"&&(d=c,c=!1),_.syncFSRequests++,_.syncFSRequests>1&&N(`warning: ${_.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var h=_.getMounts(_.root.mount),f=0;function I(R){return _.syncFSRequests--,d(R)}function b(R){if(R)return b.errored?void 0:(b.errored=!0,I(R));++f>=h.length&&I(null)}h.forEach(R=>{if(!R.type.syncfs)return b(null);R.type.syncfs(R,c,b)})},mount:(c,d,h)=>{var f,I=h==="/",b=!h;if(I&&_.root)throw new _.ErrnoError(10);if(!I&&!b){var R=_.lookupPath(h,{follow_mount:!1});if(h=R.path,f=R.node,_.isMountpoint(f))throw new _.ErrnoError(10);if(!_.isDir(f.mode))throw new _.ErrnoError(54)}var v={type:c,opts:d,mountpoint:h,mounts:[]},V=c.mount(v);return V.mount=v,v.root=V,I?_.root=V:f&&(f.mounted=v,f.mount&&f.mount.mounts.push(v)),V},unmount:c=>{var d=_.lookupPath(c,{follow_mount:!1});if(!_.isMountpoint(d.node))throw new _.ErrnoError(28);var h=d.node,f=h.mounted,I=_.getMounts(f);Object.keys(_.nameTable).forEach(R=>{for(var v=_.nameTable[R];v;){var V=v.name_next;I.includes(v.mount)&&_.destroyNode(v),v=V}}),h.mounted=null;var b=h.mount.mounts.indexOf(f);h.mount.mounts.splice(b,1)},lookup:(c,d)=>c.node_ops.lookup(c,d),mknod:(c,d,h)=>{var f=_.lookupPath(c,{parent:!0}).node,I=me.basename(c);if(!I||I==="."||I==="..")throw new _.ErrnoError(28);var b=_.mayCreate(f,I);if(b)throw new _.ErrnoError(b);if(!f.node_ops.mknod)throw new _.ErrnoError(63);return f.node_ops.mknod(f,I,d,h)},create:(c,d)=>(d=d!==void 0?d:438,d&=4095,d|=32768,_.mknod(c,d,0)),mkdir:(c,d)=>(d=d!==void 0?d:511,d&=1023,d|=16384,_.mknod(c,d,0)),mkdirTree:(c,d)=>{for(var h=c.split("/"),f="",I=0;I<h.length;++I)if(h[I]){f+="/"+h[I];try{_.mkdir(f,d)}catch(b){if(b.errno!=20)throw b}}},mkdev:(c,d,h)=>(h===void 0&&(h=d,d=438),d|=8192,_.mknod(c,d,h)),symlink:(c,d)=>{if(!Zt.resolve(c))throw new _.ErrnoError(44);var h=_.lookupPath(d,{parent:!0}).node;if(!h)throw new _.ErrnoError(44);var f=me.basename(d),I=_.mayCreate(h,f);if(I)throw new _.ErrnoError(I);if(!h.node_ops.symlink)throw new _.ErrnoError(63);return h.node_ops.symlink(h,f,c)},rename:(c,d)=>{var h,f,I=me.dirname(c),b=me.dirname(d),R=me.basename(c),v=me.basename(d);if(h=_.lookupPath(c,{parent:!0}).node,f=_.lookupPath(d,{parent:!0}).node,!h||!f)throw new _.ErrnoError(44);if(h.mount!==f.mount)throw new _.ErrnoError(75);var V,L=_.lookupNode(h,R),ee=Zt.relative(c,b);if(ee.charAt(0)!==".")throw new _.ErrnoError(28);if((ee=Zt.relative(d,I)).charAt(0)!==".")throw new _.ErrnoError(55);try{V=_.lookupNode(f,v)}catch(ne){}if(L!==V){var ae=_.isDir(L.mode),ce=_.mayDelete(h,R,ae);if(ce)throw new _.ErrnoError(ce);if(ce=V?_.mayDelete(f,v,ae):_.mayCreate(f,v))throw new _.ErrnoError(ce);if(!h.node_ops.rename)throw new _.ErrnoError(63);if(_.isMountpoint(L)||V&&_.isMountpoint(V))throw new _.ErrnoError(10);if(f!==h&&(ce=_.nodePermissions(h,"w")))throw new _.ErrnoError(ce);_.hashRemoveNode(L);try{h.node_ops.rename(L,f,v)}catch(ne){throw ne}finally{_.hashAddNode(L)}}},rmdir:c=>{var d=_.lookupPath(c,{parent:!0}).node,h=me.basename(c),f=_.lookupNode(d,h),I=_.mayDelete(d,h,!0);if(I)throw new _.ErrnoError(I);if(!d.node_ops.rmdir)throw new _.ErrnoError(63);if(_.isMountpoint(f))throw new _.ErrnoError(10);d.node_ops.rmdir(d,h),_.destroyNode(f)},readdir:c=>{var d=_.lookupPath(c,{follow:!0}).node;if(!d.node_ops.readdir)throw new _.ErrnoError(54);return d.node_ops.readdir(d)},unlink:c=>{var d=_.lookupPath(c,{parent:!0}).node;if(!d)throw new _.ErrnoError(44);var h=me.basename(c),f=_.lookupNode(d,h),I=_.mayDelete(d,h,!1);if(I)throw new _.ErrnoError(I);if(!d.node_ops.unlink)throw new _.ErrnoError(63);if(_.isMountpoint(f))throw new _.ErrnoError(10);d.node_ops.unlink(d,h),_.destroyNode(f)},readlink:c=>{var d=_.lookupPath(c).node;if(!d)throw new _.ErrnoError(44);if(!d.node_ops.readlink)throw new _.ErrnoError(28);return Zt.resolve(_.getPath(d.parent),d.node_ops.readlink(d))},stat:(c,d)=>{var h=_.lookupPath(c,{follow:!d}).node;if(!h)throw new _.ErrnoError(44);if(!h.node_ops.getattr)throw new _.ErrnoError(63);return h.node_ops.getattr(h)},lstat:c=>_.stat(c,!0),chmod:(c,d,h)=>{var f;if(typeof c=="string"?f=_.lookupPath(c,{follow:!h}).node:f=c,!f.node_ops.setattr)throw new _.ErrnoError(63);f.node_ops.setattr(f,{mode:4095&d|-4096&f.mode,timestamp:Date.now()})},lchmod:(c,d)=>{_.chmod(c,d,!0)},fchmod:(c,d)=>{var h=_.getStreamChecked(c);_.chmod(h.node,d)},chown:(c,d,h,f)=>{var I;if(typeof c=="string"?I=_.lookupPath(c,{follow:!f}).node:I=c,!I.node_ops.setattr)throw new _.ErrnoError(63);I.node_ops.setattr(I,{timestamp:Date.now()})},lchown:(c,d,h)=>{_.chown(c,d,h,!0)},fchown:(c,d,h)=>{var f=_.getStreamChecked(c);_.chown(f.node,d,h)},truncate:(c,d)=>{if(d<0)throw new _.ErrnoError(28);var h;if(typeof c=="string"?h=_.lookupPath(c,{follow:!0}).node:h=c,!h.node_ops.setattr)throw new _.ErrnoError(63);if(_.isDir(h.mode))throw new _.ErrnoError(31);if(!_.isFile(h.mode))throw new _.ErrnoError(28);var f=_.nodePermissions(h,"w");if(f)throw new _.ErrnoError(f);h.node_ops.setattr(h,{size:d,timestamp:Date.now()})},ftruncate:(c,d)=>{var h=_.getStreamChecked(c);if(!(2097155&h.flags))throw new _.ErrnoError(28);_.truncate(h.node,d)},utime:(c,d,h)=>{var f=_.lookupPath(c,{follow:!0}).node;f.node_ops.setattr(f,{timestamp:Math.max(d,h)})},open:(c,d,h)=>{if(c==="")throw new _.ErrnoError(44);var f;if(h=h===void 0?438:h,h=64&(d=typeof d=="string"?function(v){var V={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[v];if(V===void 0)throw new Error(`Unknown file open mode: ${v}`);return V}(d):d)?4095&h|32768:0,typeof c=="object")f=c;else{c=me.normalize(c);try{f=_.lookupPath(c,{follow:!(131072&d)}).node}catch(v){}}var I=!1;if(64&d)if(f){if(128&d)throw new _.ErrnoError(20)}else f=_.mknod(c,h,0),I=!0;if(!f)throw new _.ErrnoError(44);if(_.isChrdev(f.mode)&&(d&=-513),65536&d&&!_.isDir(f.mode))throw new _.ErrnoError(54);if(!I){var b=_.mayOpen(f,d);if(b)throw new _.ErrnoError(b)}512&d&&!I&&_.truncate(f,0),d&=-131713;var R=_.createStream({node:f,path:_.getPath(f),flags:d,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});return R.stream_ops.open&&R.stream_ops.open(R),!o.logReadFiles||1&d||(_.readFiles||(_.readFiles={}),c in _.readFiles||(_.readFiles[c]=1)),R},close:c=>{if(_.isClosed(c))throw new _.ErrnoError(8);c.getdents&&(c.getdents=null);try{c.stream_ops.close&&c.stream_ops.close(c)}catch(d){throw d}finally{_.closeStream(c.fd)}c.fd=null},isClosed:c=>c.fd===null,llseek:(c,d,h)=>{if(_.isClosed(c))throw new _.ErrnoError(8);if(!c.seekable||!c.stream_ops.llseek)throw new _.ErrnoError(70);if(h!=0&&h!=1&&h!=2)throw new _.ErrnoError(28);return c.position=c.stream_ops.llseek(c,d,h),c.ungotten=[],c.position},read:(c,d,h,f,I)=>{if(f<0||I<0)throw new _.ErrnoError(28);if(_.isClosed(c))throw new _.ErrnoError(8);if((2097155&c.flags)==1)throw new _.ErrnoError(8);if(_.isDir(c.node.mode))throw new _.ErrnoError(31);if(!c.stream_ops.read)throw new _.ErrnoError(28);var b=I!==void 0;if(b){if(!c.seekable)throw new _.ErrnoError(70)}else I=c.position;var R=c.stream_ops.read(c,d,h,f,I);return b||(c.position+=R),R},write:(c,d,h,f,I,b)=>{if(f<0||I<0)throw new _.ErrnoError(28);if(_.isClosed(c))throw new _.ErrnoError(8);if(!(2097155&c.flags))throw new _.ErrnoError(8);if(_.isDir(c.node.mode))throw new _.ErrnoError(31);if(!c.stream_ops.write)throw new _.ErrnoError(28);c.seekable&&1024&c.flags&&_.llseek(c,0,2);var R=I!==void 0;if(R){if(!c.seekable)throw new _.ErrnoError(70)}else I=c.position;var v=c.stream_ops.write(c,d,h,f,I,b);return R||(c.position+=v),v},allocate:(c,d,h)=>{if(_.isClosed(c))throw new _.ErrnoError(8);if(d<0||h<=0)throw new _.ErrnoError(28);if(!(2097155&c.flags))throw new _.ErrnoError(8);if(!_.isFile(c.node.mode)&&!_.isDir(c.node.mode))throw new _.ErrnoError(43);if(!c.stream_ops.allocate)throw new _.ErrnoError(138);c.stream_ops.allocate(c,d,h)},mmap:(c,d,h,f,I)=>{if(2&f&&!(2&I)&&(2097155&c.flags)!=2)throw new _.ErrnoError(2);if((2097155&c.flags)==1)throw new _.ErrnoError(2);if(!c.stream_ops.mmap)throw new _.ErrnoError(43);return c.stream_ops.mmap(c,d,h,f,I)},msync:(c,d,h,f,I)=>c.stream_ops.msync?c.stream_ops.msync(c,d,h,f,I):0,munmap:c=>0,ioctl:(c,d,h)=>{if(!c.stream_ops.ioctl)throw new _.ErrnoError(59);return c.stream_ops.ioctl(c,d,h)},readFile:(c,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 h,f=_.open(c,d.flags),I=_.stat(c).size,b=new Uint8Array(I);return _.read(f,b,0,I,0),d.encoding==="utf8"?h=Bt(b,0):d.encoding==="binary"&&(h=b),_.close(f),h},writeFile:(c,d,h={})=>{h.flags=h.flags||577;var f=_.open(c,h.flags,h.mode);if(typeof d=="string"){var I=new Uint8Array(Do(d)+1),b=wo(d,I,0,I.length);_.write(f,I,0,b,void 0,h.canOwn)}else{if(!ArrayBuffer.isView(d))throw new Error("Unsupported data type");_.write(f,d,0,d.byteLength,void 0,h.canOwn)}_.close(f)},cwd:()=>_.currentPath,chdir:c=>{var d=_.lookupPath(c,{follow:!0});if(d.node===null)throw new _.ErrnoError(44);if(!_.isDir(d.node.mode))throw new _.ErrnoError(54);var h=_.nodePermissions(d.node,"x");if(h)throw new _.ErrnoError(h);_.currentPath=d.path},createDefaultDirectories:()=>{_.mkdir("/tmp"),_.mkdir("/home"),_.mkdir("/home/web_user")},createDefaultDevices:()=>{_.mkdir("/dev"),_.registerDevice(_.makedev(1,3),{read:()=>0,write:(f,I,b,R,v)=>R}),_.mkdev("/dev/null",_.makedev(1,3)),Rr.register(_.makedev(5,0),Rr.default_tty_ops),Rr.register(_.makedev(6,0),Rr.default_tty1_ops),_.mkdev("/dev/tty",_.makedev(5,0)),_.mkdev("/dev/tty1",_.makedev(6,0));var c=new Uint8Array(1024),d=0,h=()=>(d===0&&(d=Bn(c).byteLength),c[--d]);_.createDevice("/dev","random",h),_.createDevice("/dev","urandom",h),_.mkdir("/dev/shm"),_.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{_.mkdir("/proc");var c=_.mkdir("/proc/self");_.mkdir("/proc/self/fd"),_.mount({mount:()=>{var d=_.createNode(c,"fd",16895,73);return d.node_ops={lookup:(h,f)=>{var I=+f,b=_.getStreamChecked(I),R={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>b.path}};return R.parent=R,R}},d}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?_.createDevice("/dev","stdin",o.stdin):_.symlink("/dev/tty","/dev/stdin"),o.stdout?_.createDevice("/dev","stdout",null,o.stdout):_.symlink("/dev/tty","/dev/stdout"),o.stderr?_.createDevice("/dev","stderr",null,o.stderr):_.symlink("/dev/tty1","/dev/stderr"),_.open("/dev/stdin",0),_.open("/dev/stdout",1),_.open("/dev/stderr",1)},ensureErrnoError:()=>{_.ErrnoError||(_.ErrnoError=function(c,d){this.name="ErrnoError",this.node=d,this.setErrno=function(h){this.errno=h},this.setErrno(c),this.message="FS error"},_.ErrnoError.prototype=new Error,_.ErrnoError.prototype.constructor=_.ErrnoError,[44].forEach(c=>{_.genericErrors[c]=new _.ErrnoError(c),_.genericErrors[c].stack="<generic error, no stack>"}))},staticInit:()=>{_.ensureErrnoError(),_.nameTable=new Array(4096),_.mount(j,{},"/"),_.createDefaultDirectories(),_.createDefaultDevices(),_.createSpecialDirectories(),_.filesystems={MEMFS:j}},init:(c,d,h)=>{_.init.initialized=!0,_.ensureErrnoError(),o.stdin=c||o.stdin,o.stdout=d||o.stdout,o.stderr=h||o.stderr,_.createStandardStreams()},quit:()=>{_.init.initialized=!1;for(var c=0;c<_.streams.length;c++){var d=_.streams[c];d&&_.close(d)}},findObject:(c,d)=>{var h=_.analyzePath(c,d);return h.exists?h.object:null},analyzePath:(c,d)=>{try{c=(f=_.lookupPath(c,{follow:!d})).path}catch(I){}var h={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var f=_.lookupPath(c,{parent:!0});h.parentExists=!0,h.parentPath=f.path,h.parentObject=f.node,h.name=me.basename(c),f=_.lookupPath(c,{follow:!d}),h.exists=!0,h.path=f.path,h.object=f.node,h.name=f.node.name,h.isRoot=f.path==="/"}catch(I){h.error=I.errno}return h},createPath:(c,d,h,f)=>{c=typeof c=="string"?c:_.getPath(c);for(var I=d.split("/").reverse();I.length;){var b=I.pop();if(b){var R=me.join2(c,b);try{_.mkdir(R)}catch(v){}c=R}}return R},createFile:(c,d,h,f,I)=>{var b=me.join2(typeof c=="string"?c:_.getPath(c),d),R=li(f,I);return _.create(b,R)},createDataFile:(c,d,h,f,I,b)=>{var R=d;c&&(c=typeof c=="string"?c:_.getPath(c),R=d?me.join2(c,d):c);var v=li(f,I),V=_.create(R,v);if(h){if(typeof h=="string"){for(var L=new Array(h.length),ee=0,ae=h.length;ee<ae;++ee)L[ee]=h.charCodeAt(ee);h=L}_.chmod(V,146|v);var ce=_.open(V,577);_.write(ce,h,0,h.length,0,b),_.close(ce),_.chmod(V,v)}return V},createDevice:(c,d,h,f)=>{var I=me.join2(typeof c=="string"?c:_.getPath(c),d),b=li(!!h,!!f);_.createDevice.major||(_.createDevice.major=64);var R=_.makedev(_.createDevice.major++,0);return _.registerDevice(R,{open:v=>{v.seekable=!1},close:v=>{f&&f.buffer&&f.buffer.length&&f(10)},read:(v,V,L,ee,ae)=>{for(var ce=0,ne=0;ne<ee;ne++){var Ce;try{Ce=h()}catch(Ve){throw new _.ErrnoError(29)}if(Ce===void 0&&ce===0)throw new _.ErrnoError(6);if(Ce==null)break;ce++,V[L+ne]=Ce}return ce&&(v.node.timestamp=Date.now()),ce},write:(v,V,L,ee,ae)=>{for(var ce=0;ce<ee;ce++)try{f(V[L+ce])}catch(ne){throw new _.ErrnoError(29)}return ee&&(v.node.timestamp=Date.now()),ce}}),_.mkdev(I,b,R)},forceLoadFile:c=>{if(c.isDevice||c.isFolder||c.link||c.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{c.contents=Ds(s(c.url),!0),c.usedBytes=c.contents.length}catch(d){throw new _.ErrnoError(29)}},createLazyFile:(c,d,h,f,I)=>{function b(){this.lengthKnown=!1,this.chunks=[]}if(b.prototype.get=function(ae){if(!(ae>this.length-1||ae<0)){var ce=ae%this.chunkSize,ne=ae/this.chunkSize|0;return this.getter(ne)[ce]}},b.prototype.setDataGetter=function(ae){this.getter=ae},b.prototype.cacheLength=function(){var ae=new XMLHttpRequest;if(ae.open("HEAD",h,!1),ae.send(null),!(ae.status>=200&&ae.status<300||ae.status===304))throw new Error("Couldn't load "+h+". Status: "+ae.status);var ce,ne=Number(ae.getResponseHeader("Content-length")),Ce=(ce=ae.getResponseHeader("Accept-Ranges"))&&ce==="bytes",Ve=(ce=ae.getResponseHeader("Content-Encoding"))&&ce==="gzip",Oe=1048576;Ce||(Oe=ne);var nt=this;nt.setDataGetter(et=>{var Tt=et*Oe,Ki=(et+1)*Oe-1;if(Ki=Math.min(Ki,ne-1),nt.chunks[et]===void 0&&(nt.chunks[et]=((fr,Vo)=>{if(fr>Vo)throw new Error("invalid range ("+fr+", "+Vo+") or no bytes requested!");if(Vo>ne-1)throw new Error("only "+ne+" bytes available! programmer error!");var pt=new XMLHttpRequest;if(pt.open("GET",h,!1),ne!==Oe&&pt.setRequestHeader("Range","bytes="+fr+"-"+Vo),pt.responseType="arraybuffer",pt.overrideMimeType&&pt.overrideMimeType("text/plain; charset=x-user-defined"),pt.send(null),!(pt.status>=200&&pt.status<300||pt.status===304))throw new Error("Couldn't load "+h+". Status: "+pt.status);return pt.response!==void 0?new Uint8Array(pt.response||[]):Ds(pt.responseText||"",!0)})(Tt,Ki)),nt.chunks[et]===void 0)throw new Error("doXHR failed!");return nt.chunks[et]}),!Ve&&ne||(Oe=ne=1,ne=this.getter(0).length,Oe=ne,C("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=ne,this._chunkSize=Oe,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!g)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var R=new b;Object.defineProperties(R,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var v={isDevice:!1,contents:R}}else v={isDevice:!1,url:h};var V=_.createFile(c,d,v,f,I);v.contents?V.contents=v.contents:v.url&&(V.contents=null,V.url=v.url),Object.defineProperties(V,{usedBytes:{get:function(){return this.contents.length}}});var L={};function ee(ae,ce,ne,Ce,Ve){var Oe=ae.node.contents;if(Ve>=Oe.length)return 0;var nt=Math.min(Oe.length-Ve,Ce);if(Oe.slice)for(var et=0;et<nt;et++)ce[ne+et]=Oe[Ve+et];else for(et=0;et<nt;et++)ce[ne+et]=Oe.get(Ve+et);return nt}return Object.keys(V.stream_ops).forEach(ae=>{var ce=V.stream_ops[ae];L[ae]=function(){return _.forceLoadFile(V),ce.apply(null,arguments)}}),L.read=(ae,ce,ne,Ce,Ve)=>(_.forceLoadFile(V),ee(ae,ce,ne,Ce,Ve)),L.mmap=(ae,ce,ne,Ce,Ve)=>{_.forceLoadFile(V);var Oe=Wn();if(!Oe)throw new _.ErrnoError(48);return ee(ae,Z,Oe,ce,ne),{ptr:Oe,allocated:!0}},V.stream_ops=L,V}},ji=(c,d)=>c?Bt(ue,c,d):"",At={DEFAULT_POLLMASK:5,calculateAt:function(c,d,h){if(me.isAbs(d))return d;var f;if(c===-100?f=_.cwd():f=At.getStreamFromFD(c).path,d.length==0){if(!h)throw new _.ErrnoError(44);return f}return me.join2(f,d)},doStat:function(c,d,h){try{var f=c(d)}catch(v){if(v&&v.node&&me.normalize(d)!==me.normalize(_.getPath(v.node)))return-54;throw v}H[h>>2]=f.dev,H[h+4>>2]=f.mode,Pe[h+8>>2]=f.nlink,H[h+12>>2]=f.uid,H[h+16>>2]=f.gid,H[h+20>>2]=f.rdev,Ke=[f.size>>>0,(Te=f.size,+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[h+24>>2]=Ke[0],H[h+28>>2]=Ke[1],H[h+32>>2]=4096,H[h+36>>2]=f.blocks;var I=f.atime.getTime(),b=f.mtime.getTime(),R=f.ctime.getTime();return Ke=[Math.floor(I/1e3)>>>0,(Te=Math.floor(I/1e3),+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[h+40>>2]=Ke[0],H[h+44>>2]=Ke[1],Pe[h+48>>2]=I%1e3*1e3,Ke=[Math.floor(b/1e3)>>>0,(Te=Math.floor(b/1e3),+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[h+56>>2]=Ke[0],H[h+60>>2]=Ke[1],Pe[h+64>>2]=b%1e3*1e3,Ke=[Math.floor(R/1e3)>>>0,(Te=Math.floor(R/1e3),+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[h+72>>2]=Ke[0],H[h+76>>2]=Ke[1],Pe[h+80>>2]=R%1e3*1e3,Ke=[f.ino>>>0,(Te=f.ino,+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[h+88>>2]=Ke[0],H[h+92>>2]=Ke[1],0},doMsync:function(c,d,h,f,I){if(!_.isFile(d.node.mode))throw new _.ErrnoError(43);if(2&f)return 0;var b=ue.slice(c,c+h);_.msync(d,b,I,h,f)},varargs:void 0,get:()=>(At.varargs+=4,H[At.varargs-4>>2]),getStr:c=>ji(c),getStreamFromFD:function(c){return _.getStreamChecked(c)}};function mi(c){switch(c){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${c}`)}}var Ac=void 0;function Dt(c){for(var d="",h=c;ue[h];)d+=Ac[ue[h++]];return d}var k={},pr={},ws={},qi=void 0;function Ue(c){throw new qi(c)}var bc=void 0;function or(c){throw new bc(c)}function zr(c,d,h){function f(v){var V=h(v);V.length!==c.length&&or("Mismatched type converter count");for(var L=0;L<c.length;++L)sr(c[L],V[L])}c.forEach(function(v){ws[v]=d});var I=new Array(d.length),b=[],R=0;d.forEach((v,V)=>{pr.hasOwnProperty(v)?I[V]=pr[v]:(b.push(v),k.hasOwnProperty(v)||(k[v]=[]),k[v].push(()=>{I[V]=pr[v],++R===b.length&&f(I)}))}),b.length===0&&f(I)}function sr(c,d,h={}){if(!("argPackAdvance"in d))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(f,I,b={}){var R=I.name;if(f||Ue(`type "${R}" must have a positive integer typeid pointer`),pr.hasOwnProperty(f)){if(b.ignoreDuplicateRegistrations)return;Ue(`Cannot register type '${R}' twice`)}if(pr[f]=I,delete ws[f],k.hasOwnProperty(f)){var v=k[f];delete k[f],v.forEach(V=>V())}}(c,d,h)}function Rc(c){if(!(this instanceof vr)||!(c instanceof vr))return!1;for(var d=this.$$.ptrType.registeredClass,h=this.$$.ptr,f=c.$$.ptrType.registeredClass,I=c.$$.ptr;d.baseClass;)h=d.upcast(h),d=d.baseClass;for(;f.baseClass;)I=f.upcast(I),f=f.baseClass;return d===f&&h===I}function Gn(c){Ue(c.$$.ptrType.registeredClass.name+" instance already deleted")}var Mo=!1;function vc(c){}function Cc(c){c.count.value-=1,c.count.value===0&&function(d){d.smartPtr?d.smartPtrType.rawDestructor(d.smartPtr):d.ptrType.registeredClass.rawDestructor(d.ptr)}(c)}function Nc(c,d,h){if(d===h)return c;if(h.baseClass===void 0)return null;var f=Nc(c,d,h.baseClass);return f===null?null:h.downcast(f)}var Oo={};function Sl(){return Object.keys(Po).length}function yl(){var c=[];for(var d in Po)Po.hasOwnProperty(d)&&c.push(Po[d]);return c}var xo=[];function nr(){for(;xo.length;){var c=xo.pop();c.$$.deleteScheduled=!1,c.delete()}}var Jr=void 0;function Dc(c){Jr=c,xo.length&&Jr&&Jr(nr)}var Po={};function zi(c,d){return d=function(h,f){for(f===void 0&&Ue("ptr should not be undefined");h.baseClass;)f=h.upcast(f),h=h.baseClass;return f}(c,d),Po[d]}function ko(c,d){return d.ptrType&&d.ptr||or("makeClassHandle requires ptr and ptrType"),!!d.smartPtrType!=!!d.smartPtr&&or("Both smartPtrType and smartPtr must be specified"),d.count={value:1},Ji(Object.create(c,{$$:{value:d}}))}function wc(c){var d=this.getPointee(c);if(!d)return this.destructor(c),null;var h=zi(this.registeredClass,d);if(h!==void 0){if(h.$$.count.value===0)return h.$$.ptr=d,h.$$.smartPtr=c,h.clone();var f=h.clone();return this.destructor(c),f}function I(){return this.isSmartPointer?ko(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:d,smartPtrType:this,smartPtr:c}):ko(this.registeredClass.instancePrototype,{ptrType:this,ptr:c})}var b,R=this.registeredClass.getActualType(d),v=Oo[R];if(!v)return I.call(this);b=this.isConst?v.constPointerType:v.pointerType;var V=Nc(d,this.registeredClass,b.registeredClass);return V===null?I.call(this):this.isSmartPointer?ko(b.registeredClass.instancePrototype,{ptrType:b,ptr:V,smartPtrType:this,smartPtr:c}):ko(b.registeredClass.instancePrototype,{ptrType:b,ptr:V})}var Ji=function(c){return typeof FinalizationRegistry=="undefined"?(Ji=d=>d,c):(Mo=new FinalizationRegistry(d=>{Cc(d.$$)}),vc=d=>Mo.unregister(d),(Ji=d=>{var h=d.$$;if(h.smartPtr){var f={$$:h};Mo.register(d,f,d)}return d})(c))};function Mc(){if(this.$$.ptr||Gn(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var c,d=Ji(Object.create(Object.getPrototypeOf(this),{$$:{value:(c=this.$$,{count:c.count,deleteScheduled:c.deleteScheduled,preservePointerOnDelete:c.preservePointerOnDelete,ptr:c.ptr,ptrType:c.ptrType,smartPtr:c.smartPtr,smartPtrType:c.smartPtrType})}}));return d.$$.count.value+=1,d.$$.deleteScheduled=!1,d}function Al(){this.$$.ptr||Gn(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ue("Object already scheduled for deletion"),vc(this),Cc(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Oc(){return!this.$$.ptr}function xc(){return this.$$.ptr||Gn(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ue("Object already scheduled for deletion"),xo.push(this),xo.length===1&&Jr&&Jr(nr),this.$$.deleteScheduled=!0,this}function vr(){}function Ht(c){if(c===void 0)return"_unknown";var d=(c=c.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return d>=48&&d<=57?`_${c}`:c}function Ms(c,d){return c=Ht(c),{[c]:function(){return d.apply(this,arguments)}}[c]}function Pc(c,d,h){if(c[d].overloadTable===void 0){var f=c[d];c[d]=function(){return c[d].overloadTable.hasOwnProperty(arguments.length)||Ue(`Function '${h}' called with an invalid number of arguments (${arguments.length}) - expects one of (${c[d].overloadTable})!`),c[d].overloadTable[arguments.length].apply(this,arguments)},c[d].overloadTable=[],c[d].overloadTable[f.argCount]=f}}function Os(c,d,h,f,I,b,R,v){this.name=c,this.constructor=d,this.instancePrototype=h,this.rawDestructor=f,this.baseClass=I,this.getActualType=b,this.upcast=R,this.downcast=v,this.pureVirtualFunctions=[]}function Lo(c,d,h){for(;d!==h;)d.upcast||Ue(`Expected null or instance of ${h.name}, got an instance of ${d.name}`),c=d.upcast(c),d=d.baseClass;return c}function bl(c,d){if(d===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),0;d.$$||Ue(`Cannot pass "${Ls(d)}" as a ${this.name}`),d.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`);var h=d.$$.ptrType.registeredClass;return Lo(d.$$.ptr,h,this.registeredClass)}function Rl(c,d){var h;if(d===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),this.isSmartPointer?(h=this.rawConstructor(),c!==null&&c.push(this.rawDestructor,h),h):0;d.$$||Ue(`Cannot pass "${Ls(d)}" as a ${this.name}`),d.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&d.$$.ptrType.isConst&&Ue(`Cannot convert argument of type ${d.$$.smartPtrType?d.$$.smartPtrType.name:d.$$.ptrType.name} to parameter type ${this.name}`);var f=d.$$.ptrType.registeredClass;if(h=Lo(d.$$.ptr,f,this.registeredClass),this.isSmartPointer)switch(d.$$.smartPtr===void 0&&Ue("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:d.$$.smartPtrType===this?h=d.$$.smartPtr:Ue(`Cannot convert argument of type ${d.$$.smartPtrType?d.$$.smartPtrType.name:d.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:h=d.$$.smartPtr;break;case 2:if(d.$$.smartPtrType===this)h=d.$$.smartPtr;else{var I=d.clone();h=this.rawShare(h,Yi.toHandle(function(){I.delete()})),c!==null&&c.push(this.rawDestructor,h)}break;default:Ue("Unsupporting sharing policy")}return h}function kc(c,d){if(d===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),0;d.$$||Ue(`Cannot pass "${Ls(d)}" as a ${this.name}`),d.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`),d.$$.ptrType.isConst&&Ue(`Cannot convert argument of type ${d.$$.ptrType.name} to parameter type ${this.name}`);var h=d.$$.ptrType.registeredClass;return Lo(d.$$.ptr,h,this.registeredClass)}function Uo(c){return this.fromWireType(H[c>>2])}function vl(c){return this.rawGetPointee&&(c=this.rawGetPointee(c)),c}function Lc(c){this.rawDestructor&&this.rawDestructor(c)}function Cl(c){c!==null&&c.delete()}function Cr(c,d,h,f,I,b,R,v,V,L,ee){this.name=c,this.registeredClass=d,this.isReference=h,this.isConst=f,this.isSmartPointer=I,this.pointeeType=b,this.sharingPolicy=R,this.rawGetPointee=v,this.rawConstructor=V,this.rawShare=L,this.rawDestructor=ee,I||d.baseClass!==void 0?this.toWireType=Rl:f?(this.toWireType=bl,this.destructorFunction=null):(this.toWireType=kc,this.destructorFunction=null)}var xs=[],Uc=c=>{var d=xs[c];return d||(c>=xs.length&&(xs.length=c+1),xs[c]=d=Vn.get(c)),d},Nl=(c,d,h)=>c.includes("j")?((f,I,b)=>{var R=o["dynCall_"+f];return b&&b.length?R.apply(null,[I].concat(b)):R.call(null,I)})(c,d,h):Uc(d).apply(null,h);function Xi(c,d){var h,f,I,b=(c=Dt(c)).includes("j")?(h=c,f=d,I=[],function(){return I.length=0,Object.assign(I,arguments),Nl(h,f,I)}):Uc(d);return typeof b!="function"&&Ue(`unknown function pointer with signature ${c}: ${d}`),b}var Vc=void 0;function Ps(c){var d=Dr(c),h=Dt(d);return wt(d),h}function ks(c,d){var h=[],f={};throw d.forEach(function I(b){f[b]||pr[b]||(ws[b]?ws[b].forEach(I):(h.push(b),f[b]=!0))}),new Vc(`${c}: `+h.map(Ps).join([", "]))}function jn(c,d){for(var h=[],f=0;f<c;f++)h.push(Pe[d+4*f>>2]);return h}function Fc(c){for(;c.length;){var d=c.pop();c.pop()(d)}}function qn(c,d){if(!(c instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof c} which is not a function`);var h=Ms(c.name||"unknownFunctionName",function(){});h.prototype=c.prototype;var f=new h,I=c.apply(f,d);return I instanceof Object?I:f}function Qi(c,d,h,f,I,b){var R=d.length;R<2&&Ue("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var v=d[1]!==null&&h!==null,V=!1,L=1;L<d.length;++L)if(d[L]!==null&&d[L].destructorFunction===void 0){V=!0;break}var ee=d[0].name!=="void",ae="",ce="";for(L=0;L<R-2;++L)ae+=(L!==0?", ":"")+"arg"+L,ce+=(L!==0?", ":"")+"arg"+L+"Wired";var ne=`
|
|
53
|
+
return function ${Ht(c)}(${ae}) {
|
|
54
|
+
if (arguments.length !== ${R-2}) {
|
|
55
|
+
throwBindingError('function ${c} called with ${arguments.length} arguments, expected ${R-2} args!');
|
|
56
|
+
}`;V&&(ne+=`var destructors = [];
|
|
57
|
+
`);var Ce=V?"destructors":"null",Ve=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],Oe=[Ue,f,I,Fc,d[0],d[1]];for(v&&(ne+="var thisWired = classParam.toWireType("+Ce+`, this);
|
|
58
|
+
`),L=0;L<R-2;++L)ne+="var arg"+L+"Wired = argType"+L+".toWireType("+Ce+", arg"+L+"); // "+d[L+2].name+`
|
|
59
|
+
`,Ve.push("argType"+L),Oe.push(d[L+2]);if(v&&(ce="thisWired"+(ce.length>0?", ":"")+ce),ne+=(ee||b?"var rv = ":"")+"invoker(fn"+(ce.length>0?", ":"")+ce+`);
|
|
60
|
+
`,V)ne+=`runDestructors(destructors);
|
|
61
|
+
`;else for(L=v?1:2;L<d.length;++L){var nt=L===1?"thisWired":"arg"+(L-2)+"Wired";d[L].destructorFunction!==null&&(ne+=nt+"_dtor("+nt+"); // "+d[L].name+`
|
|
62
|
+
`,Ve.push(nt+"_dtor"),Oe.push(d[L].destructorFunction))}return ee&&(ne+=`var ret = retType.fromWireType(rv);
|
|
63
|
+
return ret;
|
|
64
|
+
`),ne+=`}
|
|
65
|
+
`,Ve.push(ne),qn(Function,Ve).apply(null,Oe)}function $c(){this.allocated=[void 0],this.freelist=[]}var Wt=new $c;function Bc(c){c>=Wt.reserved&&--Wt.get(c).refcount==0&&Wt.free(c)}function Nr(){for(var c=0,d=Wt.reserved;d<Wt.allocated.length;++d)Wt.allocated[d]!==void 0&&++c;return c}var Yi={toValue:c=>(c||Ue("Cannot use deleted val. handle = "+c),Wt.get(c).value),toHandle:c=>{switch(c){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Wt.allocate({refcount:1,value:c})}}};function Ls(c){if(c===null)return"null";var d=typeof c;return d==="object"||d==="array"||d==="function"?c.toString():""+c}function Hc(c,d){switch(d){case 2:return function(h){return this.fromWireType(Ln[h>>2])};case 3:return function(h){return this.fromWireType(Un[h>>3])};default:throw new TypeError("Unknown float type: "+c)}}function Wc(c,d,h){switch(d){case 0:return h?function(f){return Z[f]}:function(f){return ue[f]};case 1:return h?function(f){return Se[f>>1]}:function(f){return Ye[f>>1]};case 2:return h?function(f){return H[f>>2]}:function(f){return Pe[f>>2]};default:throw new TypeError("Unknown integer type: "+c)}}var S=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,T=(c,d)=>{for(var h=c,f=h>>1,I=f+d/2;!(f>=I)&&Ye[f];)++f;if((h=f<<1)-c>32&&S)return S.decode(ue.subarray(c,h));for(var b="",R=0;!(R>=d/2);++R){var v=Se[c+2*R>>1];if(v==0)break;b+=String.fromCharCode(v)}return b},w=(c,d,h)=>{if(h===void 0&&(h=2147483647),h<2)return 0;for(var f=d,I=(h-=2)<2*c.length?h/2:c.length,b=0;b<I;++b){var R=c.charCodeAt(b);Se[d>>1]=R,d+=2}return Se[d>>1]=0,d-f},P=c=>2*c.length,B=(c,d)=>{for(var h=0,f="";!(h>=d/4);){var I=H[c+4*h>>2];if(I==0)break;if(++h,I>=65536){var b=I-65536;f+=String.fromCharCode(55296|b>>10,56320|1023&b)}else f+=String.fromCharCode(I)}return f},W=(c,d,h)=>{if(h===void 0&&(h=2147483647),h<4)return 0;for(var f=d,I=f+h-4,b=0;b<c.length;++b){var R=c.charCodeAt(b);if(R>=55296&&R<=57343&&(R=65536+((1023&R)<<10)|1023&c.charCodeAt(++b)),H[d>>2]=R,(d+=4)+4>I)break}return H[d>>2]=0,d-f},z=c=>{for(var d=0,h=0;h<c.length;++h){var f=c.charCodeAt(h);f>=55296&&f<=57343&&++h,d+=4}return d},Y={},re=[],G=[],he={},De=()=>{if(!De.strings){var c={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 c[d]:c[d]=he[d];var h=[];for(var d in c)h.push(`${d}=${c[d]}`);De.strings=h}return De.strings},ve,fe,we,st=function(c,d,h,f){c||(c=this),this.parent=c,this.mount=c.mount,this.mounted=null,this.id=_.nextInode++,this.name=d,this.mode=h,this.node_ops={},this.stream_ops={},this.rdev=f},Je=365,gt=146;Object.defineProperties(st.prototype,{read:{get:function(){return(this.mode&Je)===Je},set:function(c){c?this.mode|=Je:this.mode&=-366}},write:{get:function(){return(this.mode>)===gt},set:function(c){c?this.mode|=gt:this.mode&=-147}},isFolder:{get:function(){return _.isDir(this.mode)}},isDevice:{get:function(){return _.isChrdev(this.mode)}}}),_.FSNode=st,_.createPreloadedFile=function(c,d,h,f,I,b,R,v,V,L){var ee=d?Zt.resolve(me.join2(c,d)):c;function ae(ce){function ne(Ce){L&&L(),v||_.createDataFile(c,d,Ce,f,I,V),b&&b(),No()}(function(Ce,Ve,Oe,nt){typeof Browser!="undefined"&&Browser.init();var et=!1;return Il.forEach(function(Tt){et||Tt.canHandle(Ve)&&(Tt.handle(Ce,Ve,Oe,nt),et=!0)}),et})(ce,ee,ne,()=>{R&&R(),No()})||ne(ce)}ie(),typeof h=="string"?Tl(h,ce=>ae(ce),R):ae(h)},_.staticInit(),function(){for(var c=new Array(256),d=0;d<256;++d)c[d]=String.fromCharCode(d);Ac=c}(),qi=o.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},bc=o.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},vr.prototype.isAliasOf=Rc,vr.prototype.clone=Mc,vr.prototype.delete=Al,vr.prototype.isDeleted=Oc,vr.prototype.deleteLater=xc,o.getInheritedInstanceCount=Sl,o.getLiveInheritedInstances=yl,o.flushPendingDeletes=nr,o.setDelayFunction=Dc,Cr.prototype.getPointee=vl,Cr.prototype.destructor=Lc,Cr.prototype.argPackAdvance=8,Cr.prototype.readValueFromPointer=Uo,Cr.prototype.deleteObject=Cl,Cr.prototype.fromWireType=wc,Vc=o.UnboundTypeError=(ve=Error,(we=Ms(fe="UnboundTypeError",function(c){this.name=fe,this.message=c;var d=new Error(c).stack;d!==void 0&&(this.stack=this.toString()+`
|
|
66
|
+
`+d.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(ve.prototype),we.prototype.constructor=we,we.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},we),Object.assign($c.prototype,{get(c){return this.allocated[c]},has(c){return this.allocated[c]!==void 0},allocate(c){var d=this.freelist.pop()||this.allocated.length;return this.allocated[d]=c,d},free(c){this.allocated[c]=void 0,this.freelist.push(c)}}),Wt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Wt.reserved=Wt.allocated.length,o.count_emval_handles=Nr;var Xe,xt={p:function(c,d,h){throw new Wi(c).init(d,h),c},C:function(c,d,h){At.varargs=h;try{var f=At.getStreamFromFD(c);switch(d){case 0:return(I=At.get())<0?-28:_.createStream(f,I).fd;case 1:case 2:case 6:case 7:return 0;case 3:return f.flags;case 4:var I=At.get();return f.flags|=I,0;case 5:return I=At.get(),Se[I+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return b=28,H[zn()>>2]=b,-1}}catch(R){if(_===void 0||R.name!=="ErrnoError")throw R;return-R.errno}var b},w:function(c,d,h,f){At.varargs=f;try{d=At.getStr(d),d=At.calculateAt(c,d);var I=f?At.get():0;return _.open(d,h,I).fd}catch(b){if(_===void 0||b.name!=="ErrnoError")throw b;return-b.errno}},t:function(c,d,h,f,I){},n:function(c,d,h,f,I){var b=mi(h);sr(c,{name:d=Dt(d),fromWireType:function(R){return!!R},toWireType:function(R,v){return v?f:I},argPackAdvance:8,readValueFromPointer:function(R){var v;if(h===1)v=Z;else if(h===2)v=Se;else{if(h!==4)throw new TypeError("Unknown boolean type size: "+d);v=H}return this.fromWireType(v[R>>b])},destructorFunction:null})},r:function(c,d,h,f,I,b,R,v,V,L,ee,ae,ce){ee=Dt(ee),b=Xi(I,b),v&&(v=Xi(R,v)),L&&(L=Xi(V,L)),ce=Xi(ae,ce);var ne=Ht(ee);(function(Ce,Ve,Oe){o.hasOwnProperty(Ce)?((Oe===void 0||o[Ce].overloadTable!==void 0&&o[Ce].overloadTable[Oe]!==void 0)&&Ue(`Cannot register public name '${Ce}' twice`),Pc(o,Ce,Ce),o.hasOwnProperty(Oe)&&Ue(`Cannot register multiple overloads of a function with the same number of arguments (${Oe})!`),o[Ce].overloadTable[Oe]=Ve):(o[Ce]=Ve,Oe!==void 0&&(o[Ce].numArguments=Oe))})(ne,function(){ks(`Cannot construct ${ee} due to unbound types`,[f])}),zr([c,d,h],f?[f]:[],function(Ce){var Ve,Oe;Ce=Ce[0],Oe=f?(Ve=Ce.registeredClass).instancePrototype:vr.prototype;var nt=Ms(ne,function(){if(Object.getPrototypeOf(this)!==et)throw new qi("Use 'new' to construct "+ee);if(Tt.constructor_body===void 0)throw new qi(ee+" has no accessible constructor");var pt=Tt.constructor_body[arguments.length];if(pt===void 0)throw new qi(`Tried to invoke ctor of ${ee} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Tt.constructor_body).toString()}) parameters instead!`);return pt.apply(this,arguments)}),et=Object.create(Oe,{constructor:{value:nt}});nt.prototype=et;var Tt=new Os(ee,nt,et,ce,Ve,b,v,L);Tt.baseClass&&(Tt.baseClass.__derivedClasses===void 0&&(Tt.baseClass.__derivedClasses=[]),Tt.baseClass.__derivedClasses.push(Tt));var Ki=new Cr(ee,Tt,!0,!1,!1),fr=new Cr(ee+"*",Tt,!1,!1,!1),Vo=new Cr(ee+" const*",Tt,!1,!0,!1);return Oo[c]={pointerType:fr,constPointerType:Vo},function(pt,Jp,Dl){o.hasOwnProperty(pt)||or("Replacing nonexistant public symbol"),o[pt].overloadTable!==void 0&&Dl!==void 0?o[pt].overloadTable[Dl]=Jp:(o[pt]=Jp,o[pt].argCount=Dl)}(ne,nt),[Ki,fr,Vo]})},q:function(c,d,h,f,I,b){var R=jn(d,h);I=Xi(f,I),zr([],[c],function(v){var V=`constructor ${(v=v[0]).name}`;if(v.registeredClass.constructor_body===void 0&&(v.registeredClass.constructor_body=[]),v.registeredClass.constructor_body[d-1]!==void 0)throw new qi(`Cannot register multiple constructors with identical number of parameters (${d-1}) for class '${v.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return v.registeredClass.constructor_body[d-1]=()=>{ks(`Cannot construct ${v.name} due to unbound types`,R)},zr([],R,function(L){return L.splice(1,0,null),v.registeredClass.constructor_body[d-1]=Qi(V,L,null,I,b),[]}),[]})},d:function(c,d,h,f,I,b,R,v,V){var L=jn(h,f);d=Dt(d),b=Xi(I,b),zr([],[c],function(ee){var ae=`${(ee=ee[0]).name}.${d}`;function ce(){ks(`Cannot call ${ae} due to unbound types`,L)}d.startsWith("@@")&&(d=Symbol[d.substring(2)]),v&&ee.registeredClass.pureVirtualFunctions.push(d);var ne=ee.registeredClass.instancePrototype,Ce=ne[d];return Ce===void 0||Ce.overloadTable===void 0&&Ce.className!==ee.name&&Ce.argCount===h-2?(ce.argCount=h-2,ce.className=ee.name,ne[d]=ce):(Pc(ne,d,ae),ne[d].overloadTable[h-2]=ce),zr([],L,function(Ve){var Oe=Qi(ae,Ve,ee,b,R,V);return ne[d].overloadTable===void 0?(Oe.argCount=h-2,ne[d]=Oe):ne[d].overloadTable[h-2]=Oe,[]}),[]})},D:function(c,d){sr(c,{name:d=Dt(d),fromWireType:function(h){var f=Yi.toValue(h);return Bc(h),f},toWireType:function(h,f){return Yi.toHandle(f)},argPackAdvance:8,readValueFromPointer:Uo,destructorFunction:null})},k:function(c,d,h){var f=mi(h);sr(c,{name:d=Dt(d),fromWireType:function(I){return I},toWireType:function(I,b){return b},argPackAdvance:8,readValueFromPointer:Hc(d,f),destructorFunction:null})},c:function(c,d,h,f,I){d=Dt(d),I===-1&&(I=4294967295);var b=mi(h),R=L=>L;if(f===0){var v=32-8*h;R=L=>L<<v>>>v}var V=d.includes("unsigned");sr(c,{name:d,fromWireType:R,toWireType:V?function(L,ee){return this.name,ee>>>0}:function(L,ee){return this.name,ee},argPackAdvance:8,readValueFromPointer:Wc(d,b,f!==0),destructorFunction:null})},b:function(c,d,h){var f=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][d];function I(b){var R=Pe,v=R[b>>=2],V=R[b+1];return new f(R.buffer,V,v)}sr(c,{name:h=Dt(h),fromWireType:I,argPackAdvance:8,readValueFromPointer:I},{ignoreDuplicateRegistrations:!0})},j:function(c,d){var h=(d=Dt(d))==="std::string";sr(c,{name:d,fromWireType:function(f){var I,b=Pe[f>>2],R=f+4;if(h)for(var v=R,V=0;V<=b;++V){var L=R+V;if(V==b||ue[L]==0){var ee=ji(v,L-v);I===void 0?I=ee:(I+="\0",I+=ee),v=L+1}}else{var ae=new Array(b);for(V=0;V<b;++V)ae[V]=String.fromCharCode(ue[R+V]);I=ae.join("")}return wt(f),I},toWireType:function(f,I){var b;I instanceof ArrayBuffer&&(I=new Uint8Array(I));var R=typeof I=="string";R||I instanceof Uint8Array||I instanceof Uint8ClampedArray||I instanceof Int8Array||Ue("Cannot pass non-string to std::string"),b=h&&R?Do(I):I.length;var v=Zi(4+b+1),V=v+4;if(Pe[v>>2]=b,h&&R)wo(I,ue,V,b+1);else if(R)for(var L=0;L<b;++L){var ee=I.charCodeAt(L);ee>255&&(wt(V),Ue("String has UTF-16 code units that do not fit in 8 bits")),ue[V+L]=ee}else for(L=0;L<b;++L)ue[V+L]=I[L];return f!==null&&f.push(wt,v),v},argPackAdvance:8,readValueFromPointer:Uo,destructorFunction:function(f){wt(f)}})},f:function(c,d,h){var f,I,b,R,v;h=Dt(h),d===2?(f=T,I=w,R=P,b=()=>Ye,v=1):d===4&&(f=B,I=W,R=z,b=()=>Pe,v=2),sr(c,{name:h,fromWireType:function(V){for(var L,ee=Pe[V>>2],ae=b(),ce=V+4,ne=0;ne<=ee;++ne){var Ce=V+4+ne*d;if(ne==ee||ae[Ce>>v]==0){var Ve=f(ce,Ce-ce);L===void 0?L=Ve:(L+="\0",L+=Ve),ce=Ce+d}}return wt(V),L},toWireType:function(V,L){typeof L!="string"&&Ue(`Cannot pass non-string to C++ string type ${h}`);var ee=R(L),ae=Zi(4+ee+d);return Pe[ae>>2]=ee>>v,I(L,ae+4,ee+d),V!==null&&V.push(wt,ae),ae},argPackAdvance:8,readValueFromPointer:Uo,destructorFunction:function(V){wt(V)}})},o:function(c,d){sr(c,{isVoid:!0,name:d=Dt(d),argPackAdvance:0,fromWireType:function(){},toWireType:function(h,f){}})},g:function(c,d,h,f){var I,b;(c=re[c])(d=Yi.toValue(d),h=(b=Y[I=h])===void 0?Dt(I):b,null,f)},m:Bc,l:function(c,d){var h=function(Ve,Oe){for(var nt,et,Tt,Ki=new Array(Ve),fr=0;fr<Ve;++fr)Ki[fr]=(nt=Pe[Oe+4*fr>>2],et="parameter "+fr,Tt=void 0,(Tt=pr[nt])===void 0&&Ue(et+" has unknown type "+Ps(nt)),Tt);return Ki}(c,d),f=h[0],I=f.name+"_$"+h.slice(1).map(function(Ve){return Ve.name}).join("_")+"$",b=G[I];if(b!==void 0)return b;for(var R=["retType"],v=[f],V="",L=0;L<c-1;++L)V+=(L!==0?", ":"")+"arg"+L,R.push("argType"+L),v.push(h[1+L]);var ee="return function "+Ht("methodCaller_"+I)+`(handle, name, destructors, args) {
|
|
67
|
+
`,ae=0;for(L=0;L<c-1;++L)ee+=" var arg"+L+" = argType"+L+".readValueFromPointer(args"+(ae?"+"+ae:"")+`);
|
|
68
|
+
`,ae+=h[L+1].argPackAdvance;for(ee+=" var rv = handle[name]("+V+`);
|
|
69
|
+
`,L=0;L<c-1;++L)h[L+1].deleteObject&&(ee+=" argType"+L+".deleteObject(arg"+L+`);
|
|
70
|
+
`);f.isVoid||(ee+=` return retType.toWireType(destructors, rv);
|
|
71
|
+
`),ee+=`};
|
|
72
|
+
`,R.push(ee);var ce,ne,Ce=qn(Function,R).apply(null,v);return ce=Ce,ne=re.length,re.push(ce),b=ne,G[I]=b,b},a:()=>{jr("")},e:function(){return Date.now()},v:()=>ue.length,A:(c,d,h)=>ue.copyWithin(c,d,d+h),u:c=>{ue.length,jr("OOM")},y:(c,d)=>{var h=0;return De().forEach(function(f,I){var b=d+h;Pe[c+4*I>>2]=b,((R,v)=>{for(var V=0;V<R.length;++V)Z[0|v++]=R.charCodeAt(V);Z[0|v]=0})(f,b),h+=f.length+1}),0},z:(c,d)=>{var h=De();Pe[c>>2]=h.length;var f=0;return h.forEach(function(I){f+=I.length+1}),Pe[d>>2]=f,0},i:function(c){try{var d=At.getStreamFromFD(c);return _.close(d),0}catch(h){if(_===void 0||h.name!=="ErrnoError")throw h;return h.errno}},x:function(c,d){try{var h=At.getStreamFromFD(c),f=h.tty?2:_.isDir(h.mode)?3:_.isLink(h.mode)?7:4;return Z[d|0]=f,Se[d+2>>1]=0,Ke=[0,(Te=0,+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[d+8>>2]=Ke[0],H[d+12>>2]=Ke[1],Ke=[0,(Te=0,+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[d+16>>2]=Ke[0],H[d+20>>2]=Ke[1],0}catch(I){if(_===void 0||I.name!=="ErrnoError")throw I;return I.errno}},B:function(c,d,h,f){try{var I=((b,R,v,V)=>{for(var L=0,ee=0;ee<v;ee++){var ae=Pe[R>>2],ce=Pe[R+4>>2];R+=8;var ne=_.read(b,Z,ae,ce,V);if(ne<0)return-1;if(L+=ne,ne<ce)break;V!==void 0&&(V+=ne)}return L})(At.getStreamFromFD(c),d,h);return Pe[f>>2]=I,0}catch(b){if(_===void 0||b.name!=="ErrnoError")throw b;return b.errno}},s:function(c,d,h,f,I){var b,R,v=(R=h)+2097152>>>0<4194305-!!(b=d)?(b>>>0)+4294967296*R:NaN;try{if(isNaN(v))return 61;var V=At.getStreamFromFD(c);return _.llseek(V,v,f),Ke=[V.position>>>0,(Te=V.position,+Math.abs(Te)>=1?Te>0?+Math.floor(Te/4294967296)>>>0:~~+Math.ceil((Te-+(~~Te>>>0))/4294967296)>>>0:0)],H[I>>2]=Ke[0],H[I+4>>2]=Ke[1],V.getdents&&v===0&&f===0&&(V.getdents=null),0}catch(L){if(_===void 0||L.name!=="ErrnoError")throw L;return L.errno}},h:function(c,d,h,f){try{var I=((b,R,v,V)=>{for(var L=0,ee=0;ee<v;ee++){var ae=Pe[R>>2],ce=Pe[R+4>>2];R+=8;var ne=_.write(b,Z,ae,ce,V);if(ne<0)return-1;L+=ne,V!==void 0&&(V+=ne)}return L})(At.getStreamFromFD(c),d,h);return Pe[f>>2]=I,0}catch(b){if(_===void 0||b.name!=="ErrnoError")throw b;return b.errno}}},Zi=(function(){var c,d,h,f,I={a:xt};function b(R,v){var V,L,ee=R.exports;return D=(x=ee).E,V=D.buffer,o.HEAP8=Z=new Int8Array(V),o.HEAP16=Se=new Int16Array(V),o.HEAP32=H=new Int32Array(V),o.HEAPU8=ue=new Uint8Array(V),o.HEAPU16=Ye=new Uint16Array(V),o.HEAPU32=Pe=new Uint32Array(V),o.HEAPF32=Ln=new Float32Array(V),o.HEAPF64=Un=new Float64Array(V),Vn=x.H,L=x.F,Ns.unshift(L),No(),ee}if(ie(),o.instantiateWasm)try{return o.instantiateWasm(I,b)}catch(R){N("Module.instantiateWasm callback failed with error: "+R),r(R)}(c=A,d=ui,h=I,f=function(R){b(R.instance)},c||typeof WebAssembly.instantiateStreaming!="function"||$t(d)||typeof fetch!="function"?qr(d,h,f):fetch(d,{credentials:"same-origin"}).then(R=>WebAssembly.instantiateStreaming(R,h).then(f,function(v){return N("wasm streaming compile failed: "+v),N("falling back to ArrayBuffer instantiation"),qr(d,h,f)}))).catch(r)}(),c=>(Zi=x.G)(c)),wt=c=>(wt=x.I)(c),zn=()=>(zn=x.J)(),Dr=c=>(Dr=x.K)(c),Jn=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=x.L)(),c=>(Jn=x.M)(c));o.dynCall_jiji=(c,d,h,f,I)=>(o.dynCall_jiji=x.N)(c,d,h,f,I),o._ff_h264_cabac_tables=67061;function Us(){function c(){Xe||(Xe=!0,o.calledRun=!0,Fn||(o.noFSInit||_.init.initialized||_.init(),_.ignorePermissions=!1,Rr.init(),Hi(Ns),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(),Bi.unshift(d);var d;Hi(Bi)}()))}hr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)d=o.preRun.shift(),Gr.unshift(d);var d;Hi(Gr)}(),hr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),c()},1)):c()))}if(di=function c(){Xe||Us(),Xe||(di=c)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Us(),t.ready}})(),Fy=Vy,$y=class extends ac{constructor(i){super(Fy,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)}},TP=(()=>{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),a=typeof window=="object",u=typeof importScripts=="function",m=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(a||u)&&(u?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):"",u&&(s=S=>{var T=new XMLHttpRequest;return T.open("GET",S,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}));var p,g=o.print||console.log.bind(console),E=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&&(p=o.wasmBinary);var A,C;o.noExitRuntime,typeof WebAssembly!="object"&&hr("no native wasm support detected");var N,D,x,Z,ue,Se,Ye,H,Pe,Ln=!1,Un=[],Vn=[],Fn=[],Gr=0,Ns=null,Bi=null;function hr(S){o.onAbort&&o.onAbort(S),E(S="Aborted("+S+")"),Ln=!0,S+=". Build with -sASSERTIONS for more info.";var T=new WebAssembly.RuntimeError(S);throw r(T),T}var ci,di;function ie(S){return S.startsWith("data:application/octet-stream;base64,")}function No(S){if(S==ci&&p)return new Uint8Array(p);if(s)return s(S);throw"both async and sync fetching of the wasm failed"}function jr(S,T,w){return function(P){return p||!a&&!u||typeof fetch!="function"?Promise.resolve().then(()=>No(P)):fetch(P,{credentials:"same-origin"}).then(B=>{if(!B.ok)throw"failed to load wasm binary file at '"+P+"'";return B.arrayBuffer()}).catch(()=>No(P))}(S).then(P=>WebAssembly.instantiate(P,T)).then(P=>P).then(w,P=>{E("failed to asynchronously prepare wasm: "+P),hr(P)})}ie(ci="videodec_simd.wasm")||(di=ci,ci=o.locateFile?o.locateFile(di,m):m+di);var ui=S=>{for(;S.length>0;)S.shift()(o)};function $n(S){this.excPtr=S,this.ptr=S-24,this.set_type=function(T){Se[this.ptr+4>>2]=T},this.get_type=function(){return Se[this.ptr+4>>2]},this.set_destructor=function(T){Se[this.ptr+8>>2]=T},this.get_destructor=function(){return Se[this.ptr+8>>2]},this.set_caught=function(T){T=T?1:0,N[this.ptr+12|0]=T},this.get_caught=function(){return N[this.ptr+12|0]!=0},this.set_rethrown=function(T){T=T?1:0,N[this.ptr+13|0]=T},this.get_rethrown=function(){return N[this.ptr+13|0]!=0},this.init=function(T,w){this.set_adjusted_ptr(0),this.set_type(T),this.set_destructor(w)},this.set_adjusted_ptr=function(T){Se[this.ptr+16>>2]=T},this.get_adjusted_ptr=function(){return Se[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Hc(this.get_type()))return Se[this.excPtr>>2];var T=this.get_adjusted_ptr();return T!==0?T:this.excPtr}}function Te(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 Ke=void 0;function $t(S){for(var T="",w=S;D[w];)T+=Ke[D[w++]];return T}var J={},qr={},Hi={},Wi=void 0;function me(S){throw new Wi(S)}var Bn=void 0;function Zt(S){throw new Bn(S)}function Gi(S,T,w){function P(Y){var re=w(Y);re.length!==S.length&&Zt("Mismatched type converter count");for(var G=0;G<S.length;++G)Bt(S[G],re[G])}S.forEach(function(Y){Hi[Y]=T});var B=new Array(T.length),W=[],z=0;T.forEach((Y,re)=>{qr.hasOwnProperty(Y)?B[re]=qr[Y]:(W.push(Y),J.hasOwnProperty(Y)||(J[Y]=[]),J[Y].push(()=>{B[re]=qr[Y],++z===W.length&&P(B)}))}),W.length===0&&P(B)}function Bt(S,T,w={}){if(!("argPackAdvance"in T))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(P,B,W={}){var z=B.name;if(P||me(`type "${z}" must have a positive integer typeid pointer`),qr.hasOwnProperty(P)){if(W.ignoreDuplicateRegistrations)return;me(`Cannot register type '${z}' twice`)}if(qr[P]=B,delete Hi[P],J.hasOwnProperty(P)){var Y=J[P];delete J[P],Y.forEach(re=>re())}}(S,T,w)}function Hn(S){if(!(this instanceof or)||!(S instanceof or))return!1;for(var T=this.$$.ptrType.registeredClass,w=this.$$.ptr,P=S.$$.ptrType.registeredClass,B=S.$$.ptr;T.baseClass;)w=T.upcast(w),T=T.baseClass;for(;P.baseClass;)B=P.upcast(B),P=P.baseClass;return T===P&&w===B}function Do(S){me(S.$$.ptrType.registeredClass.name+" instance already deleted")}var wo=!1;function Ds(S){}function Rr(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 Wn(S,T,w){if(T===w)return S;if(w.baseClass===void 0)return null;var P=Wn(S,T,w.baseClass);return P===null?null:w.downcast(P)}var j={};function Tl(){return Object.keys(mi).length}function Il(){var S=[];for(var T in mi)mi.hasOwnProperty(T)&&S.push(mi[T]);return S}var li=[];function _(){for(;li.length;){var S=li.pop();S.$$.deleteScheduled=!1,S.delete()}}var ji=void 0;function At(S){ji=S,li.length&&ji&&ji(_)}var mi={};function Ac(S,T){return T=function(w,P){for(P===void 0&&me("ptr should not be undefined");w.baseClass;)P=w.upcast(P),w=w.baseClass;return P}(S,T),mi[T]}function Dt(S,T){return T.ptrType&&T.ptr||Zt("makeClassHandle requires ptr and ptrType"),!!T.smartPtrType!=!!T.smartPtr&&Zt("Both smartPtrType and smartPtr must be specified"),T.count={value:1},pr(Object.create(S,{$$:{value:T}}))}function k(S){var T=this.getPointee(S);if(!T)return this.destructor(S),null;var w=Ac(this.registeredClass,T);if(w!==void 0){if(w.$$.count.value===0)return w.$$.ptr=T,w.$$.smartPtr=S,w.clone();var P=w.clone();return this.destructor(S),P}function B(){return this.isSmartPointer?Dt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:T,smartPtrType:this,smartPtr:S}):Dt(this.registeredClass.instancePrototype,{ptrType:this,ptr:S})}var W,z=this.registeredClass.getActualType(T),Y=j[z];if(!Y)return B.call(this);W=this.isConst?Y.constPointerType:Y.pointerType;var re=Wn(T,this.registeredClass,W.registeredClass);return re===null?B.call(this):this.isSmartPointer?Dt(W.registeredClass.instancePrototype,{ptrType:W,ptr:re,smartPtrType:this,smartPtr:S}):Dt(W.registeredClass.instancePrototype,{ptrType:W,ptr:re})}var pr=function(S){return typeof FinalizationRegistry=="undefined"?(pr=T=>T,S):(wo=new FinalizationRegistry(T=>{Rr(T.$$)}),Ds=T=>wo.unregister(T),(pr=T=>{var w=T.$$;if(w.smartPtr){var P={$$:w};wo.register(T,P,T)}return T})(S))};function ws(){if(this.$$.ptr||Do(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var S,T=pr(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 qi(){this.$$.ptr||Do(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&me("Object already scheduled for deletion"),Ds(this),Rr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Ue(){return!this.$$.ptr}function bc(){return this.$$.ptr||Do(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&me("Object already scheduled for deletion"),li.push(this),li.length===1&&ji&&ji(_),this.$$.deleteScheduled=!0,this}function or(){}function zr(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 sr(S,T){return S=zr(S),{[S]:function(){return T.apply(this,arguments)}}[S]}function Rc(S,T,w){if(S[T].overloadTable===void 0){var P=S[T];S[T]=function(){return S[T].overloadTable.hasOwnProperty(arguments.length)||me(`Function '${w}' 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[P.argCount]=P}}function Gn(S,T,w,P,B,W,z,Y){this.name=S,this.constructor=T,this.instancePrototype=w,this.rawDestructor=P,this.baseClass=B,this.getActualType=W,this.upcast=z,this.downcast=Y,this.pureVirtualFunctions=[]}function Mo(S,T,w){for(;T!==w;)T.upcast||me(`Expected null or instance of ${w.name}, got an instance of ${T.name}`),S=T.upcast(S),T=T.baseClass;return S}function vc(S,T){if(T===null)return this.isReference&&me(`null is not a valid ${this.name}`),0;T.$$||me(`Cannot pass "${Lo(T)}" as a ${this.name}`),T.$$.ptr||me(`Cannot pass deleted object as a pointer of type ${this.name}`);var w=T.$$.ptrType.registeredClass;return Mo(T.$$.ptr,w,this.registeredClass)}function Cc(S,T){var w;if(T===null)return this.isReference&&me(`null is not a valid ${this.name}`),this.isSmartPointer?(w=this.rawConstructor(),S!==null&&S.push(this.rawDestructor,w),w):0;T.$$||me(`Cannot pass "${Lo(T)}" as a ${this.name}`),T.$$.ptr||me(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&T.$$.ptrType.isConst&&me(`Cannot convert argument of type ${T.$$.smartPtrType?T.$$.smartPtrType.name:T.$$.ptrType.name} to parameter type ${this.name}`);var P=T.$$.ptrType.registeredClass;if(w=Mo(T.$$.ptr,P,this.registeredClass),this.isSmartPointer)switch(T.$$.smartPtr===void 0&&me("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:T.$$.smartPtrType===this?w=T.$$.smartPtr:me(`Cannot convert argument of type ${T.$$.smartPtrType?T.$$.smartPtrType.name:T.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:w=T.$$.smartPtr;break;case 2:if(T.$$.smartPtrType===this)w=T.$$.smartPtr;else{var B=T.clone();w=this.rawShare(w,Os.toHandle(function(){B.delete()})),S!==null&&S.push(this.rawDestructor,w)}break;default:me("Unsupporting sharing policy")}return w}function Nc(S,T){if(T===null)return this.isReference&&me(`null is not a valid ${this.name}`),0;T.$$||me(`Cannot pass "${Lo(T)}" as a ${this.name}`),T.$$.ptr||me(`Cannot pass deleted object as a pointer of type ${this.name}`),T.$$.ptrType.isConst&&me(`Cannot convert argument of type ${T.$$.ptrType.name} to parameter type ${this.name}`);var w=T.$$.ptrType.registeredClass;return Mo(T.$$.ptr,w,this.registeredClass)}function Oo(S){return this.fromWireType(ue[S>>2])}function Sl(S){return this.rawGetPointee&&(S=this.rawGetPointee(S)),S}function yl(S){this.rawDestructor&&this.rawDestructor(S)}function xo(S){S!==null&&S.delete()}function nr(S,T,w,P,B,W,z,Y,re,G,he){this.name=S,this.registeredClass=T,this.isReference=w,this.isConst=P,this.isSmartPointer=B,this.pointeeType=W,this.sharingPolicy=z,this.rawGetPointee=Y,this.rawConstructor=re,this.rawShare=G,this.rawDestructor=he,B||T.baseClass!==void 0?this.toWireType=Cc:P?(this.toWireType=vc,this.destructorFunction=null):(this.toWireType=Nc,this.destructorFunction=null)}var Jr=[],Dc=S=>{var T=Jr[S];return T||(S>=Jr.length&&(Jr.length=S+1),Jr[S]=T=Pe.get(S)),T},Po=(S,T,w)=>S.includes("j")?((P,B,W)=>{var z=o["dynCall_"+P];return W&&W.length?z.apply(null,[B].concat(W)):z.call(null,B)})(S,T,w):Dc(T).apply(null,w);function zi(S,T){var w,P,B,W=(S=$t(S)).includes("j")?(w=S,P=T,B=[],function(){return B.length=0,Object.assign(B,arguments),Po(w,P,B)}):Dc(T);return typeof W!="function"&&me(`unknown function pointer with signature ${S}: ${T}`),W}var ko=void 0;function wc(S){var T=Ls(S),w=$t(T);return Nr(T),w}function Ji(S,T){var w=[],P={};throw T.forEach(function B(W){P[W]||qr[W]||(Hi[W]?Hi[W].forEach(B):(w.push(W),P[W]=!0))}),new ko(`${S}: `+w.map(wc).join([", "]))}function Mc(S,T){for(var w=[],P=0;P<S;P++)w.push(Se[T+4*P>>2]);return w}function Al(S){for(;S.length;){var T=S.pop();S.pop()(T)}}function Oc(S,T){if(!(S instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof S} which is not a function`);var w=sr(S.name||"unknownFunctionName",function(){});w.prototype=S.prototype;var P=new w,B=S.apply(P,T);return B instanceof Object?B:P}function xc(S,T,w,P,B,W){var z=T.length;z<2&&me("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Y=T[1]!==null&&w!==null,re=!1,G=1;G<T.length;++G)if(T[G]!==null&&T[G].destructorFunction===void 0){re=!0;break}var he=T[0].name!=="void",De="",ve="";for(G=0;G<z-2;++G)De+=(G!==0?", ":"")+"arg"+G,ve+=(G!==0?", ":"")+"arg"+G+"Wired";var fe=`
|
|
73
|
+
return function ${zr(S)}(${De}) {
|
|
74
|
+
if (arguments.length !== ${z-2}) {
|
|
75
|
+
throwBindingError('function ${S} called with ${arguments.length} arguments, expected ${z-2} args!');
|
|
76
|
+
}`;re&&(fe+=`var destructors = [];
|
|
77
|
+
`);var we=re?"destructors":"null",st=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],Je=[me,P,B,Al,T[0],T[1]];for(Y&&(fe+="var thisWired = classParam.toWireType("+we+`, this);
|
|
78
|
+
`),G=0;G<z-2;++G)fe+="var arg"+G+"Wired = argType"+G+".toWireType("+we+", arg"+G+"); // "+T[G+2].name+`
|
|
79
|
+
`,st.push("argType"+G),Je.push(T[G+2]);if(Y&&(ve="thisWired"+(ve.length>0?", ":"")+ve),fe+=(he||W?"var rv = ":"")+"invoker(fn"+(ve.length>0?", ":"")+ve+`);
|
|
80
|
+
`,re)fe+=`runDestructors(destructors);
|
|
81
|
+
`;else for(G=Y?1:2;G<T.length;++G){var gt=G===1?"thisWired":"arg"+(G-2)+"Wired";T[G].destructorFunction!==null&&(fe+=gt+"_dtor("+gt+"); // "+T[G].name+`
|
|
82
|
+
`,st.push(gt+"_dtor"),Je.push(T[G].destructorFunction))}return he&&(fe+=`var ret = retType.fromWireType(rv);
|
|
83
|
+
return ret;
|
|
84
|
+
`),fe+=`}
|
|
85
|
+
`,st.push(fe),Oc(Function,st).apply(null,Je)}function vr(){this.allocated=[void 0],this.freelist=[]}var Ht=new vr;function Ms(S){S>=Ht.reserved&&--Ht.get(S).refcount==0&&Ht.free(S)}function Pc(){for(var S=0,T=Ht.reserved;T<Ht.allocated.length;++T)Ht.allocated[T]!==void 0&&++S;return S}var Os={toValue:S=>(S||me("Cannot use deleted val. handle = "+S),Ht.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 Ht.allocate({refcount:1,value:S})}}};function Lo(S){if(S===null)return"null";var T=typeof S;return T==="object"||T==="array"||T==="function"?S.toString():""+S}function bl(S,T){switch(T){case 2:return function(w){return this.fromWireType(Ye[w>>2])};case 3:return function(w){return this.fromWireType(H[w>>3])};default:throw new TypeError("Unknown float type: "+S)}}function Rl(S,T,w){switch(T){case 0:return w?function(P){return N[P]}:function(P){return D[P]};case 1:return w?function(P){return x[P>>1]}:function(P){return Z[P>>1]};case 2:return w?function(P){return ue[P>>2]}:function(P){return Se[P>>2]};default:throw new TypeError("Unknown integer type: "+S)}}var kc=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Uo=(S,T,w)=>{for(var P=T+w,B=T;S[B]&&!(B>=P);)++B;if(B-T>16&&S.buffer&&kc)return kc.decode(S.subarray(T,B));for(var W="";T<B;){var z=S[T++];if(128&z){var Y=63&S[T++];if((224&z)!=192){var re=63&S[T++];if((z=(240&z)==224?(15&z)<<12|Y<<6|re:(7&z)<<18|Y<<12|re<<6|63&S[T++])<65536)W+=String.fromCharCode(z);else{var G=z-65536;W+=String.fromCharCode(55296|G>>10,56320|1023&G)}}else W+=String.fromCharCode((31&z)<<6|Y)}else W+=String.fromCharCode(z)}return W},vl=(S,T)=>S?Uo(D,S,T):"",Lc=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,Cl=(S,T)=>{for(var w=S,P=w>>1,B=P+T/2;!(P>=B)&&Z[P];)++P;if((w=P<<1)-S>32&&Lc)return Lc.decode(D.subarray(S,w));for(var W="",z=0;!(z>=T/2);++z){var Y=x[S+2*z>>1];if(Y==0)break;W+=String.fromCharCode(Y)}return W},Cr=(S,T,w)=>{if(w===void 0&&(w=2147483647),w<2)return 0;for(var P=T,B=(w-=2)<2*S.length?w/2:S.length,W=0;W<B;++W){var z=S.charCodeAt(W);x[T>>1]=z,T+=2}return x[T>>1]=0,T-P},xs=S=>2*S.length,Uc=(S,T)=>{for(var w=0,P="";!(w>=T/4);){var B=ue[S+4*w>>2];if(B==0)break;if(++w,B>=65536){var W=B-65536;P+=String.fromCharCode(55296|W>>10,56320|1023&W)}else P+=String.fromCharCode(B)}return P},Nl=(S,T,w)=>{if(w===void 0&&(w=2147483647),w<4)return 0;for(var P=T,B=P+w-4,W=0;W<S.length;++W){var z=S.charCodeAt(W);if(z>=55296&&z<=57343&&(z=65536+((1023&z)<<10)|1023&S.charCodeAt(++W)),ue[T>>2]=z,(T+=4)+4>B)break}return ue[T>>2]=0,T-P},Xi=S=>{for(var T=0,w=0;w<S.length;++w){var P=S.charCodeAt(w);P>=55296&&P<=57343&&++w,T+=4}return T},Vc={},Ps=[],ks=[],jn;jn=()=>performance.now();var Fc,qn,Qi,$c=[null,[],[]];(function(){for(var S=new Array(256),T=0;T<256;++T)S[T]=String.fromCharCode(T);Ke=S})(),Wi=o.BindingError=class extends Error{constructor(S){super(S),this.name="BindingError"}},Bn=o.InternalError=class extends Error{constructor(S){super(S),this.name="InternalError"}},or.prototype.isAliasOf=Hn,or.prototype.clone=ws,or.prototype.delete=qi,or.prototype.isDeleted=Ue,or.prototype.deleteLater=bc,o.getInheritedInstanceCount=Tl,o.getLiveInheritedInstances=Il,o.flushPendingDeletes=_,o.setDelayFunction=At,nr.prototype.getPointee=Sl,nr.prototype.destructor=yl,nr.prototype.argPackAdvance=8,nr.prototype.readValueFromPointer=Oo,nr.prototype.deleteObject=xo,nr.prototype.fromWireType=k,ko=o.UnboundTypeError=(Fc=Error,(Qi=sr(qn="UnboundTypeError",function(S){this.name=qn,this.message=S;var T=new Error(S).stack;T!==void 0&&(this.stack=this.toString()+`
|
|
86
|
+
`+T.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Fc.prototype),Qi.prototype.constructor=Qi,Qi.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},Qi),Object.assign(vr.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)}}),Ht.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Ht.reserved=Ht.allocated.length,o.count_emval_handles=Pc;var Wt,Bc={o:function(S,T,w){throw new $n(S).init(T,w),S},r:function(S,T,w,P,B){},m:function(S,T,w,P,B){var W=Te(w);Bt(S,{name:T=$t(T),fromWireType:function(z){return!!z},toWireType:function(z,Y){return Y?P:B},argPackAdvance:8,readValueFromPointer:function(z){var Y;if(w===1)Y=N;else if(w===2)Y=x;else{if(w!==4)throw new TypeError("Unknown boolean type size: "+T);Y=ue}return this.fromWireType(Y[z>>W])},destructorFunction:null})},q:function(S,T,w,P,B,W,z,Y,re,G,he,De,ve){he=$t(he),W=zi(B,W),Y&&(Y=zi(z,Y)),G&&(G=zi(re,G)),ve=zi(De,ve);var fe=zr(he);(function(we,st,Je){o.hasOwnProperty(we)?((Je===void 0||o[we].overloadTable!==void 0&&o[we].overloadTable[Je]!==void 0)&&me(`Cannot register public name '${we}' twice`),Rc(o,we,we),o.hasOwnProperty(Je)&&me(`Cannot register multiple overloads of a function with the same number of arguments (${Je})!`),o[we].overloadTable[Je]=st):(o[we]=st,Je!==void 0&&(o[we].numArguments=Je))})(fe,function(){Ji(`Cannot construct ${he} due to unbound types`,[P])}),Gi([S,T,w],P?[P]:[],function(we){var st,Je;we=we[0],Je=P?(st=we.registeredClass).instancePrototype:or.prototype;var gt=sr(fe,function(){if(Object.getPrototypeOf(this)!==Xe)throw new Wi("Use 'new' to construct "+he);if(xt.constructor_body===void 0)throw new Wi(he+" has no accessible constructor");var Dr=xt.constructor_body[arguments.length];if(Dr===void 0)throw new Wi(`Tried to invoke ctor of ${he} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(xt.constructor_body).toString()}) parameters instead!`);return Dr.apply(this,arguments)}),Xe=Object.create(Je,{constructor:{value:gt}});gt.prototype=Xe;var xt=new Gn(he,gt,Xe,ve,st,W,Y,G);xt.baseClass&&(xt.baseClass.__derivedClasses===void 0&&(xt.baseClass.__derivedClasses=[]),xt.baseClass.__derivedClasses.push(xt));var Zi=new nr(he,xt,!0,!1,!1),wt=new nr(he+"*",xt,!1,!1,!1),zn=new nr(he+" const*",xt,!1,!0,!1);return j[S]={pointerType:wt,constPointerType:zn},function(Dr,Jn,Us){o.hasOwnProperty(Dr)||Zt("Replacing nonexistant public symbol"),o[Dr].overloadTable!==void 0&&Us!==void 0?o[Dr].overloadTable[Us]=Jn:(o[Dr]=Jn,o[Dr].argCount=Us)}(fe,gt),[Zi,wt,zn]})},p:function(S,T,w,P,B,W){var z=Mc(T,w);B=zi(P,B),Gi([],[S],function(Y){var re=`constructor ${(Y=Y[0]).name}`;if(Y.registeredClass.constructor_body===void 0&&(Y.registeredClass.constructor_body=[]),Y.registeredClass.constructor_body[T-1]!==void 0)throw new Wi(`Cannot register multiple constructors with identical number of parameters (${T-1}) for class '${Y.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Y.registeredClass.constructor_body[T-1]=()=>{Ji(`Cannot construct ${Y.name} due to unbound types`,z)},Gi([],z,function(G){return G.splice(1,0,null),Y.registeredClass.constructor_body[T-1]=xc(re,G,null,B,W),[]}),[]})},d:function(S,T,w,P,B,W,z,Y,re){var G=Mc(w,P);T=$t(T),W=zi(B,W),Gi([],[S],function(he){var De=`${(he=he[0]).name}.${T}`;function ve(){Ji(`Cannot call ${De} due to unbound types`,G)}T.startsWith("@@")&&(T=Symbol[T.substring(2)]),Y&&he.registeredClass.pureVirtualFunctions.push(T);var fe=he.registeredClass.instancePrototype,we=fe[T];return we===void 0||we.overloadTable===void 0&&we.className!==he.name&&we.argCount===w-2?(ve.argCount=w-2,ve.className=he.name,fe[T]=ve):(Rc(fe,T,De),fe[T].overloadTable[w-2]=ve),Gi([],G,function(st){var Je=xc(De,st,he,W,z,re);return fe[T].overloadTable===void 0?(Je.argCount=w-2,fe[T]=Je):fe[T].overloadTable[w-2]=Je,[]}),[]})},u:function(S,T){Bt(S,{name:T=$t(T),fromWireType:function(w){var P=Os.toValue(w);return Ms(w),P},toWireType:function(w,P){return Os.toHandle(P)},argPackAdvance:8,readValueFromPointer:Oo,destructorFunction:null})},k:function(S,T,w){var P=Te(w);Bt(S,{name:T=$t(T),fromWireType:function(B){return B},toWireType:function(B,W){return W},argPackAdvance:8,readValueFromPointer:bl(T,P),destructorFunction:null})},b:function(S,T,w,P,B){T=$t(T),B===-1&&(B=4294967295);var W=Te(w),z=G=>G;if(P===0){var Y=32-8*w;z=G=>G<<Y>>>Y}var re=T.includes("unsigned");Bt(S,{name:T,fromWireType:z,toWireType:re?function(G,he){return this.name,he>>>0}:function(G,he){return this.name,he},argPackAdvance:8,readValueFromPointer:Rl(T,W,P!==0),destructorFunction:null})},a:function(S,T,w){var P=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][T];function B(W){var z=Se,Y=z[W>>=2],re=z[W+1];return new P(z.buffer,re,Y)}Bt(S,{name:w=$t(w),fromWireType:B,argPackAdvance:8,readValueFromPointer:B},{ignoreDuplicateRegistrations:!0})},j:function(S,T){var w=(T=$t(T))==="std::string";Bt(S,{name:T,fromWireType:function(P){var B,W=Se[P>>2],z=P+4;if(w)for(var Y=z,re=0;re<=W;++re){var G=z+re;if(re==W||D[G]==0){var he=vl(Y,G-Y);B===void 0?B=he:(B+="\0",B+=he),Y=G+1}}else{var De=new Array(W);for(re=0;re<W;++re)De[re]=String.fromCharCode(D[z+re]);B=De.join("")}return Nr(P),B},toWireType:function(P,B){var W;B instanceof ArrayBuffer&&(B=new Uint8Array(B));var z=typeof B=="string";z||B instanceof Uint8Array||B instanceof Uint8ClampedArray||B instanceof Int8Array||me("Cannot pass non-string to std::string"),W=w&&z?(De=>{for(var ve=0,fe=0;fe<De.length;++fe){var we=De.charCodeAt(fe);we<=127?ve++:we<=2047?ve+=2:we>=55296&&we<=57343?(ve+=4,++fe):ve+=3}return ve})(B):B.length;var Y=Yi(4+W+1),re=Y+4;if(Se[Y>>2]=W,w&&z)((De,ve,fe,we)=>{if(!(we>0))return 0;for(var st=fe,Je=fe+we-1,gt=0;gt<De.length;++gt){var Xe=De.charCodeAt(gt);if(Xe>=55296&&Xe<=57343&&(Xe=65536+((1023&Xe)<<10)|1023&De.charCodeAt(++gt)),Xe<=127){if(fe>=Je)break;ve[fe++]=Xe}else if(Xe<=2047){if(fe+1>=Je)break;ve[fe++]=192|Xe>>6,ve[fe++]=128|63&Xe}else if(Xe<=65535){if(fe+2>=Je)break;ve[fe++]=224|Xe>>12,ve[fe++]=128|Xe>>6&63,ve[fe++]=128|63&Xe}else{if(fe+3>=Je)break;ve[fe++]=240|Xe>>18,ve[fe++]=128|Xe>>12&63,ve[fe++]=128|Xe>>6&63,ve[fe++]=128|63&Xe}}ve[fe]=0})(B,D,re,W+1);else if(z)for(var G=0;G<W;++G){var he=B.charCodeAt(G);he>255&&(Nr(re),me("String has UTF-16 code units that do not fit in 8 bits")),D[re+G]=he}else for(G=0;G<W;++G)D[re+G]=B[G];return P!==null&&P.push(Nr,Y),Y},argPackAdvance:8,readValueFromPointer:Oo,destructorFunction:function(P){Nr(P)}})},g:function(S,T,w){var P,B,W,z,Y;w=$t(w),T===2?(P=Cl,B=Cr,z=xs,W=()=>Z,Y=1):T===4&&(P=Uc,B=Nl,z=Xi,W=()=>Se,Y=2),Bt(S,{name:w,fromWireType:function(re){for(var G,he=Se[re>>2],De=W(),ve=re+4,fe=0;fe<=he;++fe){var we=re+4+fe*T;if(fe==he||De[we>>Y]==0){var st=P(ve,we-ve);G===void 0?G=st:(G+="\0",G+=st),ve=we+T}}return Nr(re),G},toWireType:function(re,G){typeof G!="string"&&me(`Cannot pass non-string to C++ string type ${w}`);var he=z(G),De=Yi(4+he+T);return Se[De>>2]=he>>Y,B(G,De+4,he+T),re!==null&&re.push(Nr,De),De},argPackAdvance:8,readValueFromPointer:Oo,destructorFunction:function(re){Nr(re)}})},n:function(S,T){Bt(S,{isVoid:!0,name:T=$t(T),argPackAdvance:0,fromWireType:function(){},toWireType:function(w,P){}})},e:function(S,T,w,P){var B,W;(S=Ps[S])(T=Os.toValue(T),w=(W=Vc[B=w])===void 0?$t(B):W,null,P)},l:Ms,h:function(S,T){var w=function(st,Je){for(var gt,Xe,xt,Zi=new Array(st),wt=0;wt<st;++wt)Zi[wt]=(gt=Se[Je+4*wt>>2],Xe="parameter "+wt,xt=void 0,(xt=qr[gt])===void 0&&me(Xe+" has unknown type "+wc(gt)),xt);return Zi}(S,T),P=w[0],B=P.name+"_$"+w.slice(1).map(function(st){return st.name}).join("_")+"$",W=ks[B];if(W!==void 0)return W;for(var z=["retType"],Y=[P],re="",G=0;G<S-1;++G)re+=(G!==0?", ":"")+"arg"+G,z.push("argType"+G),Y.push(w[1+G]);var he="return function "+zr("methodCaller_"+B)+`(handle, name, destructors, args) {
|
|
87
|
+
`,De=0;for(G=0;G<S-1;++G)he+=" var arg"+G+" = argType"+G+".readValueFromPointer(args"+(De?"+"+De:"")+`);
|
|
88
|
+
`,De+=w[G+1].argPackAdvance;for(he+=" var rv = handle[name]("+re+`);
|
|
89
|
+
`,G=0;G<S-1;++G)w[G+1].deleteObject&&(he+=" argType"+G+".deleteObject(arg"+G+`);
|
|
90
|
+
`);P.isVoid||(he+=` return retType.toWireType(destructors, rv);
|
|
91
|
+
`),he+=`};
|
|
92
|
+
`,z.push(he);var ve,fe,we=Oc(Function,z).apply(null,Y);return ve=we,fe=Ps.length,Ps.push(ve),W=fe,ks[B]=W,W},f:()=>{hr("")},c:jn,t:(S,T,w)=>D.copyWithin(S,T,T+w),s:S=>{D.length,hr("OOM")},i:(S,T,w,P)=>{for(var B,W,z,Y=0,re=0;re<w;re++){var G=Se[T>>2],he=Se[T+4>>2];T+=8;for(var De=0;De<he;De++)B=S,W=D[G+De],z=void 0,z=$c[B],W===0||W===10?((B===1?g:E)(Uo(z,0)),z.length=0):z.push(W);Y+=he}return Se[P>>2]=Y,0}},Nr=(function(){var S,T,w,P,B={a:Bc};function W(z,Y){var re,G,he=z.exports;return A=(C=he).v,re=A.buffer,o.HEAP8=N=new Int8Array(re),o.HEAP16=x=new Int16Array(re),o.HEAP32=ue=new Int32Array(re),o.HEAPU8=D=new Uint8Array(re),o.HEAPU16=Z=new Uint16Array(re),o.HEAPU32=Se=new Uint32Array(re),o.HEAPF32=Ye=new Float32Array(re),o.HEAPF64=H=new Float64Array(re),Pe=C.z,G=C.w,Vn.unshift(G),function(){if(Gr--,o.monitorRunDependencies&&o.monitorRunDependencies(Gr),Gr==0&&(Ns!==null&&(clearInterval(Ns),Ns=null),Bi)){var De=Bi;Bi=null,De()}}(),he}if(Gr++,o.monitorRunDependencies&&o.monitorRunDependencies(Gr),o.instantiateWasm)try{return o.instantiateWasm(B,W)}catch(z){E("Module.instantiateWasm callback failed with error: "+z),r(z)}(S=p,T=ci,w=B,P=function(z){W(z.instance)},S||typeof WebAssembly.instantiateStreaming!="function"||ie(T)||typeof fetch!="function"?jr(T,w,P):fetch(T,{credentials:"same-origin"}).then(z=>WebAssembly.instantiateStreaming(z,w).then(P,function(Y){return E("wasm streaming compile failed: "+Y),E("falling back to ArrayBuffer instantiation"),jr(T,w,P)}))).catch(r)}(),S=>(Nr=C.x)(S)),Yi=S=>(Yi=C.y)(S),Ls=S=>(Ls=C.A)(S),Hc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=C.B)(),S=>(Hc=C.C)(S));o.dynCall_jiji=(S,T,w,P,B)=>(o.dynCall_jiji=C.D)(S,T,w,P,B);function Wc(){function S(){Wt||(Wt=!0,o.calledRun=!0,Ln||(ui(Vn),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(),Fn.unshift(T);var T;ui(Fn)}()))}Gr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)T=o.preRun.shift(),Un.unshift(T);var T;ui(Un)}(),Gr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),S()},1)):S()))}if(Bi=function S(){Wt||Wc(),Wt||(Bi=S)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return Wc(),t.ready}})();var By="web.sdk.qcloud.com",Hy=`https://${By}/trtc/webrtc/v5/doc`,IP=`${Hy}/zh-cn/`,bE=(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))(bE||{});var RE={"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}},SP=RE["480p_2"],yP=RE["120p_2"],Lu={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",RESIZE:"resize",TIME_UPDATE:"timeupdate"},AP=Lu.MAIN,bP=Lu.AUXILIARY,RP=Lu.BIG,vP=Lu.SMALL;var CP=Object.keys(bE);var Wy=function(i,t,e,r){return new(e||(e=Promise))(function(o,s){function n(m){try{u(r.next(m))}catch(p){s(p)}}function a(m){try{u(r.throw(m))}catch(p){s(p)}}function u(m){var p;m.done?o(m.value):(p=m.value,p instanceof e?p:new e(function(g){g(p)})).then(n,a)}u((r=r.apply(i,t||[])).next())})},lp=Symbol(32),mp=Symbol(16),hp=Symbol(8),dp=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,t){return t&&this.consume(),this.need=i,this.flush()}read(i){return Wy(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,e)=>{var r;this.reject=e,this.resolve=o=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(o)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(lp)}readU16(){return this.read(mp)}readU8(){return this.read(hp)}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,t=this.buffer.subarray(this.consumed),e=0,r=o=>t.length<(e=o);if(typeof this.need=="number"){if(r(this.need))return;i=t.subarray(0,e)}else if(this.need===lp){if(r(4))return;i=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===mp){if(r(2))return;i=t[0]<<8|t[1]}else if(this.need===hp){if(r(1))return;i=t[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(t.subarray(0,e)),i=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,e)),i=this.need}return this.consumed+=e,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)return new Promise(t=>this.pull=t);this.flush()}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,255&i]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,255&i]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let t=this.buffer.length,e=t+i;if(e<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,e);else{let r=new Uint8Array(e);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(t,e)}return this.buffer=new Uint8Array(i),this.buffer}};dp.U32=lp,dp.U16=mp,dp.U8=hp;var Gy=127,NP=~Gy,DP=Math.pow(2,31),wP=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},MP=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function IE(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:OP}=Object.prototype,vE=class CE{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 CE.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){var r;switch(t){case"wasm":let s=((r=this.core.assetsPath)==null?void 0:r.replace(/\/+$/,""))||".";return new $y(xu(Ou({},e),{wasmPath:`${s}/videodec.wasm`}));case"webCodecs":return new Dn;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 a=this.core.room.videoManager.createDecodeContext(xu(Ou({},t),{createDecoder:this.createDecoder}));return e(a.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,a),a.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=IE()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t),n=`report health data: ${t.track.userId} ${t.track.streamType} ${t.type}+${t.renderer} goodType\uFF1A${t.goodType} ${t.failedReason?`failedReason: ${t.failedReason}`:""}`;r&&(this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1,max:100}),n+=` RENDER_FREEZE_RATE: ${Math.floor(o/r*100)}%`),r&&(this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1,max:100}),n+=` DATA_FREEZE_RATE: ${Math.floor(s/r*100)}%`),t.inputFrameCount&&(this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1,max:100}),n+=` VIDEO_CONSUME_RENDER_RATE: ${Math.floor(t.decodedFrameCount/t.inputFrameCount*100)}%`),this.core.log.info(n)}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(xu(Ou({},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:a,endTime:u})=>{a>e.startPerformanceTime&&(s+=u===0?IE()-a:u-a)});let n=0;return o&&o.durationItemList.forEach(a=>{a.startTime>e.startPerformanceTime&&(n+=a.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};Wr(vE,"Name","TRTCVideoDecoder");var pp=vE;var r_=pi(bi());function fp({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return U.on($.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>=i||a.totalSizeInSecond>t))throw new de({code:q.INVALID_OPERATION,message:$e({key:Fe.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=i,isSize:a.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});a.callCountInSecond++,r.call(this,...n)}})}var jy="2025-10-14 19:41:38",NE=!0,DE=function(){var i;if(NE){NE=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Xr}/en/index.html`),console.info(`* Changelog: ${Xr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",dt),Ur||F.debug("Build Time:",jy);let t=`UA: ${navigator.userAgent}
|
|
93
|
+
CPU core: ${navigator.hardwareConcurrency}, GPU: ${fm()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),F.info(t),F.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Yo().then(r=>{r&&F.info(Pr)})}};var ys={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 se={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},mr=(k=>(k[k.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",k[k.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",k[k.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",k[k.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",k[k.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",k[k.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",k[k.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",k[k.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",k[k.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",k[k.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",k[k.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",k[k.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",k[k.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",k[k.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",k[k.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",k[k.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",k[k.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",k[k.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",k[k.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",k[k.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",k[k.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",k[k.INVALID_OPERATION=5100]="INVALID_OPERATION",k[k.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",k[k.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",k[k.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",k[k.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",k[k.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",k[k.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",k[k.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",k[k.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",k[k.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",k[k.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",k[k.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",k[k.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",k[k.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",k[k.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",k[k.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",k[k.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",k[k.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",k[k.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",k[k.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",k[k.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",k[k.DEVICE_ERROR=5300]="DEVICE_ERROR",k[k.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",k[k.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",k[k.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",k[k.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",k[k.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",k[k.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",k[k.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",k[k.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",k[k.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",k[k.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",k[k.SERVER_ERROR=5400]="SERVER_ERROR",k[k.NEED_TO_BUY=5401]="NEED_TO_BUY",k[k.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",k[k.OPERATION_FAILED=5500]="OPERATION_FAILED",k[k.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",k[k.REJOIN_FAILED=5502]="REJOIN_FAILED",k[k.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",k[k.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",k[k.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",k[k.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",k[k.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",k[k.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",k[k.OPERATION_ABORT=5998]="OPERATION_ABORT",k[k.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",k))(mr||{});function ME({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=mr[i];try{o=wE[s]}catch(n){o=wE.UNKNOWN_ERROR}return je(o)?r=o(t):Ne(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var wE=ge(X({},tr),{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: ${ut(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: ${ut(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=As(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=As(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=As(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=As(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=As(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=As(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=As(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 As(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var gp=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:a,data:u}){var p;let m;o?m=o:m=ME({code:e===se.SERVER_ERROR?e:r||e,params:X({fnName:n,error:a},s)});super(m);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"data");l(this,"handler");l(this,"originError");this.name=mr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=a,this.message=m,this.data=u,this.extraCode===5302&&((p=this.originError)!=null&&p.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},E={startLocalVideo:"webcam",startLocalAudio:"microphone"},A=document.createElement("a");Qo?A.href=`ms-settings:privacy-${E[this.functionName]}`:Lr&&(A.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),A.href.length>0&&A.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof de){let{stack:n}=e,a={code:se.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:a.code=se.INVALID_PARAMETER,a.message=e.message;break;case q.INVALID_OPERATION:a.code=se.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:a.code=se.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(tr.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:a.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:case q.SWITCH_ROOM_FAILED:a.code=se.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:a.code=se.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=qy(e.name));break;case q.VIDEO_ENCODE_FAILED:a.extraCode=5505;case q.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=se.OPERATION_FAILED;break;case q.UNKNOWN:break;default:a.code=se.OPERATION_FAILED}s=new i(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
94
|
+
`)))}else{if(e instanceof i)return e;s=new i({code:se.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function qy(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 oe=gp;function si(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function uc(i){return i===ys.QOS_PREFERENCE_CLEAR?"detail":i===ys.QOS_PREFERENCE_SMOOTH?"motion":""}function wn(i,t){let e=t?Ll:ea;return rm(i)?X(X({},e),i):Mr[i]?Mr[i]:e}var OE={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}}},xE={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}}},Mn={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(Ne(i)&&!document.getElementById(i))throw new oe({code:se.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},PE={name:"userId",required:!0,type:"string"},kE={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function On(i,t){if(!i)throw new oe({code:se.INVALID_OPERATION,extraCode:5101,fnName:t})}function LE(i,t,e){if(!i)throw new oe({code:se.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}function UE(i,t,e){if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new oe({code:se.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:e}})}function VE(i,t,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new oe({code:se.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:e}})}var rL={type:"number",notLessThanZero:!0},zy=(i,t)=>i.width*i.height>=t.width*t.height&&i.frameRate>=t.frameRate&&i.bitrate>=t.bitrate;function FE(i){var r;if(!((r=i==null?void 0:i.option)!=null&&r.small))return;if(!zd()){F.warn("small stream is not supported"),delete i.option.small;return}let t=wn(i.option.profile),e=wn(i.option.small,!0);if(!zy(t,e)){F.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 Jy={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 oe({code:se.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(Ne(i.roomId))throw new oe({code:se.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});UE(i.roomId,e,t)}else if(i.strRoomId)VE(i.strRoomId,e,t);else throw new oe({code:se.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:Mn,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:OE},validate(i){var t,e;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201});(e=i==null?void 0:i.option)!=null&&e.small&&FE(i)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:ge(X({},Mn),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:OE},validate(i){var t;(t=i==null?void 0:i.option)!=null&&t.small&&FE(i)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:kE},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:kE}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Mn,publish:{type:"boolean"},option:xE},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(wi())throw new oe({code:se.ENV_NOT_SUPPORTED,extraCode:5201});if(!Pa())throw new oe({code:se.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Mn,publish:{type:"boolean"},option:xE}},muteRemoteAudio:[PE,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[PE,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Mn,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){On(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(LE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:se.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:ge(X({},Mn),{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){On(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(LE(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new oe({code:se.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!=="*"&&M(i.streamType))throw new oe({code:se.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){On(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(!La)throw new oe({code:se.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new oe({code:se.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new oe({code:se.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:se.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});On(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 oe({code:se.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 oe({code:se.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new oe({code:se.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(On(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new oe({code:se.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(i,t,e){if(On(this._room.isJoined,e),this._room.useStringRoomId&&i.strRoomId===this._room.roomId||!this._room.useStringRoomId&&i.roomId===Number(this._room.roomId))throw new oe({code:se.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 oe({code:se.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(i.roomId)UE(i.roomId,e,t);else if(i.strRoomId)VE(i.strRoomId,e,t);else throw new oe({code:se.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}}}},Nt={TRTC:Jy};var zt=class extends Error{};function Xy(i,t){let e=Wo(i);for(let r=0;r<t.length;r++)xr(e[r],t[r]);return e}function Qy(i){this._resolve=Promise.resolve(i)}function Yy(i){this._reject=Promise.reject(i)}var So=class So{constructor(t,e){this.instance=t;this.group=e;l(this,"started",!1);l(this,"ops",[]);l(this,"startSame",()=>!0);l(this,"mergeUpdate",Xy);let r=So.instances.get(t);r?r.set(e,this):So.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=So.instances.get(t);return r&&r.get(e)||new So(t,e)}static gets(t,e){let r=So.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=a=>{var u;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(u=this.currentOp)==null||u.action(),a},s=a=>{var u,m;throw this.ops.shift(),t===0&&((u=this.currentOp)==null?void 0:u.type)===2&&this.ops.shift().reject(new zt("start failed")),(m=this.currentOp)==null||m.action(),a},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:Qy,reject:Yy};try{switch(this.state){case 1:if(t===0)throw new zt("already started");break;case 4:if(t===2)throw new zt("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(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new zt("already start");break;case 3:switch(t.type){case 2:throw new zt("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new zt("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new zt("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 zt("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new zt("start not allowed after update");case 0:throw new zt("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new zt("keep start")),new zt("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}};l(So,"instances",new WeakMap);var Vi=So;var Vu=new WeakMap,Fu=(i,t)=>{if(t instanceof zt){let{stack:e}=t;t=new oe({code:se.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
95
|
+
`)))}throw t};function yo(i,t){return Me((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(Fu.bind(null,r))):e.apply(this,o)})}function bs(i,t){let{merge:e,debounce:r}=t||{};return Me((o,s)=>function(...n){let a=Vi.get(this,typeof i=="string"?i:i.call(this,...n));if(!a)return o.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:u,getKey:m}=r;return new Promise((p,g)=>{var C,N;let E=(C=Vu.get(this))==null?void 0:C.get(m(...n));if(E){let{timeoutId:D,resolve:x}=E;clearTimeout(D),x()}let A=setTimeout(()=>{if(a.state===3||a.state===4)return p();a.action(2,o.bind(this),n).catch(Fu.bind(null,s)).then(p,g)},u);Vu.has(this)?(N=Vu.get(this))==null||N.set(m(...n),{timeoutId:A,resolve:p}):Vu.set(this,new Map([[m(...n),{timeoutId:A,resolve:p}]]))})}return a.action(2,o.bind(this),n).catch(Fu.bind(null,s))})}function Ao(i){return Me((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(Fu.bind(null,e)):t.apply(this,r)})}var K={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},$E=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,K.PERMISSION_STATE_CHANGE,K.VIDEO_SIZE_CHANGED]);var Tp={};hi(Tp,{ScheduleRequestType:()=>HE,getAbilityConfig:()=>Ky,getScheduleDomain:()=>Hu,isNeedToSchedule:()=>$u,scheduleProxy:()=>ni,sendScheduleRequest:()=>_p,setIsNeedToSchedule:()=>Rs,setScheduleProxy:()=>Bu});var Ep=null,$u=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(Ei).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
96
|
+
`));function Rs(i){Qe(i)&&i!==$u&&($u=i,F.info(`setIsNeedToSchedule ${i}`))}U.on("28",()=>Rs(!0));U.on("63",()=>Rs(!0));U.on("84",()=>Rs(!0));U.on("201",i=>{i.state==="RECONNECTING"&&Rs(!0)});U.on("202",i=>{i.state==="RECONNECTING"&&Rs(!0)});function Zy(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=bo(i,"config",O.MAIN),n=bo(i,"config",O.BACKUP);for(let a of o)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let u=a.name===s?O.MAIN:O.BACKUP,m=Math.round(a.duration),p=Math.round(a.domainLookupStart-a.startTime),g=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,E=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,A=Math.round(a.domainLookupEnd-a.domainLookupStart),C=Math.round(a.requestStart-a.secureConnectionStart),N=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),x=Math.round(a.responseEnd-a.responseStart),Z=[A,C,N,D,x];We.uploadEvent({log:`stat-schedule-net:${m}(${p}(${g}->${E})->${Z.join("->")}) ${u}`,userId:t}),r=ge(X({},r),{totalCost:m,local:p,dns:A,tcp:N,tls:C,request:D,response:x});break}}catch(o){F.error("getScheduleDetailCost error",o)}return r}function _p(m){return y(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:a,latencyLevel:u}){var g;if(!$u&&Ep)return{isCached:!0,result:Ep};let p={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 A=((g=yield Yo())==null?void 0:g.model)||wd();A&&E.append("model",A),a&&E.append("role",String(a)),u&&E.append("latencyLevel",String(u)),n&&E.append("frameWorkType",String(n));let C=Ee(),N=yield tA(E,p,t);N.config&&(N.config.loggerDomain&&Fo(N.config.loggerDomain),Qe(N.config.scheduleCache)&&Rs(!N.config.scheduleCache)),p.delta=Ee()-C;let D=Zy(Number(t),i,C);return Ep=N,{isCached:!1,result:N,detailCost:D}}catch(E){let A=at(E)?E[0]:E,C=ke(A.code)?A.code:0,N=`schedule failed${A.message?`: ${A.message}`:""}`,D=new de({code:q.SCHEDULE_FAILED,extraCode:C,message:$e({key:Fe.JOIN_ROOM_FAILED,data:{error:N,code:C}})});throw F.error(N,C),D}})}var ni={main:"",backup:""};function Bu(i){at(i)?(ni.main=i[0],ni.backup=i[1]):ni.main=i}var HE=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(HE||{});function bo(i,t,e=O.MAIN,r=!1){return`https://${ni[e]||Hu(i,e,r)}/api/v1/${t}`}function Ky(i,t,e){let r=bo(i,t),o=bo(i,t,O.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(u=>u.json()),a=fetch(`${o}?${s}`).then(u=>u.json());return ca([n,a])}function Hu(i,t=O.MAIN,e=!1){let r;return _i(i)?e?r=t===O.MAIN?Ei.MAIN_OVERSEA_BACKUP:Ei.BACKUP_OVERSEA:r=t===O.MAIN?Ei.MAIN_OVERSEA:Ei.BACKUP_OVERSEA:r=t===O.MAIN?Ei.MAIN:Ei.BACKUP,r}function eA(i,t,e){return new Promise((r,o)=>{Si({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 BE=(i,t)=>oo({retryFunction:eA,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function tA(i,t,e){return new Promise((r,o)=>{let s=null;ca([BE(n=>t.count[0]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[0]=n.message,s||(u>=1&&(m[0]=bo(e,"config",O.MAIN,!0)),a())})(bo(e,"config",O.MAIN),i,{get timeout(){return Go(2+t.count[0])*1e3}}),BE(n=>t.count[1]=n+1,({error:n,retry:a,retriedCount:u,retryFuncArgs:m})=>{t.msg[1]=n.message,s||(u>=2&&(m[0]=bo(e,"config",O.BACKUP,!0)),a())})(bo(e,"config",O.BACKUP),i,{get timeout(){return Go(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var rA=i=>i.startsWith("data:application/octet-stream;base64,"),iA=i=>i.startsWith("file://"),lc=class{constructor(){l(this,"_log");this._log=F.createLogger({id:"fd"})}download(t,e){return y(this,null,function*(){let{type:r="blob"}=e||{};t=Jo(t);try{let o=Ee(),s;if(je(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Ee()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),Q.addSuccessEvent({key:522700,cost:Ee()-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=Ee(),o=null,s=null;if(je(WebAssembly.instantiateStreaming)&&!rA(t)&&!iA(t)&&je(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=Ee()-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=Ee();return new Promise((r,o)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${t}, cost: ${Ee()-e}ms`),Q.addSuccessEvent({key:522702,cost:Ee()-e,split:1e3}),r(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${t}, error: ${(n==null?void 0:n.message)||JSON.stringify(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)})}};te([cs({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}`)}})],lc.prototype,"download",1),te([cs({settings:{timeout:3e3,retries:3},onRetrying(t){this._log.warn(`loadScript retrying: ${t}`)}})],lc.prototype,"loadScript",1);var mc=new lc;function WE({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,LocalMixVideoTrack:Is,LocalVideoTrack:lr,LocalScreenTrack:ii,room:t,assetsPath:r,fileDownloader:mc,innerEmitter:U,INNER_EVENT:$,constants:$l,environment:ln,utils:op,eventLogger:We,log:this.room.getLogger(),loggerManager:F,errorModule:e,kvStatManager:Q,rtcDectection:uo,trtc:this,rx:tp,enums:km,schedule:Tp,getDevices:Tn,initVisionTaskRegistry:(o,s="/mediapipe/vision.js")=>y(this,null,function*(){window.VisionTaskRegistry||(yield mc.loadScript(`${o}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(o)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Ge(),deviceDetector:ot,AudioPlayer:Sn,AutoPlayDialog:gn,Timer:lt,clearStarted:(o,s)=>{let n=o.getAlias(),a=Vi.instances.get(this);if(a)if(s){let u=a.get(n+s);if(!u)return;u.started=!1}else a.forEach((u,m)=>{m.startsWith(n)&&(u.started=!1)})},startGetPCM:nc,createAudioNode:za,getNetworkTimeOffset:tf,validateSourceNode:()=>{var o;if(ft&&!((o=this.room.audioManager._localAudioPipline)!=null&&o.source.node))throw new oe({code:se.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})}}}var GE=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=$e({key:Fe.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return F.warn(`${s}
|
|
57
97
|
|
|
58
|
-
${r.stack}`),!1}},o};var fs=new WeakMap;function If(o){let i=fs.get(o);i&&(i.forEach(e=>clearTimeout(e)),fs.delete(o))}function Af(o,i){return Q((e,t)=>function(...r){let s=fs.get(this);s||(s=new Map,fs.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=fs.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=fs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var Rf="trtc-sdk-v5",ph="5.13.2-beta.1";function Ke(...o){return Q((i,e)=>function(...t){try{Zc.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function fh(...o){return Q((i,e)=>function(...t){try{Zc.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Zc(o,i,e,t){if(Ce(o))for(let r=0;r<o.length;r++)Yc.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else Yc.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function Yc({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 L(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),ee(o.type[l])&&ve(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new L({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>Lr(l)?Ro(l):ee(l)?l:ve(l))},value:i}})}else if(!E(o.type)&&ve(i)!==o.type)throw new L(s(5002));if(o.allowEmpty===!1){let c=X(i)&&(i===0||Number.isNaN(i)),l=ee(i)&&i.trim()==="";if(c||l)throw new L(s(5003))}if(o.notLessThanZero&&X(i)&&i<0)throw new L(s(5006));if(!E(o.min)&&X(i)&&i<o.min)throw new L(s(5007));if(!E(o.max)&&X(i)&&i>o.max)throw new L(s(5008));if(ee(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new L(s(5004))}else if(ne(o.instanceOf)&&!(i instanceof o.instanceOf))throw new L(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new L(s(5005));let{properties:n}=o;rt(n)&&Et(i)&&Object.keys(n).forEach(c=>{Yc.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;rt(a)&&Ce(i)&&i.forEach((c,l)=>{Yc.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 ge(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var g,T,_;function l(S,R,q){if(q&&q.includes(S))return"hided";if(e){let H=e(...c);if(c[H.argIndex]===R)return H.value}if(R===c||S in c)return R;try{return R instanceof HTMLElement?`id: ${R.id} type:${ve(R)}`:R instanceof MediaStreamTrack?Ta(R):(JSON.stringify(R),R)}catch(H){return`type:${ve(R)}`}}let u=this._log||y;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(S,R)=>l(S,R,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let h=t?t(...c):Za[a],m=(s==null?void 0:s(...c))||!1;try{let S=n.apply(this,c),R=P();if(hr(S)){let q=`${a.includes("Plugin")?`${((T=(g=c[0]).getName)==null?void 0:T.call(g))||""} `:" "}`;return S.then(H=>(u.info(`${a}() success ${q}${i.call(this,...c)}`),v.addSuccessEvent({key:h,cost:P()-R}),H)).catch(H=>{var w;H=L.convertFrom.call(this,H,a,c.length===1?c[0]:c);let Ee=H.extraCode||H.code,fe=(w=H.message)!=null&&w.includes(Ee)?"":` code:${Ee}`;throw m||u.error(`${a}() failed ${q}${i.call(this,...c)} ${H}${fe} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:H}),H})}return v.addSuccessEvent({key:h}),S}catch(S){S=L.convertFrom.call(this,S,a);let R=S.extraCode||S.code,q=(_=S.message)!=null&&_.includes(R)?"":` code:${R}`;throw m||u.error(`${a}() failed ${S}${q} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:h,error:S}),S}})}var Kc=o=>Q((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 L({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 L({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Zc.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var ed=0,_h,tr=class tr{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",pe());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");ed=ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${ed}`}),this.log.info(`created id=${this.getAlias()}${ed}`),this.installEvent()}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 L({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return _h||(_h=this.doPreload(i)),_h}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield zi(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return tr.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return tr.getStartValidateRule(this.core);case"update":return tr.updateValidateRule;case"stop":return tr.stopValidateRule}}start(i){return f(this,null,function*(){var m,g,T,_;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:h=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=h,!n)throw new L({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:S,status:R,timestamp:q}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,q,S,R,e)}if(h&&!this.screenAudioWorkletNode){let{sign:S,status:R,timestamp:q}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,q,S,R,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()),(m=this.localAudioWorkletNode)==null||m.port.postMessage({type:"enable"}),(g=this.screenAudioWorkletNode)==null||g.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),E(a)||a.forEach(S=>{this.customAudioReferenceMap.set(S,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:S,refId:`o-${this.audioRefId++}`})}),E(c)||(T=this.localAudioWorkletNode)==null||T.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),E(l)||(_=this.localAudioWorkletNode)==null||_.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return f(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;E(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),E(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),E(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return f(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return f(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield vS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new L({code:U.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}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==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${_o(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==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":I.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return f(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return f(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(tr,"updateValidateRule",{type:"object"}),d(tr,"stopValidateRule",{type:"object"}),d(tr,"Name","AudioProcessor");var td=tr;function bS(o,i=p.MAIN){return`https://${vi[i]||Qc(o,i)}/api/v1/audioAiAuth`}function vS(r){return f(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${bS(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=Pi(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",g="Init RTCAudioProcessor failed.",T="";switch(c){case 1:T="Please check your params.";break;case 2:T=`You need to buy packages. Refer to: ${m}`;break;case 3:T="Server is invalid. Please contact our engineer. ";break;case 4:T=`Your packages is not active. Refer to: ${m}`;break;case 5:T=`Your packages is expired. Refer to: ${m}`;break;case 6:T="Your version is not supported.";break}return{auth:!1,status:h,message:l?`${g} Reason: ${l}. ${T}`:`${g}, ${T}`}})}var id=0,gh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new Ko(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)}}reload(i){return f(this,null,function*(){if(i.url){let e=yield Un.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}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 Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==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 _s(o,i){if(i&&typeof i!="function")throw new L({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var Ni=class Ni{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);id=id+1,this.log=i.log.createChild({id:`${this.getAlias()}${id}`}),this.log.info(`created id=${this.getAlias()}${id}`)}getName(){return Ni.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Ni.startValidateRule;case"update":return Ni.updateValidateRule;case"stop":return Ni.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),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 gh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}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.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return f(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{I.off("154",r,this)})};I.on("154",r,this),new Yo}else this.core.trtc.emit(k.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>f(this,null,function*(){return i.play()})});else throw t})}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&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}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(Ni,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],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 L({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 L({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});_s("onTimeUpdate",i.onTimeUpdate),_s("onEnded",i.onEnded),_s("onDurationChange",i.onDurationChange)}}),d(Ni,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){_s("onTimeUpdate",i.onTimeUpdate),_s("onEnded",i.onEnded),_s("onDurationChange",i.onDurationChange)}}),d(Ni,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(Ni,"Name","AudioMixer");var rd=Ni;var od=0,Th,ir=class ir{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",pe("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});od=od+1,this.log=i.log.createChild({id:`${this.getAlias()}${od}`}),this.log.info(`created id=${this.getAlias()}${od}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new L({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Th||(Th=this.doPreload(i)),Th}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield zi(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return ir.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return ir.startValidateRule(this.core);case"update":return ir.updateValidateRule;case"stop":return ir.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 L({code:U.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${Ql()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield DS(t,x(D({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new L({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 g=(h==null?void 0:h.max)>20?"warn":(h==null?void 0:h.max)>10?"info":"debug";this.log[g](`avg cost: ${h.value} max: ${h==null?void 0:h.max}(${_o(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.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return f(this,null,function*(){this.updateConfig(i)})}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)})}updateConfig(i){if(!this.workletNode)return;let e=!1;E(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),E(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(ir,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(ir,"stopValidateRule",{type:"object"}),d(ir,"Name","AIDenoiser");var sd=ir;function DS(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=Pi(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",m="Init RTCAIDenoiser failed.",g="";switch(a){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${m} Reason: ${c}. ${g}`:`${m}, ${g}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var bf=Ge(tt(),1);var Eh=class extends bf.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&&!me&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){re.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){re.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},OS=new Eh,Sh=OS;function Ih([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 Ki(new DataView(new Uint8Array(s).buffer),!0)}function Ah(o){return o.type==="empty"||o.data.byteLength===0}function Ch(o){return o.getInt32(0)===1&&o.getInt8(4)===6}function Rh(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 yh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Rh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Ih),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 bh({frame:o,onSEI:i}){try{let e=new DataView(o.data);if(Ah(o)||!Ch(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 Ki(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 vh=0,Vn=class Vn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);vh++,this.log=i.log.createChild({id:`${this.getAlias()}${vh}`}),this.log.info(`[sei] created id=${this.getAlias()}${vh}`),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 yh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return bh({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:ii?this.encode:yh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:ii?this.decode:bh,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 Vn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Vn,"autoStart",!0),d(Vn,"Name","SEI");var nd=Vn;function Nh({frame:o,onDump:i}){return i==null||i(),o}function Dh({frame:o,onDump:i}){return i==null||i(),o}var vf={"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
|
+
${o.stack}`),!1}},i};var xn=new WeakMap;function jE(i){let t=xn.get(i);t&&(t.forEach(e=>clearTimeout(e)),xn.delete(i))}function qE(i,t){return Me((e,r)=>function(...o){let s=xn.get(this);s||(s=new Map,xn.set(this,s));let n=t(...o),a=s.get(n);if(!a||a<=0){e.apply(this,o);let u=setTimeout(()=>{var m;(m=xn.get(this))==null||m.delete(n)},i);s.set(n,u)}else{clearTimeout(a);let u=window.setTimeout(()=>{var m;e.apply(this,o),(m=xn.get(this))==null||m.delete(n)},i);s.set(n,u)}})}var JE="trtc-sdk-v5",Ip="5.13.2-wasm.1";function Vt(...i){return Me((t,e)=>function(...r){try{Gu.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function Sp(...i){return Me((t,e)=>function(...r){try{Gu.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function Gu(i,t,e,r){if(at(i))for(let o=0;o<i.length;o++)Wu.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else Wu.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function Wu({rule:i,value:t,key:e,fnName:r,className:o}){function s(u){return{code:se.INVALID_PARAMETER,extraCode:u,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(M(t)){if(i.required)throw new oe(s(5001));if(M(i.defaultValue)){je(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let u=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(u=!0),je(i.type[m])&&t instanceof i.type[m]&&(u=!0),Ne(i.type[m])&&ut(t)===i.type[m].toLowerCase()&&(u=!0);if(!u)throw new oe({code:se.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(m=>jo(m)?qs(m):Ne(m)?m:ut(m))},value:t}})}else if(!M(i.type)&&ut(t)!==i.type)throw new oe(s(5002));if(i.allowEmpty===!1){let u=ke(t)&&(t===0||Number.isNaN(t)),m=Ne(t)&&t.trim()==="";if(u||m)throw new oe(s(5003))}if(i.notLessThanZero&&ke(t)&&t<0)throw new oe(s(5006));if(!M(i.min)&&ke(t)&&t<i.min)throw new oe(s(5007));if(!M(i.max)&&ke(t)&&t>i.max)throw new oe(s(5008));if(Ne(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new oe(s(5004))}else if(je(i.instanceOf)&&!(t instanceof i.instanceOf))throw new oe(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new oe(s(5005));let{properties:n}=i;jt(n)&&ar(t)&&Object.keys(n).forEach(u=>{Wu.call(this,{rule:n[u],value:t&&t[u],key:`${u}`,fnName:r,className:o})});let{arrayItem:a}=i;jt(a)&&at(t)&&t.forEach((u,m)=>{Wu.call(this,{rule:a,value:u,key:`${e}[${m}]`,fnName:r,className:o})}),je(i.validate)&&i.validate.call(this,t,e,r,o,this)}function rt(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o,ignoreErrorLog:s}=i;return Me((n,a)=>function(...u){var A,C,N;function m(D,x,Z){if(Z&&Z.includes(D))return"hided";if(e){let ue=e(...u);if(u[ue.argIndex]===x)return ue.value}if(x===u||D in u)return x;try{return x instanceof HTMLElement?`id: ${x.id} type:${ut(x)}`:x instanceof MediaStreamTrack?ad(x):(JSON.stringify(x),x)}catch(ue){return`type:${ut(x)}`}}let p=this._log||F;if(o!=null&&o(...u))return n.apply(this,u);u.length>0?p.info(`${a}() ${JSON.stringify(u,(D,x)=>m(D,x,["userSig","privateMapKey"]))}`):p.info(`${a}()`);let g=r?r(...u):Bd[a],E=(s==null?void 0:s(...u))||!1;try{let D=n.apply(this,u),x=Ee();if(ro(D)){let Z=`${a.includes("Plugin")?`${((C=(A=u[0]).getName)==null?void 0:C.call(A))||""} `:" "}`;return D.then(ue=>(p.info(`${a}() success ${Z}${t.call(this,...u)}`),Q.addSuccessEvent({key:g,cost:Ee()-x}),ue)).catch(ue=>{var H;ue=oe.convertFrom.call(this,ue,a,u.length===1?u[0]:u);let Se=ue.extraCode||ue.code,Ye=(H=ue.message)!=null&&H.includes(Se)?"":` code:${Se}`;throw E||p.error(`${a}() failed ${Z}${t.call(this,...u)} ${ue}${Ye} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:ue}),ue})}return Q.addSuccessEvent({key:g}),D}catch(D){D=oe.convertFrom.call(this,D,a);let x=D.extraCode||D.code,Z=(N=D.message)!=null&&N.includes(x)?"":` code:${x}`;throw E||p.error(`${a}() failed ${D}${Z} params: ${JSON.stringify(u,m)}`),Q.addFailedEvent({key:g,error:D}),D}})}var ju=i=>Me((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 oe({code:se.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(je(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new oe({code:se.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return Gu.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var qu=0,yp,Fi=class Fi{constructor(t){this.core=t;l(this,"log");l(this,"customAudioReferenceMap",new Map);l(this,"audioRefId",0);l(this,"audioContext",Ge());l(this,"localAudioWorkletNode");l(this,"screenAudioWorkletNode");l(this,"mixNode");l(this,"silentNode");qu=qu+1,this.log=t.log.createChild({id:`${this.getAlias()}${qu}`}),this.log.info(`created id=${this.getAlias()}${qu}`),this.installEvent()}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 oe({code:se.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 xi(this.audioContext,r)}catch(o){this.log.error(`preload audioProcessor failed. ${o}`)}finally{URL.revokeObjectURL(r)}})}getName(){return Fi.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return Fi.getStartValidateRule(this.core);case"update":return Fi.updateValidateRule;case"stop":return Fi.stopValidateRule}}start(t){return y(this,null,function*(){var E,A,C,N;let{room:e}=this.core,{sdkAppId:r,userId:o,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:u,enableDump:m,isLocalAudioNeedAudioProcess:p=!0,isScreenAudioNeedAudioProcess:g=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=p,this.core.room.audioManager.isScreenAudioNeedAudioProcess=g,!n)throw new oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),p&&!this.localAudioWorkletNode){let{sign:D,status:x,timestamp:Z}=yield this.getAuthData(r,o,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",r,o,Z,D,x,e)}if(g&&!this.screenAudioWorkletNode){let{sign:D,status:x,timestamp:Z}=yield this.getAuthData(r,o,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",r,o,Z,D,x,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()),(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"enable"}),(A=this.screenAudioWorkletNode)==null||A.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),M(a)||a.forEach(D=>{this.customAudioReferenceMap.set(D,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:D,refId:`o-${this.audioRefId++}`})}),M(u)||(C=this.localAudioWorkletNode)==null||C.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),M(m)||(N=this.localAudioWorkletNode)==null||N.port.postMessage({type:"dump",data:{enable:m}})})}update(t){return y(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:r,processLevel:o}=t;M(e)||(this.customAudioReferenceMap.forEach((u,m)=>{this.customAudioReferenceMap.delete(m),this.core.room.audioManager.updateAudioReference({type:"remove",refId:u})}),e.forEach(u=>{this.customAudioReferenceMap.set(u,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:u,refId:`o-${this.audioRefId++}`})})),M(o)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:o}}),M(r)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:r}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:r}}))})}stop(){return y(this,null,function*(){var e,r;let{room:t}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(r=this.screenAudioWorkletNode)==null||r.port.postMessage({type:"disable"}),yield t.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,e,r){return y(this,null,function*(){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:u}=yield sA({sdkAppId:t,userSig:r,userId:e,timestamp:o});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${u}`),new oe({code:se.INVALID_PARAMETER,message:u});return{sign:n,status:a,timestamp:o}})}initWorkletNode(t,e,r,o,s,n,a,u){t.port.postMessage({type:"init",data:{sdkAppId:String(r),userId:o,timestamp:s,sign:n,status:a}}),t.port.onmessage=m=>{var g;let{data:p}=m;switch(p.type){case"cost":let E=(p==null?void 0:p.value)>10?"info":"debug";this.log[E](`${e==="localAudio"?"":`[${e}] `}avg cost: ${p.value} max: ${p==null?void 0:p.max}(${Vs(new Date(p==null?void 0:p.maxCostTimestamp))}) hist: ${(g=p==null?void 0:p.hist)==null?void 0:g.join(" ")}`);return;case"log":this.log[p.logLevel](`${e==="localAudio"?"":`[${e}] `}${p.value}`);return;case"dump":U.emit("265",{room:u,data:p.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(t){return y(this,null,function*(){var e;if(!(!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(r){this.log.warn(`audio processor auto start failed, error: ${r}`)}})}handleLocalAudioStopped(t){return y(this,null,function*(){var e;!this.hitTest(t.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};l(Fi,"updateValidateRule",{type:"object"}),l(Fi,"stopValidateRule",{type:"object"}),l(Fi,"Name","AudioProcessor");var zu=Fi;function oA(i,t=O.MAIN){return`https://${ni[t]||Hu(i,t)}/api/v1/audioAiAuth`}function sA(o){return y(this,arguments,function*({sdkAppId:i,userId:t,userSig:e,timestamp:r}){let n=`${oA(i)}?sdkAppId=${i}&userId=${t}&userSig=${e}×tamp=${r}`,a=yield fetch(n),{data:{errCode:u,errMsg:m,sign:p,status:g}}=yield a.json();if(g==="1")return{auth:!0,sign:p,status:g,message:m};let E=_i(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",A="Init RTCAudioProcessor failed.",C="";switch(u){case 1:C="Please check your params.";break;case 2:C=`You need to buy packages. Refer to: ${E}`;break;case 3:C="Server is invalid. Please contact our engineer. ";break;case 4:C=`Your packages is not active. Refer to: ${E}`;break;case 5:C=`Your packages is expired. Refer to: ${E}`;break;case 6:C="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${A} Reason: ${m}. ${C}`:`${A}, ${C}`}})}var Ju=0,Ap=class{constructor(t,e){l(this,"audioObjectURL");l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new _n(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&&(M(t.volume)||(this.volume=t.volume),M(t.loop)||(this.loop=t.loop),M(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)}}reload(t){return y(this,null,function*(){if(t.url){let e=yield mc.download(t.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(t),this.updateSettings(t))}else this.mixInput.replaceSource(t.track)})}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 Promise.all([(t=this.player)==null?void 0:t.play(),(e=this.publisher)==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 Pn(i,t){if(t&&typeof t!="function")throw new oe({code:se.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var ai=class ai{constructor(t){this.core=t;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Ju=Ju+1,this.log=t.log.createChild({id:`${this.getAlias()}${Ju}`}),this.log.info(`created id=${this.getAlias()}${Ju}`)}getName(){return ai.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return ai.startValidateRule;case"update":return ai.updateValidateRule;case"stop":return ai.stopValidateRule}}start(t){return y(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),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 Ap(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,t,n)}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)})}handleAutoPlayFailed(t,e,r){return y(this,null,function*(){if(r.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${r}`),yield t.reload(e),yield t.play();else if(r.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let o=()=>{var s;(s=t.play())==null||s.finally(()=>{U.off("154",o,this)})};U.on("154",o,this),new gn}else this.core.trtc.emit(K.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>y(this,null,function*(){return t.play()})});else throw r})}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),M(r)||n.setOperation(r),M(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:a,onTimeUpdate:u,onDurationChange:m,onEnded:p}=t;e&&Q.addCount({key:502009}),r&&Q.addCount({key:502001}),o&&Q.addCount({key:502002}),s&&Q.addCount({key:502003}),n&&Q.addCount({key:502004}),a&&Q.addCount({key:502005}),typeof u!="function"&&Q.addCount({key:502007}),typeof p!="function"&&Q.addCount({key:502008}),typeof m!="function"&&Q.addCount({key:502006})}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()}};l(ai,"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(),a=s.indexOf(n)>=0,u=o.startsWith("blob"),m=o.startsWith("data");if(!(a||u||m))throw new oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new oe({code:se.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});Pn("onTimeUpdate",t.onTimeUpdate),Pn("onEnded",t.onEnded),Pn("onDurationChange",t.onDurationChange)}}),l(ai,"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){Pn("onTimeUpdate",t.onTimeUpdate),Pn("onEnded",t.onEnded),Pn("onDurationChange",t.onDurationChange)}}),l(ai,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(ai,"Name","AudioMixer");var Xu=ai;var Qu=0,bp,$i=class $i{constructor(t){this.core=t;l(this,"log");l(this,"audioContext",Ge("denoiser"));l(this,"workletNode");l(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Qu=Qu+1,this.log=t.log.createChild({id:`${this.getAlias()}${Qu}`}),this.log.info(`created id=${this.getAlias()}${Qu}`)}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},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new oe({code:se.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return bp||(bp=this.doPreload(t)),bp}doPreload(t){return y(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield xi(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return $i.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return $i.startValidateRule(this.core);case"update":return $i.updateValidateRule;case"stop":return $i.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 oe({code:se.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${o}/denoiser-wasm${Jm()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:u,message:m}=yield aA(r,ge(X({},t),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${n}. Message: ${m}`),new oe({code:se.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:a,status:u}}),this.workletNode.port.onmessage=p=>{var E;let{data:g}=p;if(g.type==="cost"){let A=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[A](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${Vs(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(E=g==null?void 0:g.hist)==null?void 0:E.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(t){return y(this,null,function*(){this.updateConfig(t)})}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)})}updateConfig(t){if(!this.workletNode)return;let e=!1;M(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),M(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};l($i,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),l($i,"stopValidateRule",{type:"object"}),l($i,"Name","AIDenoiser");var Yu=$i;function aA(s,n){return y(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:a,errMsg:u,sign:m,status:p}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(p==="1")return{auth:!0,sign:m,status:p,message:u};let g=_i(t)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",E="Init RTCAIDenoiser failed.",A="";switch(a){case 1:A="Please check your params.";break;case 2:A=`You need to buy packages. Refer to: ${g}`;break;case 3:A="Server is invalid. Please contact our engineer. ";break;case 4:A=`Your packages is not active. Refer to: ${g}`;break;case 5:A=`Your packages is expired. Refer to: ${g}`;break;case 6:A="Your version is not supported.";break}return{auth:!1,status:p,message:u?`${E} Reason: ${u}. ${A}`:`${E}, ${A}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var QE=pi(bi(),1);var Rp=class extends QE.EventEmitter{constructor(){super();l(this,"observer");l(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&&!it&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){We.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&F.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){We.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},cA=new Rp,vp=cA;function dA([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 a=0;a<r;a++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Es(new DataView(new Uint8Array(s).buffer),!0)}function uA(i){return i.type==="empty"||i.data.byteLength===0}function lA(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function mA(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 Cp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-mA(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(dA),s=o.reduce((p,g)=>p+g.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),a=new DataView(n),u=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let g=0;g<o[p].dataView.byteLength;g++)a.setInt8(m++,o[p].dataView.getInt8(g));for(let p=0;p<i.data.byteLength;p++)a.setInt8(m++,u.getInt8(p));return i.data=n,i}function Np({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(uA(i)||!lA(e))return i;let r=[],o=0,s=-1,n=-1;for(let a=0;a<i.data.byteLength;a++){let u=e.getUint8(a);if(u===0)o++;else if(u===1){if(o===2||o===3){let m=a-o;if(s===-1?s=m:n===-1&&(n=m,r.push(new Es(new DataView(e.buffer.slice(s,n)))),s=m,n=-1),!(e.getUint8(a+1)===6)){i.data=e.buffer.slice(m);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var Dp=0,hc=class hc{constructor(t){this.core=t;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Dp++,this.log=t.log.createChild({id:`${this.getAlias()}${Dp}`}),this.log.info(`[sei] created id=${this.getAlias()}${Dp}`),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 Cp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return Np({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(K.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:ns?this.encode:Cp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:ns?this.decode:Np,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return hc.Name}getAlias(){return"sei"}getGroup(){return"sei"}};l(hc,"autoStart",!0),l(hc,"Name","SEI");var Zu=hc;function wp({frame:i,onDump:t}){return t==null||t(),i}function Mp({frame:i,onDump:t}){return t==null||t(),i}var YE={"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:
|
|
59
99
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
60
100
|
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:
|
|
61
101
|
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.
|
|
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=>{vf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var JP=Object.keys(vf);var MS=0,ad,Bn=class Bn{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()}${++MS}`}),this.log.info("created")}getName(){return Bn.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*({visible: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(ad)yield ad;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Rf}@${Ve}/assets/debug-dialog.js`;ad=this._core.fileDownloader.loadScript(e),yield ad}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):Nh,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Dh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return Nh({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 Dh({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(Bn,"Name","Debug"),d(Bn,"autoStart",!0);var cd=Bn;var Nf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},dd=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=ue(e,W.INIT),this.stopOB=ct(),this.startOB=ct(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ct(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),le(l,Le(this.stopOB),Re(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Nf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),le(l,Zi(1),Ku(Dn))};le(this.startOB,vn(0),os(a),Le(this.stopOB),Re(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Nf(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 Yi()(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"}))}},kS={type:"object"},Fn=class Fn{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 Fn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Fn.Name}getValidateRule(i){return kS}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 dd(this.core,t,i);return le(r.trackDoneOB,Zi(1),Re(()=>{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 dd(this.core,i.track,i))}}};d(Fn,"Name","TRTCAudioDecoder");var Hn=Fn;var ld=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 N({code:A.INVALID_PARAMETER,message:B({key:V.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(g=>{e.emit(k.AUDIO_FRAME,g)},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,g=l.get(m);g==null||g.abort("disable"),l.delete(m)}});else{let h=l.get(r);h==null||h.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return f(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause()):s.isAvailable&&s.player.pause():(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(),s.isAvailable&&s.player.pause())});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};O([tf({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"}}})],ld.prototype,"enableAudioFrameEvent",1);var Df=new ld;var Of=Ge(tt(),1);var Oh=class extends Of.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=y.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return f(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return f(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},$n=new Oh;var Mf=0,Gn=new Set,Xe=null;Dd(ph);Jo.checkStorage();var z=class z extends kf.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${++Mf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(D({logger:this._log,frameWorkType:z.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(rd,t.assetsPath),this._use(td,t.assetsPath),this._use(sd,t.assetsPath),this._use(Hn,t.assetsPath),this._use(cd),t.enableSEI&&dn&&this._use(nd),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)}),t.enableDbVolume&&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 L({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Sf(this,"trtc")}static create(e){}static _create(e,t){sf();let r=new z(e,t||{});return Gn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){Fe(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})}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(k.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(k.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(k.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=x(D({},e),{uplinkRTT:Math.min(e.uplinkRTT,ws),downlinkRTT:Math.min(e.downlinkRTT,ws)});this.emit(k.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Fe(r,r).add("player-state-changed",s=>{let n=x(D({},s),{userId:e.userId});r.kind===p.VIDEO&&(n.streamType=bi(r.streamType)),this.emit(r.kind===p.AUDIO?k.AUDIO_PLAY_STATE_CHANGED:k.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===A.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=>{Ne(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,x(D({},e),{streamType:bi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(k.ERROR,new L({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,ws),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)/Rt},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)/Rt,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(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.uint32_video_stream_type],point2pointDelay:(g.uint32_video_p2p_delay||0)+(g.uint32_video_cache_ms||0),jitterBufferDelay:g.uint32_video_cache_ms||0,codec:g.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,x(D({},e),{streamType:bi(e.streamType)}))}).add("audio-frame",e=>{this.emit(k.AUDIO_FRAME,e)}),Fe(this,Ae).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}),Xe&&Xe.deviceId===ks){let t=(yield Tr()).find(r=>r.deviceId===ks);t&&Xe.groupId!==t.groupId&&(Xe=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 Tr())[0];if(!t||!Xe||Xe.groupId===t.groupId)return;let r=Xe.deviceId===e.deviceId,s=Xe.deviceId===ks&&Xe.deviceId===t.deviceId;(r||s)&&(Xe=t,this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),Fe(this,$n).add("permission-state-change",e=>{this.emit(k.PERMISSION_STATE_CHANGE,e)})}getNetworkTime(){return ki()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Ef.call(this,{TRTC:z,room:this._room,assetsPath:t,errorModule:{RtcError:L,ErrorCode:U,CoreErrorCode:A,ErrorCodeDictionary:Nt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}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),!ee(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,z.frameWorkType),this._checkTrackToPublish(),Sh.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return f(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ys&&(t.code===A.API_CALL_TIMEOUT||t.code===A.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===A.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return f(this,null,function*(){yield this.exitRoom();let t=D(D({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){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(),If(this),this._room.remotePublishedUserMap.forEach(e=>{Ne(e.remoteAudioTrack),Ne(e.remoteVideoTrack),Ne(e.remoteAuxiliaryTrack)})}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(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Ne(this),this.removeAllListeners(),this._room.destroy(),Gn.delete(this),Gn.size===0&&Sh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),I.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 vt(this._room.audioManager),a={},c={muted:!0};s&&(E(s.microphoneId)?E(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&X(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),E(s.profile)||(ee(s.profile)?ra[s.profile]&&n.setProfile(ra[s.profile]):n.setProfile(s.profile)),X(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 L({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=L.convertFrom(l.error)),this.emit(k.PUBLISH_STATE_CHANGED,x(D({},l),{error:u}))}),n.on("6",()=>{this.emit(k.ERROR,new L({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),Fe(n,n).add("player-state-changed",l=>{this.emit(k.AUDIO_PLAY_STATE_CHANGED,x(D({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=x(D({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),I.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}),Jt(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),I.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Ne(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 qe(this._room.videoManager),l={},u={};a&&(de(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),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=Ln(a.qosPreference)),E(a.profile)||(ee(a.profile)?Ft[a.profile]&&c.setProfile(Ft[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(hs(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,x(D({},m),{streamType:bi(m.streamType)}))}),c.on("5",m=>{this.emit(k.ERROR,new L({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 g;m.error&&(g=L.convertFrom(m.error)),this.emit(k.PUBLISH_STATE_CHANGED,x(D({},m),{error:g}))}),c.on("6",()=>{this.emit(k.ERROR,new L({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)),Fe(c,c).add("player-state-changed",m=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,x(D({},m),{userId:"",streamType:"main"}))}).add("video-size-changed",m=>{this.emit(k.VIDEO_SIZE_CHANGED,x(D({},m),{streamType:bi(m.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=x(D({},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)||(ee(a.profile)?Ft[a.profile]&&this._localVideoTrack.setProfile(Ft[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(Ln(a.qosPreference)),E(a.small)||(de(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(hs(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}),Jt(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(),Ne(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){var m,g;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 st(this._room.videoManager);a.on("4",T=>{let _;T.error&&(_=L.convertFrom(T.error)),this.emit(k.PUBLISH_STATE_CHANGED,x(D({},T),{error:_}))}),a.once("first-video-frame",T=>{this.emit(k.FIRST_VIDEO_FRAME,x(D({},T),{streamType:bi(T.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(E(n.profile)||(ee(n.profile)?oa[n.profile]&&a.setProfile(oa[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=Ln(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 Ci(this._room.audioManager);let T=h.getAudioTracks()[0];(m=e.option)!=null&&m.systemAudio&&!((g=e.option)!=null&&g.audioTrack)&&(c.sourceTrack=T),yield c.setInputMediaStreamTrack(T),de(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(Fe(a,a).add("player-state-changed",T=>{this.emit(k.VIDEO_PLAY_STATE_CHANGED,x(D({},T),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let T=[a];c&&(T.push(c),this._checkScreenAudioEchoCancellation(a,c)),this._room.publish(...T).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=x(D({},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=Ln(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!E(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),this._room.publish(...l).catch(()=>{})}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),this._room.unpublish(...l).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}),Jt(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 L({code:U.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",h=>{this.emit(k.VIDEO_SIZE_CHANGED,x(D({},h),{streamType:bi(h.streamType)}))}),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 S,R;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}),Jt(m,e);let g=E(n==null?void 0:n.receiveWhenViewVisible)?(S=m.option)==null?void 0:S.receiveWhenViewVisible:n.receiveWhenViewVisible,T=E(t)?m.view:t,_=E(n==null?void 0:n.viewRoot)?(R=m.option)==null?void 0:R.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:T,receiveWhenViewVisible:g,viewRoot:_})})}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 r.code!==U.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));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{_f.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===z.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(z.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(ee(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 Tr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Xe=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(k.ERROR,new L({code:U.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=X(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),le(ue(n,"decode-failed"),Le(ue(n,W.INIT)),Re(()=>{this.startPlugin(Hn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),I.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}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}`),I.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;le(ue(e,"decode-failed"),Le(ue(e,W.INIT)),ih(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),io(ue(e,"decode-downgrade-state-changed")),Re(n=>{s=n.state,this.emit(k.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,x(D({},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&&!yo(t)){let a=vo(s.view);a.length>0&&(yield r.play(a,t))}if(!E(e)){let a=vo(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 vt&&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 ni){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:bi(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}_${bi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ce(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(g=>{l.set(g.target,g.isIntersecting),e.log.info(`view ${g.target.id} is${g.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(T=>T)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let h=new Set(vo(t));l.forEach((m,g)=>{h.has(g)||(a.unobserve(g),l.delete(g))}),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()),this._clearRemoteTracks()})}_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),Ne(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"&&(!Xe||ts(Xe))&&(this._initActiveSpeaker(),I.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Xe&&!ts(Xe))this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:Xe});else{let e=yield Tr();e[0]&&!ts(e[0])?(Xe=e[0],this.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):I.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:x(D({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return f(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Df.call(e,D({trtcInstance:this},t))})}static setLogLevel(e,t){y.setLogLevel(e),E(t)||(t?y.enableUploadLog():y.disableUploadLog())}static isSupported(){return rc(z.frameWorkType)}static getPermissions(r){return f(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield $n.request(t).catch(a=>{var c;return y.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([$n.get("camera"),$n.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return _t(e)}static getMicrophoneList(e=!0){return ft(e)}static getSpeakerList(e=!0){return Tr(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(me&&(e===ao.SPEAKER||e===ao.HEADSET)){let r=yield z.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Gn.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Tr()).forEach(r=>{r.deviceId===e&&(Gn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(k.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Xe=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(qr.version=a),e){case"count":qr.addCount({key:t,useUV:n});break;case"enum":qr.addEnum({key:t,value:r,useUV:n});break;case"number":qr.addNumber({key:t,value:r,split:s,max:c});break}}};d(z,"VERSION",ph),d(z,"_loggerManager",y),d(z,"EVENT",k),d(z,"ERROR_CODE",U),d(z,"TYPE",ao),d(z,"frameWorkType",30),O([ge({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"}})})],z.prototype,"use",1),O([Ke($e.TRTC.enterRoom),Cr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Q(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),ge()],z.prototype,"enterRoom",1),O([ge()],z.prototype,"exitRoom",1),O([Ke($e.TRTC.switchRoom),ge(),kt()],z.prototype,"switchRoom",1),O([Ke($e.TRTC.switchRole),lo("room",{merge:(e,t)=>t}),ge()],z.prototype,"switchRole",1),O([ge()],z.prototype,"destroy",1),O([Ke($e.TRTC.startLocalAudio),Cr("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)}),ge()],z.prototype,"startLocalAudio",1),O([Ke($e.TRTC.updateLocalAudio),lo("audio",{debounce:{delay:200,getKey:()=>`${Mf}-localAudio`,isNeedToDebounce:e=>{var t;return!E((t=e.option)==null?void 0:t.captureVolume)}}}),ge()],z.prototype,"updateLocalAudio",1),O([Rr("audio"),ge()],z.prototype,"stopLocalAudio",1),O([Ke($e.TRTC.startLocalVideo),Cr("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)}),ge()],z.prototype,"startLocalVideo",1),O([Ke($e.TRTC.updateLocalVideo),lo("video"),ge()],z.prototype,"updateLocalVideo",1),O([Rr("video"),ge()],z.prototype,"stopLocalVideo",1),O([Ke($e.TRTC.startScreenShare),Cr("screen",()=>!0),ge()],z.prototype,"startScreenShare",1),O([Ke($e.TRTC.updateScreenShare),lo("screen"),ge()],z.prototype,"updateScreenShare",1),O([ge()],z.prototype,"stopScreenShare",1),O([Ke($e.TRTC.startRemoteVideo),Cr(e=>`v${e.userId}${e.streamType}`,()=>!0),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"startRemoteVideo",1),O([Ke($e.TRTC.updateRemoteVideo),lo(e=>`v${e.userId}${e.streamType}`),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"updateRemoteVideo",1),O([Ke($e.TRTC.stopRemoteVideo),Q(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)})}),ge({getRemoteId:e=>`${e.userId}_${e.streamType}`})],z.prototype,"stopRemoteVideo",1),O([Rr(e=>`v${e.userId}${e.streamType}`)],z.prototype,"_stopRemoteVideo",1),O([Ke(...$e.TRTC.muteRemoteAudio),ge({getRemoteId:e=>e})],z.prototype,"muteRemoteAudio",1),O([fh(...$e.TRTC.setRemoteAudioVolume),Af(200,e=>e),ge({getRemoteId:e=>e})],z.prototype,"setRemoteAudioVolume",1),O([Kc("start"),gt(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),Cr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Vl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],z.prototype,"startPlugin",1),O([Kc("update"),lo((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(Jt(e[1],t[1]),e)}),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Bl[e.getName()]})],z.prototype,"updatePlugin",1),O([Kc("stop"),Rr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),ge({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Fl[e.getName()]})],z.prototype,"stopPlugin",1),O([fh(...$e.TRTC.enableAudioVolumeEvaluation)],z.prototype,"enableAudioVolumeEvaluation",1),O([ge()],z.prototype,"getVideoSnapshot",1),O([ge()],z.prototype,"_setCurrentSpeaker",1),O([Cr(e=>`a${e.userId}`,()=>!0)],z.prototype,"_startRemoteAudio",1),O([Q(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(x(D({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Rr(e=>`a${e.userId}`)],z.prototype,"_stopRemoteAudio",1),O([Rr("room")],z.prototype,"_exitRoom",1),O([Rr("screen")],z.prototype,"_stopScreenShare",1),O([Ke(...$e.TRTC.sendSEIMessage),dh({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],z.prototype,"sendSEIMessage",1),O([Ke($e.TRTC.sendCustomMessage),dh({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],z.prototype,"sendCustomMessage",1),O([Ke($e.TRTC.create)],z,"_create",1);var Mh=z,Wn=Mh;var kh=class{constructor(){d(this,"_set",new Set);I.on(C.LEAVE_SUCCESS,this.delete,this),I.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 wS(){return f(this,null,function*(){let o,i;try{let g=yield ft();o=g&&g.length}catch(g){}try{let g=yield _t();i=g&&g.length}catch(g){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=Ei.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};re.uploadEvent({log:`trtcstats-${JSON.stringify(h)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(h)}`),re.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(m)}`,userId:this.userId}),Zl()})}function wf(){return Q(o=>{let i=new kh;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 N({code:A.INVALID_OPERATION,message:B({key:V.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new N({code:A.INVALID_OPERATION,message:B({key:V.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}`),I.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=At.getEnv();n||(n=wi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(sa.OLD_CLOUD_LADDER)?n=wi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(sa.WEBRTC)&&(n=wi.WEBRTC))),re.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),Ei.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,wS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!At.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=At.performanceNow(),I.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&re.uploadEvent({log:`stat-conv-${Number(Qt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),I.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var xf=()=>Q(o=>function(...i){return f(this,null,function*(){I.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),I.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Lf(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Uf=Ge(tt());var Te={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7"};var Ut={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},Pf=[Ut.UPDATE_REMOTE_MUTE_STAT,Ut.UPLINK_NETWORK_STATS,Ut.USER_LIST_RES,Ut.MUTE_RESULT,Ut.SERVER_FIRST_PACKAGE_RECEIVED,Ut.RECEIVE_CUSTOM_MSG,Ut.UPDATE_NETWORK_TIME_RESULT],$={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",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Y={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",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var ud=new Set;function Vf(o){let i=[...ud.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var LS=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],gs=class extends Uf.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-ud.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ud.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);return LS.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),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=P();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Pr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?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 N({code:A.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(Te.SETUP_FAILED,new N({code:A.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(Te.SETUP_FAILED,new N({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Us(e.data);let t=JSON.parse(e.data),{cmd:r,data:s}=t,n=Object.values(Ut),c=Object.keys(Ut)[n.indexOf(r)],l=$[c]||r;switch(Pf.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Ut.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=s.clientIp,this._signalInfo.signalIp=s.signalInnerIp,s.svrTime&&Kn(s.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${P()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:P()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Te.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new N({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:B({key:V.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:u}),this.emit(Te.SETUP_FAILED,u)}break}case Ut.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;ai(!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:Y.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:$.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:P()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.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+=Us(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=()=>{clearTimeout(m),u(new N({code:A.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Te.CLOSE,h);let m=setTimeout(()=>{this.off(s,g),this.off(Te.CLOSE,h);let _=new N({code:A.API_CALL_TIMEOUT,message:B({key:V.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(_),u(_)},r),g=_=>{_.data.seq===T&&(clearTimeout(m),this.off(s,g),this.off(Te.CLOSE,h),c&&(_.data.receiveTime=Date.now()),l(_))};this.on(s,g);let T=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return pi({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===A.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Te.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),ud.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"),this.emit(Te.CLOSE)}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($.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off($.JOIN_ROOM_RESULT,t))};this.on($.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Te.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Te.CONNECTED):e==="DISCONNECTED"&&this.emit(Te.DISCONNECTED))}};O([yt({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())}})],gs.prototype,"connect",1);var Bf=Ge(tt());var wh=0,xh=!1,hd=new Set,PS=o=>wh>2&&!xh&&hd.size===0&&o,Lh=!1,dt=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 Bf.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=P())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(P()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:P()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.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(),hd.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 N({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Ht;let i=null;if(this._isUplink){if(!_r()||this._peerConnection.getSenders().length===0)return Ht;i=this._peerConnection.getSenders()[0].transport}else{if(!jr()||this._peerConnection.getReceivers().length===0)return Ht;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Ht}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Se.FAILED||i.target.connectionState===Se.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new N({message:r,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Se.CONNECTED||i.target.connectionState===Se.COMPLETED)&&(this.logSelectedCandidate(),re.logSuccessEvent({userId:this._room.userId,eventType:ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(wh=0,xh=!1,Lh=!0,hd.add(this)):hd.delete(this),I.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(fr(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 N({code:A.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{I.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new N({code:A.API_CALL_TIMEOUT,message:"connection timeout"});wh+=1,PS(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Ms);I.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(Te.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=xi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new N({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:B({key:this._isUplink?V.UPLINK_RECONNECTION_FAILED:V.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(Te.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)}};O([Tt(521712,!1)],dt.prototype,"setOffer",1),O([Tt(521713,!1)],dt.prototype,"setAnswer",1);var Bh=Ge(Vh());var be=function(o){return Bh.default.parse(o)},Vt=function(o){return Bh.default.write(o)},jf=function(o){let i=be(o);return i.media.forEach(e=>{e.type===p.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Vt(i)};function Xf(o){let i=be(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(" ")}}),Vt(i)}function md(o){return Object.keys(o).filter(i=>o[i])}var Es=class Es extends dt{constructor(e){super(x(D({},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 ni(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new yi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ls(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 Wt(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===Os?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=be(e);return t.media.forEach(r=>{r.type===p.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),Vt(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=be(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),Vt(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)===Se.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Se.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new N({code:A.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=D({},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} [${md(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=Y.UNSUBSCRIBE,n=$.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=$.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new N({code:a.code,message:B({key:V.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:Y.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:$.SUBSCRIBE_RESULT,timeout:Fd});if(!this._peerConnection){let a=new N({code:A.INVALID_OPERATION,message:B({key:V.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};pt()&&this._sdpSemantics===ur?(this._peerConnection.addTransceiver(p.AUDIO,{direction:oe.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:oe.RECVONLY}),this._peerConnection.addTransceiver(p.VIDEO,{direction:oe.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield ic();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=Xf(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=jf(t.sdp),this._sdpSemantics===ur&&(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===Dr)throw new N({code:A.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new N({code:t,message:B({key:V.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{be(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(Os)});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(Os)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Ld)});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(!(Ue(Es.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=Gt(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}};O([Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new N({code:A.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Es.prototype,"subscribe",1),O([Tt(521717,!1)],Es.prototype,"unsubscribe",1),O([gt(dt.prototype.afterConnect),Tc(dt.prototype.beforeConnect)],Es.prototype,"connect",1);var Fh=Es,Hh=Fh;var Qf={voiceActivityDetection:!1},Ss=class Ss extends dt{constructor(e){super(x(D({},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&&(gi()?(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(),pt()?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:oe.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?p.VIDEO:c||p.VIDEO,{direction:oe.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||p.VIDEO,{direction:oe.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||p.VIDEO:p.VIDEO,{direction:oe.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(oe.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(oe.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(oe.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(!gi()){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=x(D({},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=x(D({},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(oe.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:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:$.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:$.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),Ti){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:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:$.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`),pt()?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===oe.INACTIVE&&(yield this.setTransceiverDirection(oe.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;gi()&&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 qe&&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===To||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=be(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;gi()&&(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`),pt()?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(oe.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)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=(${oe.INACTIVE}|${oe.RECVONLY}|${oe.SENDONLY})`))&&a++,t.includes(a)){if(e===oe.INACTIVE&&l.includes(`a=${oe.RECVONLY}`))return s=!0,`a=${e}`;if(e===oe.SENDONLY&&l.includes(`a=${oe.INACTIVE}`))return s=!0,`a=${oe.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(pt()?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(Qf);te&&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:Y.PUBLISH_CHANGE,data:n,responseCommand:$.UPDATE_OFFER_RESULT,timeout:Bd,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(!cn())return s?t===p.VIDEO?this.updateVideoBandwidthRestriction(s,e,r):this.updateAudioBandwidthRestriction(s,e):void 0;let a,c=this._peerConnection.getSenders();if(pt()){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";te&&(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 te&&(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(Qf);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Y.PUBLISH,responseCommand:$.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof st||this.localAuxVideoTrack instanceof st,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=be(e);return s.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Vt(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 g=this._isPublishingAux?p.AUXILIARY:p.BIG;c=yield this.setBandwidth({bandwidth:h,type:p.VIDEO,sdp:c,videoType:g})}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(Y.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return f(this,null,function*(){if(!(Ue(Ss.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,responseCommand:$.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=Gt(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)&&I.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{be(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===To&&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===Dr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new N({code:A.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})})):new N({code:A.UNKNOWN,message:B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:$.PUBLISH_RESULT,code:e,message:t}})})}};O([Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new N({code:A.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ss.prototype,"publish",1),O([Tt(521715,!1)],Ss.prototype,"unpublish",1),O([gt(dt.prototype.afterConnect),Tc(dt.prototype.beforeConnect)],Ss.prototype,"connect",1);var $h=Ss,qn=$h;var jn=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,g,T,_,S,R,q;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 Ee=2,fe=this._prevEncoderImplementation;c===p.AUXILIARY&&(Ee=7,fe=this._prevAuxEncoderImpl),I.emit("262",{userId:i.userId,streamType:Ee,prevImplementation:fe,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}`),I.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}`),I.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 if(a.type==="candidate-pair")fr(a)&&(this.totalBytesSent=a.bytesSent,X(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)));else if(a.type==="media-source"){if(a.kind===p.AUDIO)e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,E((T=(g=(m=i.localMainAudioTrack)==null?void 0:m.sourceTrack)==null?void 0:g.stats)==null?void 0:T.deliveredFramesDuration)?a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration):e.audio.totalSamplesDuration=i.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(a.kind===p.VIDEO)if(a.trackIdentifier===i.getVideoTrackId(p.VIDEO))if((R=(S=(_=i.localMainVideoTrack)==null?void 0:_.sourceTrack)==null?void 0:S.stats)!=null&&R.deliveredFrames){let{deliveredFrames:H}=i.localMainVideoTrack.sourceTrack.stats;e.video.framesCaptured=H,i.localMainVideoTrack.stat.framesCaptured&&i.localMainVideoTrack.stat.framesCaptured>0&&H>=i.localMainVideoTrack.stat.framesCaptured?e.video.fpsCapture=Math.floor((H-i.localMainVideoTrack.stat.framesCaptured)/this.statInterval):e.video.fpsCapture=a.framesPerSecond}else e.video.fpsCapture=a.framesPerSecond;else a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond}if(!E(a.audioLevel)&&((q=i.localMainAudioTrack)!=null&&q.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!E(a.frameWidth)){let H=p.SMALL;a.trackIdentifier===i.getVideoTrackId(p.VIDEO)||a.ssrc===r.video?H=p.VIDEO:(a.trackIdentifier===i.getVideoTrackId(p.AUXILIARY)||a.ssrc===r.auxiliary)&&(H=p.AUXILIARY),e[H].frameWidth=a.frameWidth,e[H].frameHeight=a.frameHeight,e[H].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,g;if(h.type==="codec"&&this._decodeMap.set(h.id,h),h.type==="inbound-rtp"){let T=(h.mediaType||h.kind)===p.AUDIO;if(T){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:_}=i;_.stat.packetsReceived=h.packetsReceived,_.stat.bytesReceived=h.bytesReceived,_.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=_.stat.end2EndDelay,e.hasAudio=!0}else{if(te&&h.bytesReceived===0)return;let _;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=Mt[(m=this._decodeMap.get(h.codecId))==null?void 0:m.mimeType.split("/")[1]]||"h264",e.video.codec=i.videoCodec,_=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}`),I.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,_=i.remoteAuxiliaryTrack,e.auxiliary.p2pDelay=_.stat.end2EndDelay,e.hasAuxiliary=!0,e.video.codec=((g=this._decodeMap.get(h.codecId))==null?void 0:g.mimeType.split("/")[1].toLowerCase())||"h264"),_&&(_.stat.packetsReceived=h.packetsReceived,_.stat.bytesReceived=h.bytesReceived,_.stat.packetsLost=h.packetsLost,_.stat.framesReceived=h.framesReceived,_.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(_.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)),e.video.p2pDelay=_.stat.end2EndDelay)}h.jitterBufferDelay&&(T?(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"&&fr(h)&&(this.totalBytesReceived=h.bytesReceived,X(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=P(),a=yield s.getStats(),c=P();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(Ii(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m,g,T;if(!Ii(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*Rt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Rt),E(i.senderStats.audio.audioCaptureEnergyAfter3a)||(_.uint32_audio_capture_energy_after3a=i.senderStats.audio.audioCaptureEnergyAfter3a*Rt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let S=[];if(i.senderStats.video.bytesSent){let q={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};S.push(q)}if(i.senderStats.small.bytesSent){let q={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};S.push(q)}if(i.senderStats.auxiliary.bytesSent){let q={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};S.push(q)}let R={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:S,msg_network_status:R}}let r=(m=pe())==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(_=>{let S={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let R={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};S.msg_audio_status=R}if(_.hasVideo){let R=t.get(`${_.userId}_${Pd}`),q=R?R.duration:0,H={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:q,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount,uint32_video_p2p_delay:_.video.p2pDelay,uint32_video_codec:_.video.codec};S.msg_video_status.push(H)}if(_.hasAuxiliary){let R=t.get(`${_.userId}_${Ud}`),q=R?R.duration:0,H={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:q,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount,uint32_video_p2p_delay:_.auxiliary.p2pDelay,uint32_video_codec:_.video.codec};S.msg_video_status.push(H)}e.msg_down_stream_info.push(S)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,S=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)S.uint32_audio_codec_bitrate=0;else{let R=this.getDifferenceValue(_.uint32_audio_codec_bitrate,S.uint32_audio_codec_bitrate);S.uint32_audio_codec_bitrate=Math.round(R*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=S.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/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(_=>{let S=c.find(fe=>fe.uint32_video_stream_type===_.uint32_video_stream_type);if(!S||S.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let R=0,q=0,H=0;S&&_.uint32_video_codec_bitrate>=S.uint32_video_codec_bitrate&&(R=S.uint32_video_codec_bitrate,q=S.uint32_video_enc_fps,H=S.uint32_video_codec_fps);let Ee=this.getDifferenceValue(R,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Ee*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(q,_.uint32_video_enc_fps)/s),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(H,_.uint32_video_codec_fps)/s),S.uint32_video_width===0&&S.uint32_video_height===0&&S.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),E(S.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(S.uint32_key_frame_count,_.uint32_key_frame_count))),E(S.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(S.uint32_nack_count,_.uint32_nack_count))),E(S.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(S.uint32_pli_count,_.uint32_pli_count))),E(S.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(S.uint32_video_arq_packets,_.uint32_video_arq_packets))),E(S.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(S.uint32_encode_cost,_.uint32_encode_cost)/s)),E(S.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(S.uint32_send_packet_cost,_.uint32_send_packet_cost)/s))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>u.find(S=>S.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;return h.forEach(_=>{let S=u.find(R=>R.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!Ii(_.msg_audio_status)&&!Ii(S.msg_audio_status)){let R=_.msg_audio_status,q=S.msg_audio_status,H=this.getDifferenceValue(q.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms_count);delete R.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(q.uint32_audio_cache_ms,R.uint32_audio_cache_ms)/H)||0;let Ee=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Ee&&(Ee.remoteAudioTrack.stat.jitterBufferDelay=R.uint32_audio_cache_ms),R.uint32_audio_origin_lost=this.getDifferenceValue(q.uint32_audio_origin_lost,R.uint32_audio_origin_lost),R.uint32_audio_receive=this.getDifferenceValue(q.uint32_audio_receive,R.uint32_audio_receive),R.uint32_audio_receive+=R.uint32_audio_origin_lost;let fe=this.getDifferenceValue(q.uint32_audio_codec_bitrate,R.uint32_audio_codec_bitrate);R.uint32_audio_codec_bitrate=Math.round(fe*8/s),R.uint32_audio_total_bitrate=Math.round(fe*8/s)}else _.msg_audio_status={};if(_.msg_video_status&&S.msg_video_status){let R=S.msg_video_status;_.msg_video_status=_.msg_video_status.filter(H=>R.find(Ee=>Ee.uint32_video_stream_type===H.uint32_video_stream_type)),_.msg_video_status.forEach(H=>{let Ee=R.find(x_=>x_.uint32_video_stream_type===H.uint32_video_stream_type),fe=Ee.uint32_video_receive,w=Ee.uint32_video_origin_lost,N_=Ee.uint32_video_codec_bitrate,D_=Ee.uint32_video_receive_fps,O_=Ee.uint32_video_dec_fps;H.uint32_video_origin_lost=this.getDifferenceValue(w,H.uint32_video_origin_lost),H.uint32_video_receive=this.getDifferenceValue(fe,H.uint32_video_receive)+H.uint32_video_origin_lost;let M_=this.getDifferenceValue(N_,H.uint32_video_codec_bitrate);H.uint32_video_codec_bitrate=Math.round(M_*8/s);let k_=this.getDifferenceValue(D_,H.uint32_video_receive_fps);H.uint32_video_receive_fps=Math.round(k_/s),H.uint32_video_dec_fps=Math.round(this.getDifferenceValue(O_,H.uint32_video_dec_fps)/s);let w_=this.getDifferenceValue(Ee.uint32_video_cache_ms_count,H.uint32_video_cache_ms_count);delete H.uint32_video_cache_ms_count,H.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ee.uint32_video_cache_ms,H.uint32_video_cache_ms)/w_)||0})}}),(T=n.msg_device_info)!=null&&T.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(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let S=a.receiverStats.find(R=>R.userId===_.userId);if(S&&S.audio.concealedSamples&&S.audio.totalSamplesReceived){let R=(_.audio.silentConcealedSamples||0)-(S.audio.silentConcealedSamples||0),q=_.audio.concealedSamples-S.audio.concealedSamples,H=_.audio.totalSamplesReceived-S.audio.totalSamplesReceived,Ee=Math.floor((q-R)/H*1e3*s);if(Ee>s*1e3/5){let fe=h.find(w=>w.msg_user_info.str_identifier===_.userId);fe&&(fe.msg_audio_status.uint32_audio_block_time=Ee)}}}}),e.msg_down_stream_info.forEach(_=>{_.msg_video_status.forEach(S=>{S.uint32_video_codec_bitrate===0&&S.uint32_video_receive_fps===0&&(S.uint32_video_width=0,S.uint32_video_height=0)})}),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(){var i;this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,(i=this.room.localMainVideoTrack)!=null&&i.stat&&(this.room.localMainVideoTrack.stat.framesCaptured=0)}};var Kf=Ge(tt());function Yf(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=x(D({},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 Zf(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=Yf(r);s.totalCost===0&&(s.totalCost=Date.now()-t),i(s)}))}var qS=700,ho=class ho extends Kf.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($.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Te.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)===Se.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt: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,g=this._downlinkPrevStatMap.get(c),T=u-g.totalPacketsLost,_=h-g.totalPacketsReceived;T<=0||_<0?m=0:m=Math.round(T/(T+_)*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||!jr())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"&&X(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===Se.DISCONNECTED||e.connectionState===Se.FAILED||e.connectionState===Se.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=ie.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];I.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=x(D({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(ho.EVENT_NETWORK_QUALITY,r);let s=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&s-ho.lastPingTime>t.interval*1e3){ho.lastPingTime=Date.now();let a=t.domain.map(c=>Zf(c).then(l=>({domain:c,cost:l.totalCost})));Promise.all(a).then(c=>{this.pingResults.isPoorNetwork=c.some(l=>l.cost>qS),this.pingResults.timestamp=s,this.pingResults.data=c,c.forEach(l=>{v.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&&(ie.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(ho,"EVENT_NETWORK_QUALITY","0"),d(ho,"lastPingTime",0);var Is=ho;function jS({fn:o,context:i}){return function(...e){try{let t=o.apply(i,e);return hr(t)?t.catch(r=>y.error(`${o.name}() error observed ${r}`)):t}catch(t){y.error(`${o.name}() error observed ${t}`)}}}var pd=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]=jS({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:Ve,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,Br().then(()=>{this._basicInfo.string_os_version=Wi(),this._basicInfo.string_device_name=Gi()||this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),I.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)=>I.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),ie.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 N?Number(e.getExtraCode()||e.getCode()):A.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}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 N?Number(e.getExtraCode()||e.getCode()):A.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:x(D({},XS),{msg_user_info:new Xn({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 Xn({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,v.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/Rt*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Rt,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,g=h.uint32_video_stream_type===7,T=`${l}_${m?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(T);if(_&&(m&&(u!=null&&u.remoteVideoTrack.isSubscribed)||g&&(u!=null&&u.remoteAuxiliaryTrack))){_.totalVideoFPS+=h.uint32_video_receive_fps,_.totalVideoBitrate+=h.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=h.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=h.uint32_video_height);let S=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;S.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=S.stat.jitterBufferDelay),S.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(S.stat.framesDecoded/S.stat.framesReceived*nr(10,6)))}}),!yo(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/Rt*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/Rt,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 N?e.getExtraCode()||e.getCode():A.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&dr)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&lr)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Nr)>=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:g,totalAudioDelay:T,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),m&&T&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(T/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,mo));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>mo&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+mo)}),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>mo&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+mo)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>mo&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+mo)}getReportData(){this._basicInfo.uint32_networkType=wr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Xn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:bo(this._signalInfo.relayIp),uint32_client_ip:bo(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*nr(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:bo(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return Vs(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*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=pr.enable?Vi(i,2001,e):yield ol(i),r=t instanceof ArrayBuffer,s=`${Ui(e,ar.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t));let a=[this.uploadKVStat(v),this.uploadKVStat(qr)];n||a.push(Bi({url:s,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=x(D({},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=pr.enable?Vi(e,2003,this._room.sdkAppId):yield ol(e),r=t instanceof ArrayBuffer,s=`${Ui(+this._room.sdkAppId,ar.KV_STAT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||Bi({url:s,body:t})})}};O([yt({settings:{timeout:500,retries:3}})],pd.prototype,"upload",1);var mo=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},Xn=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}},e_=pd;var Gh=class{constructor(){d(this,"_startTime");d(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=P())}stop(){this._endTime===0&&(this._endTime=P())}getDuration(){return this._endTime===0?P()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},fd=Gh;var Wh=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)=>I.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>I.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 fd,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()}},t_=Wh;var Jh=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);d(this,"_videoEncodeFailedCount",0);d(this,"_audioEncodeFailedCount",0);d(this,"_encodeFailedThreshold",3);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)=>I.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>I.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 fd;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}){if(this.hitTest(i)){if(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"})})}),e.msg_up_stream_info.msg_video_status){let t=e.msg_up_stream_info.msg_video_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(r!=null&&r.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&(re.uploadEvent({userId:this._room.userId,log:`stat-${ze.VIDEO_ENCODE_FAILED_DURING_CALL}`}),this._videoEncodeFailedCount=0)):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let t=e.msg_up_stream_info.msg_audio_status,r=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(r==null?void 0:r.stat.bytesSent)||0;if((r==null?void 0:r.isMediaTrackActive)===!1||s<=0)return;t.uint32_audio_codec_bitrate===0&&(r!=null&&r.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&(re.uploadEvent({userId:this._room.userId,log:`stat-${ze.AUDIO_ENCODE_FAILED_DURING_CALL}`}),this._audioEncodeFailedCount=0)):this._audioEncodeFailedCount=0}}}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>ca?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=P();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=P();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()<ca&&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=P(),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()}},i_=Jh;var s_=Ge(tt(),1);var _d=class{constructor(i,e,t,r,s,n=4/3){this.vbMode=i;this.faceDetectorHash=t;this.visionTaskRegistry=r;this.logger=s;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=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}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?v.addSuccessEvent({key:s.key}):v.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:g}=this.calculateBoundary(c,s,i,t),{min:T,offset:_}=this.calculateBoundary(l,n,e,r);return u=2*m+t,h=2*T+r,u/h>this.originalAspect?(u=h*this.originalAspect,g=c-u/2):(h=u/this.originalAspect,_=l-h/2),t/s>a&&(g=0,_=0,u=s,h=n),g=Math.max(0,Math.min(g,s-u)),_=Math.max(0,Math.min(_,n-h)),{sx:g,sy:_,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=D({},i),this.animationState.target=D({},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)),X(this.animationState.current.scaleOffsetX)&&X(this.animationState.target.scaleOffsetX)&&X(this.animationState.current.scaleOffsetY)&&X(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(nr(i.sx-e.sx,2)+nr(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,g,T,_,S,R,q,H;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:(g=(m=this.animationState.current)==null?void 0:m.scaleOffsetY)!=null?g:0,timestamp:Date.now()};this.animationState.target={sx:i/2,sy:r+n/2,cropWidth:i,cropHeight:e,scaleRatio:(_=(T=this.animationState.target)==null?void 0:T.scaleRatio)!=null?_:1,scaleOffsetX:(R=(S=this.animationState.target)==null?void 0:S.scaleOffsetX)!=null?R:0,scaleOffsetY:(H=(q=this.animationState.target)==null?void 0:q.scaleOffsetY)!=null?H: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 zS=`#version 300 es
|
|
102
|
+
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=>{YE[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var XV=Object.keys(YE);var hA=0,Ku,pc=class pc{constructor(t){this.core=t;l(this,"_core");l(this,"log");l(this,"dumpLocalVideoMap",{});l(this,"dumpRemoteVideoMap",{});l(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++hA}`}),this.log.info("created")}getName(){return pc.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*({visible: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(Ku)yield Ku;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${JE}@${dt}/assets/debug-dialog.js`;Ku=this._core.fileDownloader.loadScript(e),yield Ku}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):wp,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Mp,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return wp({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 Mp({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())}})}};l(pc,"Name","Debug"),l(pc,"autoStart",!0);var el=pc;var ZE=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},tl=class{constructor(t,e,r){l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"type","auto");l(this,"config");l(this,"decoder");l(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=be(e,le.INIT),this.stopOB=vt(),this.startOB=vt(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=vt(),a=u=>{let m=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),Ae(m,ze(this.stopOB),Le(()=>{},p=>{e.log.error(p),o.addFailedEvent({key:ZE(this.type),error:p}),u>4?this.startOB.error(p):this.startOB.next(u+1)})),Ae(m,Hr(1),Yh(tc))};Ae(this.startOB,Ka(0),go(a),ze(this.stopOB),Le(()=>{e.player.setOutput(),n.next("STARTED")},u=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:ZE(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 Pi()(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"}))}},pA={type:"object"},fc=class fc{constructor(t){this.core=t;l(this,"log");l(this,"contextMap",new Map);l(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return fc.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return fc.Name}getValidateRule(t){return pA}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 tl(this.core,r,t);return Ae(o.trackDoneOB,Hr(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 tl(this.core,t.track,t))}}};l(fc,"Name","TRTCAudioDecoder");var gc=fc;var rl=class{constructor(){l(this,"log");this.log=F.createLogger({id:"exp"})}call(t,e){return y(this,null,function*(){return je(this[t])?this[t](e):Promise.reject(new de({code:q.INVALID_PARAMETER,message:$e({key:Fe.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:a}=t,{audioManager:u}=e.room,{getPCMAbortCtrlMap:m,audioFrameEventConfigMap:p}=u;if(p.set(o,{enable:r,sampleRate:s,channelCount:n,port:a}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isAvailable){if(m.get(g.userId))return;let E=u.getPCM(A=>{e.emit(K.AUDIO_FRAME,A)},g.userId);m.set(g.userId,E)}});else{if(m.get(o))return;let g=u.getPCM(E=>{e.emit(K.AUDIO_FRAME,E)},o);m.set(o,g)}else if(o==="*")e.room.remotePublishedUserMap.forEach(g=>{if(g.remoteAudioTrack.isSubscribed){let{userId:E}=g,A=m.get(E);A==null||A.abort("disable"),m.delete(E)}});else{let g=m.get(o);g==null||g.abort("disable"),m.delete(o)}})}resumeRemotePlayer(t){return y(this,null,function*(){if(t.userId==="*"){let r=[];return t.trtcInstance.room.remotePublishedUserMap.forEach(o=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=o;t.streamType?t.streamType==="main"?(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume())):a.isAvailable&&r.push(a.player.resume()):(s.isAvailable&&r.push(s.player.resume()),n.isAvailable&&r.push(n.player.resume()),a.isAvailable&&r.push(a.player.resume()))}),Promise.all(r)}let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);if(e)return t.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(t){if(t.userId==="*")t.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:r,remoteVideoTrack:o,remoteAuxiliaryTrack:s}=e;t.streamType?t.streamType==="main"?(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause()):s.isAvailable&&s.player.pause():(r.isAvailable&&r.player.pause(),o.isAvailable&&o.player.pause(),s.isAvailable&&s.player.pause())});else{let e=t.trtcInstance.room.remotePublishedUserMap.get(t.userId);e&&(t.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause()):e.remoteAuxiliaryTrack.player.pause())}}};te([EE({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"}}})],rl.prototype,"enableAudioFrameEvent",1);var KE=new rl;var e_=pi(bi(),1);var Op=class extends e_.EventEmitter{constructor(){super();l(this,"states",{});l(this,"permissionChangeHandler");l(this,"log");this.log=F.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,r;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(r=this.states.microphone)==null?void 0:r.state})}}request(e){return y(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(o=>o.stop())})}get(e){return y(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(r){return this.log.error(`get ${e} permission failed, error: ${r instanceof Error?r.message:r}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Ec=new Op;var t_=0,_c=new Set,Ot=null;Ol(Ip);mn.checkStorage();var Ie=class Ie extends r_.EventEmitter{constructor(e,r){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioVolumeMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",F.createLogger({id:`t${++t_}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"enterRoomParams");l(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(X({logger:this._log,frameWorkType:Ie.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,Qe(r.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=r.enableAutoSwitchWhenRecapturing),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(Xu,r.assetsPath),this._use(zu,r.assetsPath),this._use(Yu,r.assetsPath),this._use(gc,r.assetsPath),this._use(el),r.enableSEI&&La&&this._use(Zu),this._room.on("audio-volume",o=>{var s,n;!o.find(a=>a.userId==="")&&this._localAudioTrack&&o.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()}),r.volumeType===1&&o.forEach(a=>{var m;let u=a.userId===""?this._localAudioTrack:(m=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:m.remoteAudioTrack;u&&(a.volume=u.dbVolume)}),r.enableDbVolume&&o.forEach(a=>{var m;let u=a.userId===""?this._localAudioTrack:(m=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:m.remoteAudioTrack;u&&(a.volume=u.dbVolume)}),this.emit(K.AUDIO_VOLUME,{result:o.sort((a,u)=>u.volume-a.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new oe({code:se.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),GE(this,"trtc")}static create(e){}static _create(e,r){DE();let o=new Ie(e,r||{});return _c.add(o),o.__v_skip=!0,o}get room(){return this._room}_listenEvents(){Rt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(K.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(K.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(K.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(K.ERROR,oe.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(K.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=ge(X({},e),{uplinkRTT:Math.min(e.uplinkRTT,ia),downlinkRTT:Math.min(e.downlinkRTT,ia)});this.emit(K.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Rt(o,o).add("player-state-changed",s=>{let n=ge(X({},s),{userId:e.userId});o.kind===O.VIDEO&&(n.streamType=si(o.streamType)),this.emit(o.kind===O.AUDIO?K.AUDIO_PLAY_STATE_CHANGED:K.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(K.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{mt(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:u}=r;a||this._remoteAudioConfigMap.delete(o),u||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==u&&(u?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(u?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(a?K.REMOTE_AUDIO_AVAILABLE:K.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(K.SEI_MESSAGE,ge(X({},e),{streamType:si(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(K.ERROR,new oe({code:se.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,u,m,p,g;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,ia),upLoss:((u=this._networkQuality)==null?void 0:u.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:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_level)||0)/Ci},video:e.msg_up_stream_info.msg_video_status.filter(E=>r[E.uint32_video_stream_type]).map(E=>({bitrate:(E.uint32_video_codec_bitrate||0)/1e3,width:E.uint32_video_width,height:E.uint32_video_height,frameRate:E.uint32_video_enc_fps,videoType:r[E.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(E=>({userId:E.msg_user_info.str_identifier,audio:{bitrate:(E.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(E.msg_audio_status.uint32_audio_level||0)/Ci,point2pointDelay:(E.msg_audio_status.uint32_audio_p2p_delay||0)+(E.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:E.msg_audio_status.uint32_audio_cache_ms||0},video:E.msg_video_status.map(A=>({bitrate:(A.uint32_video_codec_bitrate||0)/1e3,width:A.uint32_video_width,height:A.uint32_video_height,frameRate:A.uint32_video_dec_fps,videoType:r[A.uint32_video_stream_type],point2pointDelay:(A.uint32_video_p2p_delay||0)+(A.uint32_video_cache_ms||0),jitterBufferDelay:A.uint32_video_cache_ms||0,codec:A.uint32_video_codec}))}))};this.emit(K.STATISTICS,o)}).add("custom-message",e=>{this.emit(K.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(K.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(K.FIRST_VIDEO_FRAME,ge(X({},e),{streamType:si(e.streamType)}))}).add("audio-frame",e=>{this.emit(K.AUDIO_FRAME,e)}),Rt(this,ot).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=>y(this,null,function*(){if(this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ot&&Ot.deviceId===ra){let r=(yield mo()).find(o=>o.deviceId===ra);r&&Ot.groupId!==r.groupId&&(Ot=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>y(this,null,function*(){this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield mo())[0];if(!r||!Ot||Ot.groupId===r.groupId)return;let o=Ot.deviceId===e.deviceId,s=Ot.deviceId===ra&&Ot.deviceId===r.deviceId;(o||s)&&(Ot=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))})),Rt(this,Ec).add("permission-state-change",e=>{this.emit(K.PERMISSION_STATE_CHANGE,e)})}getNetworkTime(){return fi()}use(e){let r,o;return"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,r.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(r,o)}_use(e,r){let o=this._plugins.get(e.Name);if(o)return this._log.warn("duplicate install plugin",e.Name),o;let s=new e(WE.call(this,{TRTC:Ie,room:this._room,assetsPath:r,errorModule:{RtcError:oe,ErrorCode:se,CoreErrorCode:q,ErrorCodeDictionary:mr}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return y(this,null,function*(){var u,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),!Ne(e.proxy)&&e.proxy.turnServer&&((m=(u=this._room).setTurnServer)==null||m.call(u,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,Qe(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,r,Ie.frameWorkType),this._checkTrackToPublish(),vp.start()})}exitRoom(){return y(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return y(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(r){if(r instanceof Yn&&(r.code===q.API_CALL_TIMEOUT||r.code===q.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${r.code===q.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw r}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return y(this,null,function*(){yield this.exitRoom();let r=X(X({},this.enterRoomParams),e);yield this.enterRoom(r)})}_clearRemoteTracks(){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(),jE(this),this._room.remotePublishedUserMap.forEach(e=>{mt(e.remoteAudioTrack),mt(e.remoteVideoTrack),mt(e.remoteAuxiliaryTrack)})}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(){this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),mt(this),this.removeAllListeners(),this._room.destroy(),_c.delete(this),_c.size===0&&vp.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),U.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 ri(this._room.audioManager),a={},u={muted:!0};s&&(M(s.microphoneId)?M(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&ke(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),M(s.profile)||(Ne(s.profile)?qc[s.profile]&&n.setProfile(qc[s.profile]):n.setProfile(s.profile)),ke(s.earMonitorVolume)&&(u.muted=!(s.earMonitorVolume>0),u.volume=s.earMonitorVolume),M(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),M(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),M(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),Qe(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",m=>{this.emit(K.ERROR,new oe({code:se.DEVICE_ERROR,extraCode:5309,messageParams:{error:m}}))}),n.on("2",m=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"active",device:m})}),n.on("4",m=>{let p;m.error&&(p=oe.convertFrom(m.error)),this.emit(K.PUBLISH_STATE_CHANGED,ge(X({},m),{error:p}))}),n.on("6",()=>{this.emit(K.ERROR,new oe({code:se.OPERATION_FAILED,extraCode:5506,message:"audio encode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),M(o)||n.setMute(o),Rt(n,n).add("player-state-changed",m=>{this.emit(K.AUDIO_PLAY_STATE_CHANGED,ge(X({},m),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=ge(X({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:u,track:n}),U.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):M(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),M(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),M(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!M(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),M(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),xr(this._localAudioConfig,e)})}stopLocalAudio(){return y(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),U.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),mt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return y(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var g;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,capture:s=!0,mute:n,option:a}=e,u=new lr(this._room.videoManager),m={},p={};a&&(Qe(a.avoidCropping)&&(u.avoidCropping=a.avoidCropping),a.cameraId?m.deviceId=a.cameraId:M(a.useFrontCamera)?M(a.videoTrack)||(m.customSource=a.videoTrack):m.facingMode=a.useFrontCamera?O.FACING_MODE_USER:O.FACING_MODE_ENVIRONMENT,M(a.retryWhenExactFailed)||(m.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(m.contentHint=uc(a.qosPreference)),M(a.profile)||(Ne(a.profile)?Mr[a.profile]&&u.setProfile(Mr[a.profile]):u.setProfile(a.profile)),M(a.fillMode)||(p.objectFit=a.fillMode),M(a.mirror)||(p.mirror=a.mirror),M(a.small)||(M(a.smallMode)||(this._room.smallMode=a.smallMode),Qe(a.small)&&a.small===!1?u.stopSmall():u.updateSmallConfig(wn(a.small,!0))),M(a.rotation)||u.setRotation(a.rotation),Qe(this._enableAutoSwitchWhenRecapturing)&&(u.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),u.once("first-video-frame",E=>{this.emit(K.FIRST_VIDEO_FRAME,ge(X({},E),{streamType:si(E.streamType)}))}),u.on("5",E=>{this.emit(K.ERROR,new oe({code:se.DEVICE_ERROR,extraCode:5308,messageParams:{error:E}}))}),u.on("2",E=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"active",device:E})}),u.on("4",E=>{let A;E.error&&(A=oe.convertFrom(E.error)),this.emit(K.PUBLISH_STATE_CHANGED,ge(X({},E),{error:A}))}),u.on("6",()=>{this.emit(K.ERROR,new oe({code:se.OPERATION_FAILED,extraCode:5505,message:"video encode failed"}))}),this._listenOutputTrackChanged(u),s?yield u.capture(m):(g=u.manager)==null||g.changeInput(u),M(n)||(yield u.setMute(n)),Rt(u,u).add("player-state-changed",E=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,ge(X({},E),{userId:"",streamType:"main"}))}).add("video-size-changed",E=>{this.emit(K.VIDEO_SIZE_CHANGED,ge(X({},E),{streamType:si(E.streamType)}))}),o&&this._room.isJoined&&this._room.publish(u).catch(()=>{}),this._localVideoTrack=u,this._localVideoConfig=ge(X({},e),{view:r,publish:o,capture:s}),yield this._updateVideoPlayOption({view:r,playOption:p,track:u})})}updateLocalVideo(e){return y(this,null,function*(){var m,p,g;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,capture:n,option:a}=e,u={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):M(a==null?void 0:a.useFrontCamera)?M(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?O.FACING_MODE_USER:O.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let E={};E.deviceId=(a==null?void 0:a.cameraId)||((m=this._localVideoConfig.option)==null?void 0:m.cameraId),E.facingMode=a!=null&&a.useFrontCamera||(p=this._localVideoConfig.option)!=null&&p.useFrontCamera?O.FACING_MODE_USER:O.FACING_MODE_ENVIRONMENT,E.customSource=(a==null?void 0:a.videoTrack)||((g=this._localVideoConfig.option)==null?void 0:g.videoTrack),yield this._localVideoTrack.capture(E)}a&&(M(a.profile)||(Ne(a.profile)?Mr[a.profile]&&this._localVideoTrack.setProfile(Mr[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&M(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),M(a.fillMode)||(u.objectFit=a.fillMode),M(a.mirror)||(u.mirror=a.mirror),M(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(uc(a.qosPreference)),M(a.small)||(Qe(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(wn(a.small,!0)))),this._room.isJoined&&M(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(()=>{})),M(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:u,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),xr(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(),mt(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return y(this,arguments,function*(e={publish:!0,view:null}){var E,A;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,muteSystemAudio:s,option:n}=e,a=new ii(this._room.videoManager);a.on("4",C=>{let N;C.error&&(N=oe.convertFrom(C.error)),this.emit(K.PUBLISH_STATE_CHANGED,ge(X({},C),{error:N}))}),a.once("first-video-frame",C=>{this.emit(K.FIRST_VIDEO_FRAME,ge(X({},C),{streamType:si(C.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let u=null,m={},p={};n&&(M(n.profile)||(Ne(n.profile)?zc[n.profile]&&a.setProfile(zc[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(m.systemAudio=!0,m.echoCancellation=n.echoCancellation,m.noiseSuppression=n.noiseSuppression,m.autoGainControl=n.autoGainControl),M(n.fillMode)||(p.objectFit=n.fillMode),n.videoTrack&&(m.videoTrack=n.videoTrack),n.audioTrack&&(m.audioTrack=n.audioTrack),n.captureElement&&(m.captureElement=n.captureElement),n.preferDisplaySurface&&(m.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(m.contentHint=uc(n.qosPreference)));let g=yield a.capture(m);if(a.mediaTrack.addEventListener(O.ENDED,()=>{this._stopScreenShare(),this.emit(K.SCREEN_SHARE_STOPPED)}),g.getAudioTracks()[0]){u=new Ss(this._room.audioManager);let C=g.getAudioTracks()[0];(E=e.option)!=null&&E.systemAudio&&!((A=e.option)!=null&&A.audioTrack)&&(u.sourceTrack=C),yield u.setInputMediaStreamTrack(C),Qe(s)&&u.mediaTrack&&(u.mediaTrack.enabled=!s),this._speakerId&&u.setAudioOutput(this._speakerId)}if(Rt(a,a).add("player-state-changed",C=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,ge(X({},C),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let C=[a];u&&(C.push(u),this._checkScreenAudioEchoCancellation(a,u)),this._room.publish(...C).catch(()=>{})}this._localScreenTrack=a,this._localScreenAudioTrack=u,this._localScreenConfig=ge(X({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:p,track:a})})}updateScreenShare(e){return y(this,null,function*(){var u;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,muteSystemAudio:s,option:n}=e,a={};if(n&&(M(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let m=uc(n.qosPreference);this._localScreenTrack.setContentHint(m)}if(this._room.isJoined&&!M(o)){if(o&&!this._localScreenConfig.publish){let m=[this._localScreenTrack];this._localScreenAudioTrack&&m.push(this._localScreenAudioTrack),this._room.publish(...m).catch(()=>{})}if(this._localScreenConfig.publish&&!o){let m=[this._localScreenTrack];this._localScreenAudioTrack&&m.push(this._localScreenAudioTrack),this._room.unpublish(...m).catch(()=>{})}}(u=this._localScreenAudioTrack)!=null&&u.mediaTrack&&Qe(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),xr(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,a=`${o}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let u=this._room.remotePublishedUserMap.get(o);if(!u)return;let m={},p=s==="main"?u.remoteVideoTrack:u.remoteAuxiliaryTrack;p.on("decode-failed",g=>{this.emit(K.ERROR,new oe({code:se.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),p.on("video-size-changed",g=>{this.emit(K.VIDEO_SIZE_CHANGED,ge(X({},g),{streamType:si(g.streamType)}))}),this._listenOutputTrackChanged(p),n&&(M(n.fillMode)||(m.objectFit=n.fillMode),M(n.mirror)||(m.mirror=n.mirror),M(n.poster)||(m.poster=n.poster),m.canvasRender=n.canvasRender,s==="main"&&!M(n.small)&&(!u.remoteVideoTrack.isSubscribing&&!u.remoteVideoTrack.isSubscribed&&u.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,p.user))),yield this._room.subscribe(p),yield this._enableVideoDecodeFallback(p,s),yield this._updateVideoPlayOption({view:r,playOption:m,track:p}),this._emitTrackEvent(p),this._remoteVideoConfigMap.set(a,{config:e}),n&&!M(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:p,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return y(this,null,function*(){var D,x;let{view:r,userId:o,streamType:s,option:n}=e,a=`${o}_${s}`,u=this._remoteVideoConfigMap.get(a);if(!u||!this._room.remotePublishedUserMap.has(o))return;let m={};n&&(M(n.fillMode)||(m.objectFit=n.fillMode),M(n.mirror)||(m.mirror=n.mirror));let p=null,g=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(g!=null&&g.muteState.hasVideo)&&(p=g.remoteVideoTrack),s==="sub"&&(g!=null&&g.muteState.hasAuxiliary)&&(p=g.remoteAuxiliaryTrack),!p)return;let{config:E}=u;s==="main"&&n&&!M(n.small)&&this._room.changeType(n.small,p.user),yield this._updateVideoPlayOption({view:r,playOption:m,track:p,prevConfig:E}),xr(E,e);let A=M(n==null?void 0:n.receiveWhenViewVisible)?(D=E.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,C=M(r)?E.view:r,N=M(n==null?void 0:n.viewRoot)?(x=E.option)==null?void 0:x.viewRoot:n.viewRoot;this._observeView({remoteTrack:p,view:C,receiveWhenViewVisible:A,viewRoot:N})})}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:a,remoteAuxiliaryTrack:u}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&o.push(a)),e.streamType==="sub"&&(u.stop(),n.hasAuxiliary&&o.push(u))}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 o.code!==se.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){this._remoteAudioVolumeMap.set("*",r),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,r));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(K.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{$E.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===Ie.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(Ie.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(Ne(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let a=this._room.remotePublishedUserMap.get(r);a&&(o=a.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 a=this._room.remotePublishedUserMap.get(r);a&&(n=o==="main"?a.remoteVideoTrack:a.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 mo()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Ot=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*(){var a;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;n.on("decode-failed",u=>{this.emit(K.ERROR,new oe({code:se.OPERATION_FAILED,extraCode:5506,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let u=(a=this._remoteAudioVolumeMap.get(r))!=null?a:this._remoteAudioVolumeMap.get("*"),m=ke(u)?u:100;s.volume=m,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),Ae(be(n,"decode-failed"),ze(be(n,le.INIT)),Le(()=>{this.startPlugin(gc.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),U.emit("115",{userId:r,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${r}`})}catch(u){throw this._remoteAudioConfigMap.delete(r),u}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}`),U.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;Ae(be(e,"decode-failed"),ze(be(e,le.INIT)),rc(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),ki(be(e,"decode-downgrade-state-changed")),Le(n=>{s=n.state,this.emit(K.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,ge(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),M(e)&&s&&s.view&&!zs(r)){let a=Xs(s.view);a.length>0&&(yield o.play(a,r))}if(!M(e)){let a=Xs(e);a.length>0?yield o.play(a,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(M(e.muted)||r.setPlayerMute(e.muted),M(e.volume)||r.setAudioVolume(e.volume/100),r instanceof ri&&r.mediaTrack){let n=e.muted===!1&&!M(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:r.mediaTrack,refId:"em"})}else if(r instanceof Li){let n=e.muted?0:e.volume;if(M(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(K.TRACK,{userId:o,streamType:si(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(M(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${si(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(r===null||at(r)&&r.length===0||!o){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let m=n.visibleViewMap||new Map,p=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),m.clear(),a=new IntersectionObserver(E=>{E.forEach(A=>{m.set(A.target,A.isIntersecting),e.log.info(`view ${A.target.id} is${A.isIntersecting?"":" not"} visible`)}),clearTimeout(p),p=window.setTimeout(()=>{[...m.values()].find(C=>C)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let g=new Set(Xs(r));m.forEach((E,A)=>{g.has(A)||(a.unobserve(A),m.delete(A))}),g.forEach(E=>{m.set(E,!0),a.observe(E)}),a.takeRecords().forEach(E=>{m.set(E.target,E.isIntersecting)}),n.visibleViewMap=m,n.observer=a}_exitRoom(){return y(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_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),mt(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(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ot||In(Ot))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return y(this,null,function*(){if(Ot&&!In(Ot))this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ot});else{let e=yield mo();e[0]&&!In(e[0])?(Ot=e[0],this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):U.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:ge(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)})`),KE.call(e,X({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),M(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return qd(Ie.frameWorkType)}static getPermissions(o){return y(this,arguments,function*({request:e=!0,types:r=["camera","microphone"]}){e&&(yield Ec.request(r).catch(a=>{var u;return F.error(`getPermissions request failed, error: ${(u=a==null?void 0:a.message)!=null?u:a}`)}));let[s,n]=yield Promise.all([Ec.get("camera"),Ec.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return ir(e)}static getMicrophoneList(e=!0){return rr(e)}static getSpeakerList(e=!0){return mo(e)}static setCurrentSpeaker(e){return y(this,null,function*(){if(it&&(e===ys.SPEAKER||e===ys.HEADSET)){let o=yield Ie.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;_c.forEach(n=>y(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield mo()).forEach(o=>{o.deviceId===e&&(_c.forEach(s=>{s._setCurrentSpeaker(e),s.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Ot=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:a,max:u}){switch(a&&(ss.version=a),e){case"count":ss.addCount({key:r,useUV:n});break;case"enum":ss.addEnum({key:r,value:o,useUV:n});break;case"number":ss.addNumber({key:r,value:o,split:s,max:u});break}}};l(Ie,"VERSION",Ip),l(Ie,"_loggerManager",F),l(Ie,"EVENT",K),l(Ie,"ERROR_CODE",se),l(Ie,"TYPE",ys),l(Ie,"frameWorkType",30),te([rt({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"}})})],Ie.prototype,"use",1),te([Vt(Nt.TRTC.enterRoom),yo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),rt()],Ie.prototype,"enterRoom",1),te([rt()],Ie.prototype,"exitRoom",1),te([Vt(Nt.TRTC.switchRoom),rt(),us()],Ie.prototype,"switchRoom",1),te([Vt(Nt.TRTC.switchRole),bs("room",{merge:(e,r)=>r}),rt()],Ie.prototype,"switchRole",1),te([rt()],Ie.prototype,"destroy",1),te([Vt(Nt.TRTC.startLocalAudio),yo("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)}),rt()],Ie.prototype,"startLocalAudio",1),te([Vt(Nt.TRTC.updateLocalAudio),bs("audio",{debounce:{delay:200,getKey:()=>`${t_}-localAudio`,isNeedToDebounce:e=>{var r;return!M((r=e.option)==null?void 0:r.captureVolume)}}}),rt()],Ie.prototype,"updateLocalAudio",1),te([Ao("audio"),rt()],Ie.prototype,"stopLocalAudio",1),te([Vt(Nt.TRTC.startLocalVideo),yo("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)}),rt()],Ie.prototype,"startLocalVideo",1),te([Vt(Nt.TRTC.updateLocalVideo),bs("video"),rt()],Ie.prototype,"updateLocalVideo",1),te([Ao("video"),rt()],Ie.prototype,"stopLocalVideo",1),te([Vt(Nt.TRTC.startScreenShare),yo("screen",()=>!0),rt()],Ie.prototype,"startScreenShare",1),te([Vt(Nt.TRTC.updateScreenShare),bs("screen"),rt()],Ie.prototype,"updateScreenShare",1),te([rt()],Ie.prototype,"stopScreenShare",1),te([Vt(Nt.TRTC.startRemoteVideo),yo(e=>`v${e.userId}${e.streamType}`,()=>!0),rt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"startRemoteVideo",1),te([Vt(Nt.TRTC.updateRemoteVideo),bs(e=>`v${e.userId}${e.streamType}`),rt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"updateRemoteVideo",1),te([Vt(Nt.TRTC.stopRemoteVideo),Me(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)})}),rt({getRemoteId:e=>`${e.userId}_${e.streamType}`})],Ie.prototype,"stopRemoteVideo",1),te([Ao(e=>`v${e.userId}${e.streamType}`)],Ie.prototype,"_stopRemoteVideo",1),te([Vt(...Nt.TRTC.muteRemoteAudio),rt({getRemoteId:e=>e})],Ie.prototype,"muteRemoteAudio",1),te([Sp(...Nt.TRTC.setRemoteAudioVolume),qE(200,e=>e),rt({getRemoteId:e=>e})],Ie.prototype,"setRemoteAudioVolume",1),te([ju("start"),ho(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),yo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),rt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Um[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],Ie.prototype,"startPlugin",1),te([ju("update"),bs((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r),{merge:(e,r)=>(xr(e[1],r[1]),e)}),rt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Vm[e.getName()]})],Ie.prototype,"updatePlugin",1),te([ju("stop"),Ao((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),rt({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Fm[e.getName()]})],Ie.prototype,"stopPlugin",1),te([Sp(...Nt.TRTC.enableAudioVolumeEvaluation)],Ie.prototype,"enableAudioVolumeEvaluation",1),te([rt()],Ie.prototype,"getVideoSnapshot",1),te([rt()],Ie.prototype,"_setCurrentSpeaker",1),te([yo(e=>`a${e.userId}`,()=>!0)],Ie.prototype,"_startRemoteAudio",1),te([Me(e=>function(r){return y(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(ge(X({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),Ao(e=>`a${e.userId}`)],Ie.prototype,"_stopRemoteAudio",1),te([Ao("room")],Ie.prototype,"_exitRoom",1),te([Ao("screen")],Ie.prototype,"_stopScreenShare",1),te([Vt(...Nt.TRTC.sendSEIMessage),fp({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],Ie.prototype,"sendSEIMessage",1),te([Vt(Nt.TRTC.sendCustomMessage),fp({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],Ie.prototype,"sendCustomMessage",1),te([Vt(Nt.TRTC.create)],Ie,"_create",1);var xp=Ie,kn=xp;var il=class{constructor(t,e){l(this,"_flag");l(this,"terminalType");l(this,"userId");l(this,"tinyId");l(this,"role");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new Li(t,this),this.remoteVideoTrack=new To(t,this),this.remoteAuxiliaryTrack=new Du(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 qo(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 Pp=class{constructor(){l(this,"_set",new Set);U.on($.LEAVE_SUCCESS,this.delete,this),U.on($.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 fA(){return y(this,null,function*(){let i,t;try{let A=yield rr();i=A&&A.length}catch(A){}try{let A=yield ir();t=A&&A.length}catch(A){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:u}=this.checkSystemResult.detail,m=uo.basis(),p={webRTC:m.isWebRTCSupported,getUserMedia:m.isGetUserMediaSupported,webSocket:m.isWebSocketsSupported,screenShare:m.isScreenShareSupported,webAudio:m.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n,h265Encode:a,h265Decode:u},g={browser:m.browser,os:m.os,trtc:p,devices:e},E={isWebCodecSupported:m.isWebCodecSupported,isMediaSessionSupported:m.isMediaSessionSupported,isWebTransportSupported:m.isWebTransportSupported};We.uploadEvent({log:`trtcstats-${JSON.stringify(g)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(g)}`),We.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(E)}`,userId:this.userId}),Qm()})}function i_(){return Me(i=>{let t=new Pp;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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new de({code:q.INVALID_OPERATION,message:$e({key:Fe.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),U.emit($.JOIN_START,{room:this,roomId:s,params:e});let n=Zr.getEnv();n||(n=gi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Jc.OLD_CLOUD_LADDER)?n=gi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Jc.WEBRTC)&&(n=gi.WEBRTC))),We.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),uo.checkSystemRequirementsInternal(o).then(a=>{this.checkSystemResult=a,fA.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Zr.getEnv()&&(yield this.schedule(e,o));let a=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Zr.performanceNow(),U.emit($.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&We.uploadEvent({log:`stat-conv-${Number(Ur)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw t.delete({room:this,roomId:s}),U.emit($.JOIN_FAILED,{room:this,error:a}),a}})}})}var o_=()=>Me(i=>function(...t){return y(this,null,function*(){U.emit($.LEAVE_START,{room:this}),yield i.call(this,...t),U.emit($.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function s_(){return Me(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;U.emit("61",{room:this});let e=i.apply(this,t);return Promise.all(t.map(r=>r.publish(this,e)))})})}function n_(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function a_(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function gA({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return ro(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var ol=class{constructor(t){l(this,"_frameWorkType");l(this,"_component");l(this,"_language");l(this,"connectionType");l(this,"_room");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0});l(this,"_keyPrefix");l(this,"_log");l(this,"_intervalId");l(this,"_firstPublishedUserList");l(this,"_networkQuality");l(this,"_basicInfo");l(this,"_pathJoinRoom");l(this,"_pathLeaveRoom");l(this,"_pathMainVideoMap");l(this,"_pathMainAudioMap");l(this,"_pathAuxiliaryMap");l(this,"_remoteStreamStatMap");l(this,"_localStreamStat");l(this,"_eventMap",new Map);l(this,"_captureCostSum",0);l(this,"_captureCostCount",0);l(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=F.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&je(this[e])&&(this[e]=gA({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:dt,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,Yo().then(()=>{this._basicInfo.string_os_version=es(),this._basicInfo.string_device_name=Zo()||this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),U.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($.JOIN_START,this.handleJoinStart).addEvent($.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent($.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent($.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent($.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent($.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent($.JOIN_SUCCESS,this.handleJoinSuccess).addEvent($.JOIN_FAILED,this.handleJoinFailed).addEvent($.LEAVE_START,this.handleLeaveStart).addEvent($.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent($.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent($.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent($.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent($.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent($.PUBLISH_START,this.handlePublishStart).addEvent($.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent($.SUBSCRIBE_START,this.handleSubscribeStart).addEvent($.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent($.PLAY_TRACK_START,this.handlePlayStart).addEvent($.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent($.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===O.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent($.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent($.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent($.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent($.NETWORK_QUALITY,this.handleNetworkQuality).addEvent($.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent($.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent($.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,a=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent($.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)=>U.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),lt.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&&(M(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),M(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),M(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:a,request:u,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=a,this._pathJoinRoom.int32_schedule_request=u,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 de?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 de?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:ge(X({},EA),{msg_user_info:new Tc({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:a}=e,u=new Tc({userId:s,tinyId:n,role:a==="anchor"?20:21}),m=Date.now(),p=`${s}_${r}`,g=this._remoteStreamStatMap.get(p);g&&g.subscribeStartTime===0&&(g.subscribeStartTime=m),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(p)&&this._pathMainVideoMap.set(p,{statsToReport:{msg_user_info:u,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(p)&&this._pathMainAudioMap.set(p,{statsToReport:{msg_user_info:u,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(p)&&this._pathAuxiliaryMap.set(p,{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 a=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,Q.addNumber({key:516820,value:a})}}(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 a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a)a.totalRTT+=e,a.totalLoss+=r,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 u,m,p,g;s&&(m=s,p=1),n&&(u=n,g=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:u,totalVideoDelay:m,audioDelayCount:g,videoDelayCount:p})}}))}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:a,uint32_video_height:u}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=u,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/Ci*100)>0&&(this._localStreamStat.totalAudioLevel+=s/Ci,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:u}=s,m=n.str_identifier,p=this._room.remotePublishedUserMap.get(m);if(u.forEach(g=>{let E=g.uint32_video_stream_type===2,A=g.uint32_video_stream_type===7,C=`${m}_${E?"main":"auxiliary"}`,N=this._remoteStreamStatMap.get(C);if(N&&(E&&(p!=null&&p.remoteVideoTrack.isSubscribed)||A&&(p!=null&&p.remoteAuxiliaryTrack))){N.totalVideoFPS+=g.uint32_video_receive_fps,N.totalVideoBitrate+=g.uint32_video_codec_bitrate,N.videoCount++,N.statsToReport.uint32_video_width===0&&(N.statsToReport.uint32_video_width=g.uint32_video_width),N.statsToReport.uint32_video_height===0&&(N.statsToReport.uint32_video_height=g.uint32_video_height);let D=E?p.remoteVideoTrack:p.remoteAuxiliaryTrack;D.stat.jitterBufferDelay&&(N.videoJitterBufferDelay=D.stat.jitterBufferDelay),D.stat.framesReceived&&(N.statsToReport.uint32_video_consume_render_rate=Math.floor(D.stat.framesDecoded/D.stat.framesReceived*eo(10,6)))}}),!zs(a)){let g=`${m}_main`,E=this._remoteStreamStatMap.get(g);this._remoteStreamStatMap.has(g)&&E&&p!=null&&p.remoteAudioTrack.isSubscribed&&(E.totalAudioBitrate+=a.uint32_audio_codec_bitrate,E.audioCount++,p.remoteAudioTrack.stat.jitterBufferDelay&&(E.audioJitterBufferDelay=p.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/Ci*100)>0&&(E.totalAudioLevel+=a.uint32_audio_level/Ci,E.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 de?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&$s)>=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&ta)>=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:p,count:g,audioDelayCount:E,videoDelayCount:A,totalAudioDelay:C,totalVideoDelay:N}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(p/g),E&&C&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(C/E),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),A&&N&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(N/A))}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,O.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,O.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,vs));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:u}=n.getDataFreezeDuration(e),{renderFreeze:m}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=u,t.statsToReport.uint32_video_block_time=Math.min(a,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>vs&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+vs)}),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>vs&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+vs)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>vs&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+vs)}getReportData(){this._basicInfo.uint32_networkType=id();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Tc({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Js(this._signalInfo.relayIp),uint32_client_ip:Js(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*eo(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:Js(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return ua(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=no.enable?Ii(t,2001,e):yield em(t),o=r instanceof ArrayBuffer,s=`${Ti(e,to.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let a=[this.uploadKVStat(Q),this.uploadKVStat(ss)];n||a.push(Si({url:s,body:r,priority:"low"})),yield Promise.all(a)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return y(this,null,function*(){let e=t.getReportData(this._room.userSig,this._signalInfo.reportToken);if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=ge(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=no.enable?Ii(e,2003,this._room.sdkAppId):yield em(e),o=r instanceof ArrayBuffer,s=`${Ti(+this._room.sdkAppId,to.KV_STAT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r)),n||Si({url:s,body:r})})}};te([cs({settings:{timeout:500,retries:3}})],ol.prototype,"upload",1);var vs=5e3,EA={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},Tc=class{constructor(t){l(this,"str_identifier");l(this,"str_tinyid");l(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},c_=ol;var kp=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Ee())}stop(){this._endTime===0&&(this._endTime=Ee())}getDuration(){return this._endTime===0?Ee()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},sl=kp;var Lp=class{constructor(t){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set($.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set($.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set($.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`,O.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,O.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,O.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,O.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,O.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,O.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 sl,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===O.AUDIO?[s]:[],video:e===O.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()}},d_=Lp;var Up=class{constructor(t){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);l(this,"_videoEncodeFailedCount",0);l(this,"_audioEncodeFailedCount",0);l(this,"_encodeFailedThreshold",3);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set($.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set($.PLAY_TRACK_START,this.onPlayTrackStart).set($.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($.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($.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==O.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===O.MUTE?this.onVideoTrackMuted(t):r===O.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set($.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>U.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>U.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 sl;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.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}){if(this.hitTest(t)){if(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(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"auxiliary"})})}),e.msg_up_stream_info.msg_video_status){let r=e.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="video"&&!n.isScreen),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0)return;r.forEach(n=>{n.uint32_video_stream_type===2&&(n.uint32_video_capture_fps!==0&&n.uint32_video_codec_bitrate===0&&n.uint32_video_enc_fps===0&&(o!=null&&o.isPublished)?(this._videoEncodeFailedCount+=1,this._videoEncodeFailedCount===this._encodeFailedThreshold&&(We.uploadEvent({userId:this._room.userId,log:`stat-${gr.VIDEO_ENCODE_FAILED_DURING_CALL}`}),this._videoEncodeFailedCount=0)):this._videoEncodeFailedCount=0)})}if(e.msg_up_stream_info.msg_audio_status){let r=e.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(n=>n.kind==="audio"),s=(o==null?void 0:o.stat.bytesSent)||0;if((o==null?void 0:o.isMediaTrackActive)===!1||s<=0)return;r.uint32_audio_codec_bitrate===0&&(o!=null&&o.isPublished)?(this._audioEncodeFailedCount+=1,this._audioEncodeFailedCount===this._encodeFailedThreshold&&(We.uploadEvent({userId:this._room.userId,log:`stat-${gr.AUDIO_ENCODE_FAILED_DURING_CALL}`}),this._audioEncodeFailedCount=0)):this._audioEncodeFailedCount=0}}}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>Yc?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 a=Ee();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,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=Ee();let u=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,u)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==O.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()<Yc&&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=Ee(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=s-n.startTime;r=e.renderFreezeTotal+Math.min(a,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()}},u_=Up;var h_=pi(bi(),1);var nl=class{constructor(t,e,r,o,s,n=4/3){this.vbMode=t;this.faceDetectorHash=r;this.visionTaskRegistry=o;this.logger=s;l(this,"animationState");l(this,"originalAspect");l(this,"totalOffsetX",0);l(this,"totalOffsetY",0);l(this,"defaultScaleRatio",.1);l(this,"isRecovering",!1);l(this,"boundaryY",280);l(this,"lastActionTime",0);l(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=n||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}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,a=n.originX,u=n.originY,m=n.width,p=n.height;this.vbMode===1?this.dualStageCropping(r,o,a,u,m,p):this.vbMode===2&&this.movingPortrait(r,o,a,u,m,p)}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,a=.4){let u=t+r/2,m=e+o/2,p,g,{min:E,offset:A}=this.calculateBoundary(u,s,t,r),{min:C,offset:N}=this.calculateBoundary(m,n,e,o);return p=2*E+r,g=2*C+o,p/g>this.originalAspect?(p=g*this.originalAspect,A=u-p/2):(g=p/this.originalAspect,N=m-g/2),r/s>a&&(A=0,N=0,p=s,g=n),A=Math.max(0,Math.min(A,s-p)),N=Math.max(0,Math.min(N,n-g)),{sx:A,sy:N,cropWidth:p,cropHeight:g,timestamp:Date.now()}}processFacePositionCrop(t,e,r){if(!this.animationState.current||!this.animationState.target){let a={sx:0,sy:0,cropWidth:e,cropHeight:r,timestamp:Date.now()};this.animationState.current=a,this.animationState.target=a;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 a=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*r(e);this.animationState.current.scaleOffsetY+=a}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(t,e){return Math.sqrt(eo(t.sx-e.sx,2)+eo(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,a=.3){if(this.isRecovering)return;let u=this.calculateTargetPosition(r,o,s,n,t,e);this.processFacePositionCrop(u,t,e),s*n/u.cropWidth/u.cropHeight>a&&this.recoverOriginal(t,e)}movingPortrait(t,e,r,o,s,n){var u,m,p,g,E,A,C,N,D,x,Z,ue;let a={sx:r+s/2+this.totalOffsetX,sy:o+n/2+this.totalOffsetY,cropWidth:t,cropHeight:e,scaleRatio:(m=(u=this.animationState.current)==null?void 0:u.scaleRatio)!=null?m:1,scaleOffsetX:(g=(p=this.animationState.current)==null?void 0:p.scaleOffsetX)!=null?g:0,scaleOffsetY:(A=(E=this.animationState.current)==null?void 0:E.scaleOffsetY)!=null?A:0,timestamp:Date.now()};this.animationState.target={sx:t/2,sy:o+n/2,cropWidth:t,cropHeight:e,scaleRatio:(N=(C=this.animationState.target)==null?void 0:C.scaleRatio)!=null?N:1,scaleOffsetX:(x=(D=this.animationState.target)==null?void 0:D.scaleOffsetX)!=null?x:0,scaleOffsetY:(ue=(Z=this.animationState.target)==null?void 0:Z.scaleOffsetY)!=null?ue: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(a)}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 _A=`#version 300 es
|
|
71
103
|
in vec2 a_position;
|
|
72
104
|
in vec2 a_texCoord;
|
|
73
105
|
out vec2 v_texCoord;
|
|
74
106
|
void main() {
|
|
75
107
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
76
108
|
v_texCoord = a_texCoord;
|
|
77
|
-
}`,
|
|
109
|
+
}`,TA=`#version 300 es
|
|
78
110
|
precision highp float;
|
|
79
111
|
uniform sampler2D u_texture;
|
|
80
112
|
uniform sampler2D mask;
|
|
@@ -83,7 +115,7 @@ in vec2 v_texCoord;
|
|
|
83
115
|
out vec4 outColor;
|
|
84
116
|
void main() {
|
|
85
117
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
86
|
-
}`,
|
|
118
|
+
}`,al=class extends yr{constructor(e,r){super(e,r.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:r.width,height:r.height,logger:e.log});l(this,"_bgTexture");l(this,"_waterMarkTexture");l(this,"_lastMaskTexture");l(this,"_lastMaskFbo");l(this,"_textureValid",!1);l(this,"_selfieTextureValid",!1);l(this,"_selfieSegmentationHash");l(this,"wasm");l(this,"predictReady");l(this,"_color");l(this,"_prePrograme");l(this,"_segmentationMask");l(this,"_weixin",!1);l(this,"_centerFace");l(this,"_textureMatrixLocation");l(this,"_offsetMatrixLocation");l(this,"_colorLocation");l(this,"_enableFaceCentering",!1);l(this,"_enableEffectOptimization",!1);l(this,"_mat4");l(this,"_postProcessing");l(this,"_onAbort");l(this,"_visionTaskRegistry");l(this,"resolvePreditReady");this.init(r).catch(o=>{e.log.error(o),e.destroy(new de({code:q.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${o.message||o}`})),this.resolvePreditReady()})}init(e){return y(this,null,function*(){var n,a,u;this.predictReady=new Promise(m=>{this.resolvePreditReady=m});let r=e.Wasm,o=this.context.ctx;if(e.color&&(this._color=e.color),e.mat4&&(this._mat4=e.mat4),e.postProcessing&&(this._postProcessing=e.postProcessing),this._enableFaceCentering=(n=e.enableFaceCentering)!=null?n:!1,this._enableEffectOptimization=(a=e.enableEffectOptimization)!=null?a:!1,this.wasm=new r.AllIn1(o),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==="color"?3:0,this._onAbort=e.onAbort,e.bg||this.resolvePreditReady(),e.waterMark){let{x:m,y:p,width:g,height:E}=e.waterMark;this.wasm.setWaterMark(m,p,g,E)}if(e.beautyParams){let{beauty:m,brightness:p,ruddy:g}=e.beautyParams;this.wasm.setBeauty(m,p,g,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),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image));let s=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=o.getUniformLocation(this.program,"u_textureMatrix"),o.uniformMatrix4fv(this._textureMatrixLocation,!1,s),this._offsetMatrixLocation=o.getUniformLocation(this.program,"u_offsetMatrix"),o.uniformMatrix4fv(this._offsetMatrixLocation,!1,s),this._colorLocation=o.getUniformLocation(this.program,"u_color"),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let m=this.context.createShader(o.FRAGMENT_SHADER,TA),p=this.context.createShader(o.VERTEX_SHADER,_A);this._prePrograme=this.context.createProgram(p,m),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}this._enableEffectOptimization&&(this.wasm.vbMode===2||this.wasm.vbMode===3)?Aa()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(u=this._postProcessing)==null||u.init(o,this.positionBuffer,this.texCoordBuffer,4/3):this._postProcessing=void 0,yield this.initVisionTasks(e)})}initVisionTasks(e){return y(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._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let r=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!r)return;this._centerFace=new nl(this.wasm.vbMode,this.image,r,this._visionTaskRegistry,this.context.log)}catch(r){this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(e){let r=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let o=this.getMaskTexture(e);if(!o)return;let s=o;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,s=this._postProcessing.postProcessing(o)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,s||null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&r.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=e,this.totalFrames++,this.centerFace(),cr(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),r.viewport(0,0,r.canvas.width,r.canvas.height),r.drawArrays(r.TRIANGLE_STRIP,0,4),e.close()}getMaskTexture(e){return e.confidenceMasks?e.confidenceMasks[0].getAsWebGLTexture():void 0}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 r=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=o;if(cr(this.wasm.rotation)&&!this._visionTaskRegistry&&([s,n]=[n,s]),s===0||n===0||!this.available)return!1;o.width=s,o.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}if(this.width!==s||this.height!==n||!a?(this.resize(s,n),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,o)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,o),this._weixin){if(r.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let u=this.getMaskTexture(this._segmentationMask);r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,u||null),r.bindFramebuffer(r.FRAMEBUFFER,this._lastMaskFbo||null)}r.drawArrays(r.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,0,0,s,n):r.copyTexImage2D(r.TEXTURE_2D,0,r.RGBA,0,0,s,n,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let u=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(u)}}catch(u){this._onAbort&&this._onAbort(u)}return this.totalFrames||(r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),r.drawArrays(r.TRIANGLE_STRIP,0,4)),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:r,offset:o}=this._centerFace;if(r&&(this.wasm.vbMode===1&&this.drawImage(r.sx,r.sy,r.cropWidth,r.cropHeight),o&&this.wasm.vbMode===2)){if(!this._mat4)return;let s=this._mat4.create(),{scaleRatio:n=1,scaleOffsetX:a=0,scaleOffsetY:u=0}=r;this._mat4.fromTranslation(s,[-o.offsetX/e.canvas.width+a,u,0]),this._mat4.scale(s,s,[n,n,1]),e.uniformMatrix4fv(this._offsetMatrixLocation,!1,s)}}drawImage(e,r,o,s){let n=this.context.ctx;if(!this._mat4)return;let{width:a,height:u}=n.canvas,m=this._mat4.create();this._mat4.fromTranslation(m,[e/a,1-(r+s)/u,0]),this._mat4.scale(m,m,[o/a,s/u,1]),n.uniformMatrix4fv(this._textureMatrixLocation,!1,m)}close(){var r;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(r=this.wasm)==null||r.close()}};var cl=class extends Ct{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
87
119
|
precision highp float;
|
|
88
120
|
uniform sampler2D ySampler;
|
|
89
121
|
uniform sampler2D uSampler;
|
|
@@ -108,15 +140,4 @@ void main() {
|
|
|
108
140
|
void main() {
|
|
109
141
|
gl_Position = vertexPos;
|
|
110
142
|
textureCoord = texturePos;
|
|
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 r_=(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 YS(o){return o[0]===0&&o[1]===0&&o[2]===0&&o[3]===1}var ZS=0,Ed=class{constructor(i){d(this,"id",ZS++);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=ct(),this.track=e,this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=ue(e.availableState,W.OFF),this.stopOB=ct(),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),le(this.stateChangeOB,Zu((r,s)=>(r!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:s}),s),"INITIALIZED"),Le(this.stopOB),Re()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=le(this.pipe(this.track),Le(this.stopOB),Yi());le(e,Re(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),v.addFailedEvent({key:r_(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED"),v.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`),v.addSuccessEvent({key:r_(this.type,this.renderer)}),v.addSuccessEvent({key:514704})})),le(e,Zi(1),Re(()=>{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"&&!sn()&&(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(!YS(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=P();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}(this.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(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":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 Pe({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(Pe.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let c=new Td(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 je({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 oo(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 o_=Promise.resolve(),zn=class extends s_.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,"_enableEffectOptimization",!1);d(this,"onAbort");d(this,"_color");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"mixTrack");d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",y.createLogger({id:"vm"}));d(this,"_mat4");d(this,"_postProcessing");d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"updated",o_);d(this,"_updateFlag",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new je({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get 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 It(this._rotation)?{width:t,height:e}:{width:e,height:t}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Pe({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(ml<=22),this._glVideoContext.on(Pe.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,r){this.onAbort=e,this._mat4=t,this._postProcessing=r}enablePrintDetail(e=2e3){this._checkId=ie.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(),ie.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ot||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?v.addFailedEvent({key:r,error:t}):v.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 Pe({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 Vc(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Pe.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;Ot&&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}),this.destination.on(He.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),Qe===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Lt?(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 Lt?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 Uc(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(He.RENDER,l=>{var u;(u=this.cameraTrack)==null||u.emit("render",l)}));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 gd(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,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}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 Pt(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new cs(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;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,a;if(e instanceof st)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof qe)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof yi){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let c=e.mediaTrack;return e.setOutputMediaStreamTrack(c)}if(e instanceof no)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var t;e instanceof st?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof qe?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 yi?e.source&&e.source.context.destroy():e instanceof no&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}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 N({code:A.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:u})=>{s.drawImage(n,a,c,l,u)}),No(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 No((e==null?void 0:e.imageElement)||e.imageUrl)}catch(h){throw new N({code:A.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,r,s;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 No(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(t=e.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(r=e.enableEffectOptimization)!=null?r:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}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 N({code:A.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 Ed(e)}clear(){var e,t;(e=this.videoContext)==null||e.disconnect(),(t=this.destination)==null||t.removeAllListeners(),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}};O([Ec(function(e){this.log.error("update failed",e)}),Q(e=>function(...t){return f(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield o_,this.updated=new Promise((r,s)=>{e.apply(this,t).then(r,s),setTimeout(s,5e3,new N({code:A.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],zn.prototype,"update",1);var KS=0;var Sd=class extends W{constructor(e){super("room");d(this,"seq",++KS);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,"localPublishFlag",0);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,"enableChorus",!1);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 e_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new t_({room:this}),this.badCaseDetector=new i_({room:this}),this.audioManager=new Hc(this),this.videoManager=new zn(this)}get videoCodec(){return"h264"}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(ee(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(rt(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(zc([a,a]),vr(`https://${a}`)):(s&&vr(s),n&&zc(n))}I.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:vi.main,sched_back_domain:vi.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 N({code:A.INVALID_OPERATION,message:B({key:V.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Je.INVALID_DESTROY),new N({code:A.INVALID_OPERATION,message:B({key:V.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,I.emit(C.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var s,n,a,c;let r=P();try{let{isCached:l,result:u,detailCost:h}=yield hh({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Ve,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} ${lt(u,{keysToExclude:["username","credential"]})}`),l&&I.once(C.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=D(D({},this.scheduleResult),u),X((s=u.config)==null?void 0:s.retryCount)&&Vd(u.config.retryCount),ee((n=u.config)==null?void 0:n.loggerDomain)&&vr(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,I.emit(C.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),v.addSuccessEvent({key:521700,cost:P()-r})}catch(l){throw v.addFailedEvent({key:521700,error:l}),l}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}switchRoom(e){return Promise.reject()}isSwitchRoomSupported(){return!1}};var g_=Ge(tt());var qh=Ge(Vh());var n_=o=>{let i=be(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 a_(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 eI(){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=be(i.sdp),t=a_(e.media[0]);return o.close(),t})}var c_=(o,i)=>f(void 0,null,function*(){var a;let e=be(o),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let r=e.media[0],s=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(c=>({id:c.value,uri:c.uri}))),s.ext&&(t.video.extensions=s.ext.map(c=>({id:c.value,uri:c.uri})));for(let c of r.rtp){if(c.codec!=="opus")continue;let l=r.fmtp.find(h=>h.payload===c.payload);if(!l)continue;let u={codec:c.codec,fmtp:l.config,payload:l.payload,rate:c.rate,channels:c.encoding,rtcpfb:[],rtx:0};(a=r.rtcpFb)==null||a.forEach(({payload:h,type:m,subtype:g})=>{if(h===u.payload){let T={id:m,params:[]};g&&T.params.push(g),u.rtcpfb.push(T)}}),t.audio.codecs.push(u);break}let n=["h264","vp8","h265"];return i&&n.shift(),t.video.codecs=[...a_(s)].filter(c=>n.includes(c.codec.toLocaleLowerCase())),t.video.decoders=(yield eI()).filter(c=>["h264","vp8","h265"].includes(c.codec.toLocaleLowerCase())),t}),d_=({serverAbility:o,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=be(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(jh({mid:a,serverAbility:o,clientAbility:i,parsedOffer:r}))}),t&&s.media.push(r.media.find(a=>a.mid==="dc")),Vt(s)},jh=({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=>{br(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];br(s,a)}return s},br=(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 tI(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 iI(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 rI(o){o.type===p.VIDEO&&o.fmtp&&o.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function oI(o){o.type===p.AUDIO&&o.fmtp&&o.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var l_=(o,i,e)=>{let t=qh.default.parse(o);return t.media.forEach((r,s)=>{var n;if((r.type===p.AUDIO||r.type===p.VIDEO)&&(iI(r),rI(r),oI(r),tI(r),r.type===p.VIDEO)){if(s<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>br(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>br(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),qh.default.write(t)};var u_=Ge(tt());var Id=class extends u_.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");!me&&Be&&I.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(){I.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(Id,"EVENT_BAD_HEALTH","bad_health");var h_=Id;function m_({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function p_({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):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})})}})}),r.enqueue(s)}})}function f_(o){let i=[Ki],e=[Rh,Ah,Ch,Ih,m_,p_,Sa,Ea],t=()=>{let l=[],u=[],h=[],m=0;self.onmessage=g=>{switch(g.data.type){case"sei":g.data.isMain?(l.push(g.data.data),g.data.small&&h.push(g.data.data)):u.push(g.data.data);break;case"ntp-offset":m=g.data.data;break}},self.onrtctransform=g=>{let{options:T}=g.transformer,_=T.isReceiver?p_({userId:T.userId,streamType:T.streamType,isAudio:T.isAudio}):m_({getNtpTime:()=>Date.now()+m,isAudio:T.isAudio,isMain:T.isMain,seiMessageList:T.isMain?T.small?h:l:u});g.transformer.readable.pipeThrough(_).pipeTo(g.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 Di=(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))(Di||{}),T_=0,E_=!1,sI=new Set,nI=o=>T_>2&&!E_&&sI.size===0&&o,aI=1,ci=class extends g_.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${aI++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(ii?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?n_(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(){Qo&&(this.scriptTransformWorker=f_({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,e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e.message)})}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(),v.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):s==="failed"&&v.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 zh(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 c_(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()))}),v.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw v.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=P(),c={type:"answer",sdp:d_({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||v.addSuccessEvent({key:521703,cost:P()-a})}catch(a){let c=a instanceof N&&a.code===A.API_CALL_ABORTED;throw c||this._log.error(`connect failed: ${a}`,e),this.reset(),!c&&!this.isReconnecting&&(v.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(Te.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=D({ability:t},e),s=yield this._signalChannel.sendWaitForResponse({command:Y.REBUILD_PEER_CONNECTION,responseCommand:$.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(s.data.code!==0)throw new N({code:s.data.code,message:s.data.message});yield this.connect(s.data.data.ability,!0),v.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),I.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=Gt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield St(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),v.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=xi()&&this._log.warn(`SDK has tried reconnect for ${xi()} 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(Te.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===Se.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){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===Se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===Se.FAILED||e.target.connectionState===Se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===Se.CONNECTED||e.target.connectionState===Se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),I.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 Ht;let e=null;return!_r()||this._peerConnection.getSenders().length===0?Ht:(e=this._peerConnection.getSenders()[0].transport,!jr()||this._peerConnection.getReceivers().length===0?Ht:e?e.state:Ht)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Di.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(fr(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&&pa(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 N({code:A.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{I.off(C.LEAVE_SUCCESS,s,this),this.off(Di.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new N({code:A.API_CALL_TIMEOUT,message:"connection timeout"});T_+=1,nI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),E_=!0,this.emit(Di.FIREWALL_RESTRICTION)),t(c)},Ms);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new N({code:A.API_CALL_TIMEOUT,message:"connection timeout"}))},I.on(C.LEAVE_SUCCESS,s,this),this.on(Di.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=be(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var g;return(g=m.ssrcs)==null?void 0:g.find(T=>{var _;return(_=T.value)==null?void 0:_.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=jh({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:be(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=be(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(cn()){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=be(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=be(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=be(this._peerConnection.remoteDescription.sdp));let a=te?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:te?r*1e3:r}]),s&&(n.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:te?s*1e3:s}]);let c={type:"offer",sdp:Vt(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(Be&&We<83||_e&&Ys(ut,"12.1")||te&&xo<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=Vt(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(!te||!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===oe.INACTIVE&&n===oe.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===oe.SENDONLY&&n===oe.INACTIVE&&(this._parsedAnswer.media[s].direction=oe.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return be(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=l_(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=be(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=[],br(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,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=[],br(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",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&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],br(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),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=>mi(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`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.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:Y.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:$.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};O([Ac("reconnect")],ci.prototype,"startReconnection",1),O([Qi(e=>e.userId)],ci.prototype,"addDownlink",1),O([Qi(e=>e)],ci.prototype,"removeDownlink",1),O([kt(!0)],ci.prototype,"updateSDP",1),O([Tt(521712,!1)],ci.prototype,"setOffer",1),O([Tt(521713,!1)],ci.prototype,"setAnswer",1);var Xh=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}},zh=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 Xh(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)})}},__=new Set;function Dt(){let o=Math.floor(Math.random()*4294967296);return __.has(o)?Dt():(__.add(o),o)}var S_=Ge(tt());var po=class extends S_.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:(I.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 Qh=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),!sn()||!s||!i||typeof Worker=="undefined"){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(g=>g.uint32_video_stream_type===3)[0];else{let g=(h=a.msg_down_stream_info)==null?void 0:h.filter(T=>{var _;return((_=T.msg_user_info)==null?void 0:_.str_identifier)===r})[0];c=(m=g==null?void 0:g.msg_video_status)==null?void 0:m.filter(T=>T.uint32_video_stream_type===3)[0]}if(c){let g=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}g>0&&g<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",g,"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)}},sr=new Qh;var Ad=class extends po{constructor(e){super(x(D({},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){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,s=Object.keys(t).filter(n=>{if(t[n]!==r[n]&&t[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${Wi()} ${Gi()}`),v.addEnum({key:521719,value:I_[n]})});else{this._checkPublishStateTimeoutId=ie.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}ie.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}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&&(gi()?(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=D({},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&lr),bigVideo:!!(this.flag&dr),smallVideo:!!(this.flag&Ds),auxVideo:!!(this.flag&Nr)}}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){return f(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working, switch to h264"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working, switch to vp8"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var u,h,m,g,T,_,S;if(!this.singlePC)return;this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),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 N({code:A.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),me&&$o()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(cr)}`),t.setProfile(cr),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:Y.SPC_PUBLISH,responseCommand:$.SPC_PUBLISH_RESULT,data:x(D({},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:R}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],R,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((u=this.localMainAudioTrack)==null?void 0:u.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(T=(g=this.localMainVideoTrack)==null?void 0:g.small)==null?void 0:T.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(S=this._room.scheduleResult.config)!=null&&S.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let l=new URLSearchParams(location.search).get("profileLevelId");l&&this.singlePC.setProfileLevelId(l)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!pt())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=(g,T,_)=>{var R;let S=c[T].sender.replaceTrack(_);u.push(T),(R=this.singlePC)!=null&&R.enableInsertableStreams&&S.then(()=>this.createEncodedStreams(c[T].sender,g)),this.initSenderTransform(c[T].sender,g),l.push(S)};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(oe.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,g;let h=this.getTrackByMediaType(t);if(!h)return u.enqueue(l);h.isAudio?u.enqueue(h.enableEncodeFrame?h.encodeFrame(l):l):u.enqueue((m=this.singlePC)!=null&&m.isUsingH264||(g=this.singlePC)!=null&&g.isUsingH265?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||!Qo)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"&&!oc()){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(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(oe.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=sr.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;v.addFailedEvent({key:u,error:10002}),sr.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=Do(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(oe.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),sr.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||e&&e===this.localAuxAudioTrack,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=x(D({},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=x(D({},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(oe.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:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:$.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:$.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT||t.getCode()===A.API_CALL_ABORTED)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),Ti){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||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/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||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/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:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:$.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`),gi()&&(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)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===oe.INACTIVE&&(yield this.singlePC.setTransceiverDirection(oe.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`),gi()&&(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(oe.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.mediaType===2||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:Y.UPDATE_MUTE_STAT,responseCommand:$.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&I.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===Dr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new N({code:A.NOT_SUPPORTED_H264,message:B({key:V.NOT_SUPPORTED_H264ENCODE})})):new N({code:A.UNKNOWN,message:B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:$.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}))})}};O([gt(function({localVideoTrack:e}){e==null||delete e.retryEncodeFailed})],Ad.prototype,"unpublish",1);var I_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(I_||{}),Yh=Ad;function A_(o){return Object.keys(o).filter(i=>o[i])}var As=class extends po{constructor(e){super(x(D({},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 ni(this._room,this),this.remoteVideoTrack=new yi(this._room,this),this.remoteAuxiliaryTrack=new ls(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 Wt(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} ${A_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=sr.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),v.addFailedEvent({key:524702}),sr.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(sr.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 N({code:A.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.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Be&&We<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=D({},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} [${A_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(sr.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=Y.UNSUBSCRIBE,n=$.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=$.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 N({code:a.code,message:B({key:V.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:Dt(),bigVideoSsrc:Dt(),bigVideoRtxSsrc:Dt(),auxVideoSsrc:Dt(),auxVideoRtxSsrc:Dt()},{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:Y.SPC_SUBSCRIBE,responseCommand:$.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 N({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(!ac)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(X(n)||X(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(!ac||!this.singlePC||!this._peerConnection||Fi(e)&&Fi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return X(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),X(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Fi(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||Fi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&Fi(t)||!c&&Fi(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()}};O([kt(),Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new N({code:A.API_CALL_ABORTED,message:B({key:V.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],As.prototype,"subscribe",1),O([kt()],As.prototype,"unsubscribe",1),O([Qi(()=>"jitter")],As.prototype,"setJitterBufferDelay",1);var C_=As;function R_(){return Q(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;I.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function y_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var b_=Ge(tt());function dI(){return Math.floor(Math.random()*16383)}var Rd=class Rd extends b_.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($.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)||dI(),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(Y.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)>Rd.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),St(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(Rd,"SEQ_INTERVAL",300);var Cd=Rd;var{isString:v_,isUndefined:fo,getNetworkType:lI,isEmpty:Qn}=At,di=class extends Sd{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",zo);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);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new jn(this,this._log),this.userManager=new Wc(this.userId,this._log),this._version=Ve,this.sdpSemantics=To,fo(e.sdpSemantics)?Ei.isUnifiedPlanDefault()&&(this.sdpSemantics=ur):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${lI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=fo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&zo,!fo(e.enableSPC)&&zo&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new h_(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=tm(n,[]);I.emit(C.REMOTE_PUBLISH_STATE_CHANGED,D({room:this},s)),this.emit("remote-publish-state-changed",D({},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 N&&u.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=P();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:P()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ci({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 N({code:A.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(Te.SETUP_FAILED,h=>{this.clearJoinTimeout(),I.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)&&zo&&(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:Sl(),netType:wr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&on()};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 N({code:A.JOIN_ROOM_FAILED,message:B({key:V.JOIN_ROOM_TIMEOUT})}))},a),I.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once($.JOIN_ROOM_RESULT,h=>f(this,null,function*(){this.clearJoinTimeout();let{code:m,message:g,data:T,tinyId:_}=h.data;I.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=T.publishers,this._iceServersFromJoin=T.iceServer?[T.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var S;(S=this.singlePC)==null||S.connect(x(D({},T.ability),{useVp8:T.ability.useVp8||!!e.useVp8,useH265:T.ability.useH265||!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${m} error: ${g}`),s(new N({code:A.JOIN_ROOM_FAILED,extraCode:m,message:B({key:V.JOIN_ROOM_FAILED,data:{error:g,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(x(D({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),re.logSuccessEvent({userId:this.userId,eventType:ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Di.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof Yh&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Di.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof qn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),re.logFailedEvent({userId:this.userId,eventType:ze.REJOIN,error:e}),this.emit("error",new N({code:A.JOIN_ROOM_FAILED,message:B({key:V.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Vf(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 gs({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 Cd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Is({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Is.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Fe(this,this.signalChannel).add(Te.CONNECTION_STATE_CHANGED,a=>{I.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,D({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Te.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add($.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add($.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add($.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add($.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(re.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($.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${lt(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add($.FALLBACK_CODEC,a=>f(this,null,function*(){var l,u,h,m,g;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"&&(v.addCount({key:513e3}),yield(m=this.singlePC)==null?void 0:m.switchVideoEncoder("h264"),yield(g=this.uplinkConnection)==null?void 0:g.sendMediaSettings())})),this.signalChannel.once(Te.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,I.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),I.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&I.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Ne(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),I.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}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=ie.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),ie.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?ef(this.userId):[],s=x(D({str_sdk_version:bs,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:D({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:wr()},t.msg_device_info)});if(this.heartbeatReport=s,I.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.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",x(D({},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!==xd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",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)),I.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof qn&&(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?C_:Hh)({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!==A.ICE_TRANSPORT_ERROR&&(s===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",x(D({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=ie.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){ie.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:Y.GET_USER_LIST,responseCommand:$.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 B({key:V.SIGNAL_RESPONSE_FAILED,data:{signalResponse:$.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||!Lh)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof dt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Se.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"),re.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 qn({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 Hh({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 N({code:A.INVALID_OPERATION,message:B({key:V.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),ie.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:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:$.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 N({code:A.SWITCH_ROLE_FAILED,message:B({key:V.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof N&&r.getCode()===A.API_CALL_TIMEOUT&&(r=new N({code:A.SWITCH_ROLE_FAILED,message:B({key:V.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof vt&&(c instanceof Ci?r.audio=c:t.audio=c),c instanceof qe&&(c instanceof st&&c.mediaType===2?r.video=c:t.video=c)});let s=Qn(t),n=Qn(r);(!s||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Yh({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new qn({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",x(D({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==A.ICE_TRANSPORT_ERROR&&(l===A.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 vt&&(s instanceof Ci?r.audio=s:t.audio=s),s instanceof qe&&(s instanceof st&&s.mediaType===2?r.video=s:t.video=s))});try{let s=e.map(n=>n.kind).join(",");Qn(t)||(this._log.info(`unpublish() => main ${s}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Qn(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||!Jl()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&I.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=D({},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),I.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${md(n)}] prev: [${md(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());I.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof N?n.getCode():A.UNKNOWN,c=n;throw n instanceof N?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new N({code:A.API_CALL_ABORTED,message:B({key:V.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new N({code:a,message:B({key:V.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)}),I.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,ie.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),I.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&ie.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=ie.run("intervalInWorker",()=>{var s;zr.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!zr.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=ie.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"),ie.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(!ql||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;X(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&X(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(At.getTurnServer(s))):At.isPlainObject(e)&&r.push(At.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:$.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==A.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:$.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==A.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?$.START_PUBLISH_TENCENT_CDN_RES:$.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==A.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?$.STOP_PUBLISH_TENCENT_CDN_RES:$.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==A.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:$.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==A.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:$.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==A.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:$.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==A.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:$.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=At.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.localPublishFlag=0,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 ${Eo-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Eo}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Eo-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:Eo};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(v_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!fo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new N({code:A.INVALID_PARAMETER,message:B({key:V.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(!fo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!fo(e.userDefinePushArgs))if(v_(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 N({code:A.INVALID_PARAMETER,message:B({key:V.INVALID_USER_DEFINE_PUSH_ARGS})});Qn(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&&ii)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 N({code:A.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 g;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((g=this.scheduleResult.config)==null?void 0:g.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:Dt(),bigVideoSsrc:Dt(),bigVideoRtxSsrc:Dt(),auxVideoSsrc:Dt(),auxVideoRtxSsrc:Dt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let h=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(T=>{this.resolveSwitchRoomSubedReq=T,St(5e3).then(T)}),I.emit(C.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let m;try{this.userManager.clear(),m=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:$.SEND_SWITCH_ROOM_RES,data:u});let{code:T,message:_}=m.data;if(T===0)this.userSig=s,fo(n)||(this.privateMapKey=n),I.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:h,targetRoomId:c});else{this._log.error(`switch room failed. result: ${T} error: ${_}`);let S=new N({code:A.SWITCH_ROOM_FAILED,extraCode:T,message:_});throw I.emit(C.SWITCH_ROOM_FAILED,{room:this,error:S}),S}}catch(T){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=h,this.resolveSwitchRoomSubedReq(),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()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),Kn(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_NETWORK_TIME,responseCommand:$.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};O([Ie(["left",W.INIT],"joined"),yt({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"),ai(!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())}}),wf()],di.prototype,"join",1),O([Ie("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),xf(),Ac("leave room"),fn({fnName:"publish",validateArgs:!1}),fn({fnName:"unsubscribe",validateArgs:!1})],di.prototype,"leave",1),O([kt(),R_(),yt({settings:{retries:xi,timeout:e=>Gt(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),I.emit(C.PUBLISH_FAILED,{room:this}))}})],di.prototype,"publish",1),O([fn({fnName:"publish"}),Gp("api-call"),kt(),y_(),gt(function(){var e,t;this.localTracks.size===0&&_r()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],di.prototype,"unpublish",1),O([Ec(e=>{if(e.code!==A.API_CALL_ABORTED)throw e}),Qi(e=>e.userId)],di.prototype,"replaceTrack",1),O([Qi((...e)=>e[0].userId),$c(),Lf(),yt({settings:{retries:xi,timeout:e=>Gt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),I.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],di.prototype,"subscribe",1),O([fn({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")})}}),Qi((...e)=>e[0].userId)],di.prototype,"unsubscribe",1);Wn.create=Wn._create.bind(Wn,di);Yl(30);var H3=Wn;export{H3 as default};
|
|
143
|
+
}`});l(this,"yTextureRef");l(this,"uTextureRef");l(this,"vTextureRef");l(this,"Y");l(this,"U");l(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 l_=(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 IA(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var SA=0,dl=class{constructor(t){l(this,"id",SA++);l(this,"trackDoneOB");l(this,"startOB");l(this,"stopOB");l(this,"decoder");l(this,"videoContext");l(this,"gop",0);l(this,"gop_helper",0);l(this,"waitFirstKeyFrame",!0);l(this,"startTimestamp",0);l(this,"startTime",0);l(this,"startPerformanceTime",0);l(this,"inputFrameCount",0);l(this,"decodedFrameCount",0);l(this,"decodeFrameCount",0);l(this,"downgradeLevel",0);l(this,"lastDowngradeTime",0);l(this,"lastFrameDiff",0);l(this,"lastDecodeFrameTimestamp",0);l(this,"config");l(this,"gop_before_configure",[]);l(this,"videoElement");l(this,"type","wasm");l(this,"goodType");l(this,"renderer","2d");l(this,"wasmOption");l(this,"createDecoder");l(this,"_decodeSink");l(this,"isReported",!1);l(this,"track");l(this,"stateChangeOB");l(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=vt(),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=be(e.availableState,le.OFF),this.stopOB=vt(),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),Ae(this.stateChangeOB,Qh((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),ze(this.stopOB),Le()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Ae(this.pipe(this.track),ze(this.stopOB),Pi());Ae(e,Le(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),Q.addFailedEvent({key:l_(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:l_(this.type,this.renderer)}),Q.addSuccessEvent({key:514704})})),Ae(e,Hr(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"&&!Wm()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var a,u;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!IA(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(((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: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=Ee();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} ${(u=t.getMetadata)==null?void 0:u.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 a;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(a=this.videoContext)==null||a.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":r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(r.on("videoFrame",u=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&t.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${u.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(u.timestamp)),e.next(u)}),r.on("error",u=>{t.log.error(u),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 yt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(yt.UNAVAILABLE,m=>{t.log.error(m),e.error(7)});let u=new cl(this.videoContext);r.on("videoCodecInfo",m=>u.resize(m.width,m.height)),r.on("videoFrame",m=>{({y:u.Y,u:u.U,v:u.V}=m),this.downgradeLevel===1?this.decodedFrameCount%2===0&&u.render(this.decodedFrameCount):u.render(this.decodedFrameCount)}),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let u=new MediaStreamTrackGenerator({kind:"video"}),m=u.writable.getWriter();t.setInputMediaStreamTrack(u),r.on("videoFrame",p=>m.write(p))}else{this.videoContext=new Mt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let u=this.videoContext.createVideoImageSource();r.on("videoFrame",p=>{try{u.image=p,u.update()}catch(g){delete this.goodType,t.log.error(g),e.error(11)}});let m=new _s(this.videoContext,{name:"remotePlayer",logger:t.log});u.connect(m),t.source=u,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(a){t.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var m_=Promise.resolve(),Ic=class extends h_.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"_rotation",0);l(this,"cameraTrack");l(this,"cameraNode");l(this,"transformNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"_enableFaceCentering",!1);l(this,"_enableEffectOptimization",!1);l(this,"onAbort");l(this,"_color");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"mixTrack");l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"_virtualBackgroundAbortCallback");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",F.createLogger({id:"vm"}));l(this,"_mat4");l(this,"_postProcessing");l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);l(this,"updated",m_);l(this,"_updateFlag",!1);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Mt({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 cr(this._rotation)?{width:r,height:e}:{width:e,height:r}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Mt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new yt({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(dm<=22),this._glVideoContext.on(yt.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,o){this.onAbort=e,this._mat4=r,this._postProcessing=o}enablePrintDetail(e=2e3){this._checkId=lt.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(),lt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(_r||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 yt({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 Ru(this.smallVideoContext,e,this.log),this.smallVideoContext.on(yt.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;_r&&n.setCanvas(e);let a=e&&((r=this.destination)==null?void 0:r.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),o.setOutputMediaStreamTrack(a)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return y(this,null,function*(){var s;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ct.RENDER,n=>{var a;(a=this.cameraTrack)==null||a.emit("render",n)})),kt===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof yr?(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 yr?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 bu(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Ct.RENDER,m=>{var p;(p=this.cameraTrack)==null||p.emit("render",m)}));let{width:n,height:a}=this.cameraResolution,u=yield this.getWatermarkImage(n,a);this._waterMarkOption={x:0,y:0,width:u.width,height:u.height,image:u},this.cameraNode=new al(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,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}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 Ar(this.videoContext,this.log,this._isMirror,this._rotation),n=n.connect(this.transformNode),n.disconnect(),this.log.info(`start mirror ${this._isMirror} rotate ${this.rotation}`)),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new vn(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:u,height:m}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(u,m),u&&m&&this.waterMarkNode.resize(u,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})),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 r,o,s,n,a;if(e instanceof ii)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof lr)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof To){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let u=e.mediaTrack;return e.setOutputMediaStreamTrack(u)}if(e instanceof Is)return this.log.info("change mix input",(n=e.outMediaTrack)==null?void 0:n.label),this.setMixTrack(e);this.log.warn("change unknown input",(a=e.mediaTrack)==null?void 0:a.label)}removeInput(e){var r;e instanceof ii?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof lr?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 To?e.source&&e.source.context.destroy():e instanceof Is&&(delete this.mixTrack,this.update())}setMixTrack(e){this.mixTrack=e}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 de({code:q.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:u,width:m,height:p})=>{s.drawImage(n,a,u,m,p)}),Qs(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()})}setWatermark(e){return y(this,null,function*(){let r;try{r=yield Qs((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new de({code:q.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:a=r.height,type:u="watermark",zIndex:m=2}=e;this.watermarkImageList.some(g=>g.type===u)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==u),this.pushWaterMarkImageList({x:o,y:s,width:n,height:a,image:r,zIndex:m,type:u,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:a,image:r,zIndex:m,type:u,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,E)=>g==="imageUrl"?void 0:E))})}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,o,s;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 Qs(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type),this._enableFaceCentering=(r=e.enableFaceCentering)!=null?r:this._enableFaceCentering,this._enableEffectOptimization=(o=e.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(s=e.color)!=null?s:[0,1,0]}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 de({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 dl(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}};te([Zg(function(e){this.log.error("update failed",e)}),Me(e=>function(...r){return y(this,null,function*(){this._updateFlag||(this._updateFlag=!0,yield m_,this.updated=new Promise((o,s)=>{e.apply(this,r).then(o,s),setTimeout(s,5e3,new de({code:q.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Ic.prototype,"update",1);var yA=0;var ul=class extends le{constructor(e){super("room");l(this,"seq",++yA);l(this,"sdkAppId");l(this,"userId");l(this,"userSig");l(this,"privateMapKey");l(this,"latencyLevel");l(this,"tinyId");l(this,"scene");l(this,"roomId");l(this,"useStringRoomId");l(this,"role","anchor");l(this,"joinParams",null);l(this,"localPublishFlag",0);l(this,"localTracks",new Set);l(this,"enableAutoPlayDialog",!0);l(this,"autoReceiveAudio",!0);l(this,"autoReceiveVideo",!0);l(this,"proxy_ws");l(this,"proxy_wt");l(this,"proxy_unified");l(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}});l(this,"keyPointManager");l(this,"audioManager");l(this,"videoManager");l(this,"callDurationCalculator");l(this,"badCaseDetector");l(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});l(this,"videoDecodeFallbackType");l(this,"smallMode","canvas");l(this,"enableChorus",!1);l(this,"_isUsingCachedSchedule",!1);l(this,"_log",F.createLogger({id:`r${this.seq}`}));l(this,"_joinedTimestamp",0);l(this,"_sdkType");l(this,"heartbeatReport");l(this,"quality");l(this,"enableSEI");l(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,Qe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),Qe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),Qe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new c_({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new d_({room:this}),this.badCaseDetector=new u_({room:this}),this.audioManager=new Nu(this),this.videoManager=new Ic(this)}get videoCodec(){return"h264"}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(Ne(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(jt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=a,a?(Bu([a,a]),Fo(`https://${a}`)):(s&&Fo(s),n&&Bu(n))}U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ni.main,sched_back_domain:ni.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 de({code:q.INVALID_OPERATION,message:$e({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(tr.INVALID_DESTROY),new de({code:q.INVALID_OPERATION,message:$e({key:Fe.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,U.emit($.ROOM_DESTROY,{room:this})}schedule(e,r){return y(this,null,function*(){var s,n,a,u;let o=Ee();try{let{isCached:m,result:p,detailCost:g}=yield _p({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:dt,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} ${Er(p,{keysToExclude:["username","credential"]})}`),m&&U.once($.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=X(X({},this.scheduleResult),p),ke((s=p.config)==null?void 0:s.retryCount)&&Vl(p.config.retryCount),Ne((n=p.config)==null?void 0:n.loggerDomain)&&Fo(p.config.loggerDomain),this.videoDecodeFallbackType=((a=p.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((u=p.config)==null?void 0:u.smallMode)||this.smallMode,U.emit($.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),Q.addSuccessEvent({key:521700,cost:Ee()-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 p_(i,t=!1){let e=Object.defineProperties(vt(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Be,i.onmessageerror=Be,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var Vp=class extends pe{constructor(t,e){super(t);let r=new pe(t);r.next=Be,e(r)}},p4=_e(Vp,"takeUntilComplete");var Ft={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},f_="__INLINE__WORKER__",g_="__INLINE__WASM__",{debug:E_}=console;Ft.debug||(console.debug=()=>{});var AA=!f_.startsWith("__"),bA=!g_.startsWith("__");function ll(){let i=Jo(`${Ft.assetsPath?`${Ft.assetsPath}/`:""}worker.js`);return AA?URL.createObjectURL(new Blob([atob(f_)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var Sc;function ml(){return y(this,null,function*(){let i=Ft.assetsPath?`${Ft.assetsPath}/`:"";return Sc||(bA?Sc=new TextEncoder().encode(atob(g_)).buffer:Sc=yield fetch(Jo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),Sc)})}var Fp=class{constructor(){l(this,"playPort");l(this,"playPortSent",!1);l(this,"worklet");l(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return y(this,null,function*(){let t=Ge("player"),e=ll();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield ml(),flag:Ft},numberOfInputs:2}),F.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return y(this,null,function*(){var r;yield this.init();let e=new MessageChannel;(r=this.playPort)==null||r.postMessage(null,[e.port1]),t(e.port2)})}},hl=new Fp;var $p=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),y4=$p?Promise.resolve().then(function(){return NA}):Promise.resolve().then(function(){return PA});var A4=$p?Promise.resolve().then(function(){return wA}):Promise.resolve().then(function(){return LA});var RA=$p?Promise.resolve().then(function(){return OA}):Promise.resolve().then(function(){return VA});function Bp(...i){return y(this,null,function*(){return(yield RA).default(...i)})}var vA=i=>y(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),CA=(...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(a=>{e[n].accept[a]=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(vA));return i[0].multiple?o:o[0]}),NA={__proto__:null,default:CA};function pl(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 pl=function(e){this.s=e,this.n=e.next},pl.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 pl(i)}var __=(o,s,...n)=>y(void 0,[o,s,...n],function*(i,t,e=i.name,r){let a=[],u=[];var m,p=!1,g=!1;try{for(var E,A=function(C){var N,D,x,Z=2;for(typeof Symbol!="undefined"&&(D=Symbol.asyncIterator,x=Symbol.iterator);Z--;){if(D&&(N=C[D])!=null)return N.call(C);if(x&&(N=C[x])!=null)return new pl(N.call(C));D="@@asyncIterator",x="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());p=!(E=yield A.next()).done;p=!1){let C=E.value,N=`${e}/${C.name}`;C.kind==="file"?u.push(C.getFile().then(D=>(D.directoryHandle=i,D.handle=C,Object.defineProperty(D,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>N})))):C.kind!=="directory"||!t||r&&r(C)||a.push(__(C,t,N,r))}}catch(C){g=!0,m=C}finally{try{p&&A.return!=null&&(yield A.return())}finally{if(g)throw m}}return[...(yield Promise.all(a)).flat(),...yield Promise.all(u)]}),DA=(...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 __(e,i.recursive,void 0,i.skipDirectory)}),wA={__proto__:null,default:DA},MA=(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 a=[],u=null;if(i instanceof Blob&&i.type?u=i.type:i.headers&&i.headers.get("content-type")&&(u=i.headers.get("content-type")),t.forEach((g,E)=>{a[E]={description:g.description||"Files",accept:{}},g.mimeTypes?(E===0&&u&&g.mimeTypes.push(u),g.mimeTypes.map(A=>{a[E].accept[A]=g.extensions||[]})):u?a[E].accept[u]=g.extensions||[]:a[E].accept["*/*"]=g.extensions||[]}),e)try{yield e.getFile()}catch(g){if(e=null,r)throw g}let m=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:a,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(m);let p=yield m.createWritable();return"stream"in i?(yield i.stream().pipeTo(p),m):"body"in i?(yield i.body.pipeTo(p),m):(yield p.write(yield i),yield p.close(),m)}),OA={__proto__:null,default:MA},xA=(...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 a=="function"&&a(),e(m)},a=i[0].legacySetup&&i[0].legacySetup(n,()=>a(r),o),u=()=>{window.removeEventListener("focus",u),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",u)}),o.addEventListener("change",()=>{window.removeEventListener("focus",u),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),PA={__proto__:null,default:xA},kA=(...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=a=>{typeof n=="function"&&n(),e(a)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let a=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(a=a.filter(u=>u.webkitRelativePath.split("/").every(m=>!i[0].skipDirectory({name:m,kind:"directory"})))):a=a.filter(u=>u.webkitRelativePath.split("/").length===2),s(a)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),LA={__proto__:null,default:kA},UA=(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(u,m){return y(this,null,function*(){let p=u.getReader(),g=new ReadableStream({start:C=>function N(){return y(this,null,function*(){return p.read().then(({done:D,value:x})=>{if(!D)return C.enqueue(x),N();C.close()})})}()}),E=new Response(g),A=yield E.blob();return p.releaseLock(),new Blob([A],{type:m})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof a=="function"&&a()},a=t.legacySetup&&t.legacySetup(n,()=>a(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),VA={__proto__:null,default:UA};var Hp=class{constructor(t){this.name=t;l(this,"ready");l(this,"worker");l(this,"ports");l(this,"ids",1);l(this,"transactions",new Map);l(this,"log");l(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=ll(),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:a,payload:u}})=>{var m;if(n)(m=this.transactions.get(n))==null||m(u),this.transactions.delete(n);else switch(a){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",u),s(u);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(u.value){let p=typeof u.old=="string"?u.old:`${u.old.action}ing`,g=typeof u.value=="string"?u.value:`${u.value.action}ing`;console.log(od(),u.group,u.name,p,"\u{1F449}",g)}break;case"log":console.log(u);break;case"glog":window.dispatchEvent(new CustomEvent(a,{detail:u}));break}},r.postMessage({wasm:yield ml(),flag:Ft},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Wp=class{constructor(t,e,r){this.worker=t;l(this,"channel",new MessageChannel);l(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()}},Gp=class i extends Hp{constructor(){super("main");l(this,"switchValue",new Map);l(this,"extendChannel");l(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 Pt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},Ro=new Gp,Cs,FA=-1;function T_(i){return console.log(i),Cs.push(i.slice()),Cs.length>1e3&&Cs.shift(),i}function I_(i){return y(this,null,function*(){switch(FA){case 0:this.edpl.willDecodeAudio=T_;break;case 2:this.edpl.didEncodeAudio=T_;break}yield Ro.create(),U.emit($.JOIN_SEND_CMD,{room:this});let t=new Wp(Ro,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:a}=s;this.onWorkerEvent(n,a)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(U.emit($.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new de({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:$e({key:Fe.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:jp},useWt:{set:$A},enableDebug:{set(i){console.debug=i?E_:()=>{},Ro.setSwitchValue("enableDebug",i)}},useV2:{set:qp},dump:{value(){if(Cs||(console.warn("dump audio will be activated at next time join room"),Cs=[]),!Cs.length){console.warn("no audio data to dump,try it later");return}let i=[];return Cs.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Bp(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;Ro.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,Ro.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Bp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Ft.useHardDecoder="prefer-hardware";break;case!1:Ft.useHardDecoder="prefer-software";break;default:Ft.useHardDecoder="no-preference"}}}});function jp(i){return y(this,null,function*(){Ro.setSwitchValue("useAINS",i)})}function qp(i){return y(this,null,function*(){Ro.setSwitchValue("useV2",i)})}function $A(i){return y(this,null,function*(){Ro.setSwitchValue("useWt",i)})}function S_(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),i.player.setVolume(0),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function y_(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),Ae(p_(r.port2),ze(be(i,le.INIT)),Le(s=>{let{data:n,packetsReceived:a}=s;i.stat.packetsReceived=a,i.stat.framesReceived++,e++;let u=n[4]&31;if(e<=10){let p=Array.from(n.slice(0,10)).map(g=>g.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${u}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${p}`)}let m;switch(u){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 fl=[];function b_(i){var u;let t=vt();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let m=0;m<=fl.length;m++)if(!fl[m]){fl[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;(u=this.session)==null||u.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(ge(X({},m.data),{data:new Uint8Array(i.encodeFrame({data:m.data.data.buffer,timestamp:m.data.timestamp}).data)})))};let s=new MediaStream,n,a=m=>{let p=s.getAudioTracks()[0];p&&(n.disconnect(),s.removeTrack(p)),s.addTrack(m),this._log.info("push audio track:",m.readyState,m.getSettings().deviceId),n=Ge("player").createMediaStreamSource(s),n.connect(hl.worklet,0,this.index)};Ae(be(i,"output-media-track-changed"),ze(be(i,"ready")),Le(a,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),fl[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),Ae(t,rc(m=>i.volume=m),ki(Au(1e3)),Le(()=>{i.volume=0})),a(i.outMediaTrack)}var iW=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var zp=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;l(this,"track");l(this,"label");l(this,"insertKeyFrame",!0);l(this,"session");l(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});e.signal.addEventListener("abort",()=>{o.encoder.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,a)=>{o.encoder.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,a.enqueue(n))}}),e)})}encode(t){var e,r;(r=(e=this.session)==null?void 0:e.encoder)==null||r.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return y(this,null,function*(){let o=yield this.recreate(r,{recreateCount:0,frameEncoded:0,selectConfigIndex:0});this.session=o;let s=0;t.pipeTo(new WritableStream({write:n=>{o.encoder.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight},o)),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.encoder.close()})})}recreate(t,e){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.recreateCount===0&&U.emit($.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,e.frameEncoded=r,this.track.enabled===!1)return;let a=null;if(this.localTrack.enableEncodeFrame){a=new Uint8Array(s.byteLength),s.copyTo(a);let u=this.localTrack.encodeFrame({data:a.buffer},this.type===3);a=new Uint8Array(u.data)}a?(this.localTrack.stat.bytesSent+=a.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:a,duration:s.duration},timestamp:n},[a.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),e.recreateCount++,setTimeout(()=>this.recreate(t,e),100)}});return e.encoder=o,yield this.configure(null,e),e})}configure(t,e){return y(this,null,function*(){var r;t&&Object.assign(this.config,t),(r=e.encoder)==null||r.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function gl(i,t){return y(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.420028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Ft.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 zp(i,t.type,o,s.port2);return s.port2.onmessage=a=>{if(a.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:u}=a.data;aa({configureBr:[a.data.bitrate,u]}),n.session&&n.configure({bitrate:u},n.session)}},this._log.info("start push",r,t),n})}function R_(i){return y(this,null,function*(){var p;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((p=i.manager)!=null&&p.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 a=yield gl.call(this,i,r);this._log.info("VideoEncoder created",r);let u,m=g=>y(this,null,function*(){if(u==null||u.abort("track changed"),!g)return;u=new AbortController;let{width:E,height:A,displaySurface:C}=g.getSettings();E&&(a.config.width=E),A&&(a.config.height=A);let N=Kt.match(/Chrome\/(\d+)/);(N==null?void 0:N[1])==="114"&&C==="browser"&&delete a.config.hardwareAcceleration,this._log.info("push",e,"track:",g.readyState,g.getSettings());let D;if(typeof MediaStreamTrackProcessor!="undefined"&&!(g instanceof CanvasCaptureMediaStreamTrack))D=new MediaStreamTrackProcessor({track:g}).readable;else{let Z;D=new ReadableStream({start(ue){i.on("render",Se=>{if(i.player.mode!==0)try{ue.enqueue(new VideoFrame(Se,{timestamp:performance.now()*1e3}))}catch(Ye){console.warn(Ye)}})},pull(ue){return y(this,null,function*(){if(i.player.mode===0&&Mi()&&i.player.element)return new Promise(Se=>{i.player.element.requestVideoFrameCallback((Ye,H)=>{try{let Pe=new VideoFrame(i.player.element);ue.enqueue(Pe)}catch(Pe){console.warn(Pe)}Se()})})})}})}let x="small"in i&&i.small;return x?(this.smallEncoder||(this.smallEncoder=yield gl.call(this,i,{profile:x,type:3,trackType:o})),this.smallEncoder.track=g,this.smallEncoder.label="small",D=yield this.smallEncoder.trans(D,u,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),a.track=g,a.label=e,a.start(D,u,this)});return Ae(be(i,"output-media-track-changed"),ze(be(i,"ready")),Le(m,console.error,()=>{var g;this._log.info("stop push",e,r),u.abort("unpublish"),a.close(),(g=this.smallEncoder)==null||g.close()})),m(i.outMediaTrack)})}var vo=class vo extends le{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;l(this,"enableInBackground",!1);l(this,"interval",400);e.on("joined",()=>{this.emit(vo.INTERVALCHANGED,this.interval)}),Ae(be(this,vo.INTERVALCHANGED),go(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):Ae(hE(s),fo(()=>[]))),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==le.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(vo.INTERVALCHANGED,this.interval)}stop(){}};l(vo,"INTERVALCHANGED","intervalChanged"),te([Ze([le.INIT,le.OFF],le.ON)],vo.prototype,"start",1),te([Ze([],le.OFF)],vo.prototype,"stop",1);var El=vo;var Co=class Co extends ul{constructor(e){super(e);l(this,"index",0);l(this,"session");l(this,"tinyid");l(this,"roomid");l(this,"openid");l(this,"socketid");l(this,"relayip");l(this,"clientip");l(this,"remotePublishedUserMap",new Map);l(this,"bussinessInfo");l(this,"token");l(this,"audioVolumeEvalution",new El(this));l(this,"enableAIVoice",jp);l(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:Em(),uint32_device_type:0,str_os_verion:_m(),uint32_link_type:1,str_client_version:dt,uint32_net_type:$o[Zr.getNetworkType()],ua:navigator.userAgent,version:""}});l(this,"joinAbortController",new AbortController);l(this,"smallAbortCtrl");l(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,qp(!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=a=>{n.port2.close(),o(a.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=a=>{a.data?o.next(a.data):o.complete()},s.port2.onmessageerror=a=>o.error(a),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 u,m,p;let s=Zr.getEnv(),n=Gd(),a={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(u=this.proxy_wt)==null?void 0:u.replace("https://",""),proxy_ws:(m=this.proxy_ws)==null?void 0:m.replace("wss://",""),proxy_cloud:(p=this.scheduleResult.iceServers)!=null&&p.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:un(),browserInfo:Gd(),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:dt,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 I_.call(this,a),console.log(this),hl.playAudio(g=>this.postMessage({cmd:"setAudioWorkletPort"},[g])),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()),this.localTracks.clear()})}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=ze(be(this,"left"));Ae(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(ge(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 $.RECEIVED_PUBLISHED_USER_LIST:U.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 il(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let g=r,E=this.remotePublishedUserMap.get(g);E&&(E.remoteVideoTrack.close(),E.remoteAuxiliaryTrack.close(),E.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(g),this.emit("remote-unpublished",E))}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:g,muteState:E,flag:A}=r,C=this.remotePublishedUserMap.get(E.userId);if(!C){this.emit("remote-publish-state-changed",r);return}C.flag=A}U.emit($.REMOTE_PUBLISH_STATE_CHANGED,X({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"7":this.localPublishFlag!==r.flag&&(this.localPublishFlag=r.flag,this.emit("local-publish-flag-changed",r.flag));return;case"network-quality":this.quality=X({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:a,downlinkInfo:u,msg_down_stream_info:m}=r,p={str_sdk_version:dt,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:$o[na()]},msg_event_msg:gE(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:a,msg_down_stream_info:m};U.emit($.HEARTBEAT_REPORT,{room:this,report:p}),this.emit("heartbeat-report",p),U.emit($.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:u}),delete r.downlinkInfo;break;case"signal-connection-state-changed":U.emit($.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*(){e.forEach(a=>this.localTracks.add(a));let r=e.reduce((a,u)=>u.mediaType|a,0),o=this.sendMessage("publish",r).then(a=>a.err!==0?Promise.reject(a.err):a),s=0,n=a=>y(this,null,function*(){switch(yield o,a.muted&&(s|=a.mediaType),Rt(a,a).add("mute",()=>{this.postMessage("mute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:a.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),a.mediaType){case 1:b_.call(this,a);break;default:yield R_.call(this,a)}});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(mt),e.forEach(r=>this.localTracks.delete(r))})}subscribe(...e){return y(this,null,function*(){let r=e.reduce((g,E)=>E.mediaType|g,0),{userId:o,tinyId:s,streamType:n}=e[0],a=this.remotePublishedUserMap.get(o),u=X({},a.subscribeState),m=Object.assign(new va,u);console.log("subscribe mediaType",r,u,m,e.map(g=>g.mediaType)),m.mediaType|=r,U.emit($.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:a,subscribeState:m});let p=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(g=>m.mediaType&g).map(g=>({mediaType:g,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",p),yield Promise.all(e.filter(g=>!g.isSubscribed).map(g=>{switch(g.mediaType){case 1:return S_.call(this,g);default:return y_.call(this,g)}})),U.emit($.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:a})})}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 a of e)a.unsubscribe();U.emit($.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 gl.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(a=>s&a).map(a=>({mediaType:a,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"))}};te([ho(Co.prototype.afterJoin),Ze(["left",le.INIT],"joined"),i_()],Co.prototype,"join",1),te([Ze("joined","left",{ignoreError:!0}),o_()],Co.prototype,"leave",1),te([us(),s_()],Co.prototype,"publish",1),te([us(),n_()],Co.prototype,"unpublish",1),te([rE((...e)=>e[0].userId),a_()],Co.prototype,"subscribe",1);var _l=Co;kn.frameWorkType=37;kn.create=function(i){let t=kn._create.call(this,_l,i);return t._use(pp,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Ft.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",dt,"created",Ft),t};Object.assign(kn.prototype,{_setCurrentSpeaker(i){let t=Ge("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return y(this,null,function*(){return this.startPlugin(pp.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.640028",hardwareAcceleration:"prefer-software",optimizeForLatency:!0},fallback:"wasm"}),new Promise((e,r)=>{Ae(be(i,"decode-downgrade-state-changed"),Qt(o=>o.state==="STARTED"),Hr(1),ep(1e4),ze(be(i,le.INIT)),Le(e,r))})})}});Xm(37);var NG=kn;export{NG as default};
|