trtc-sdk-v5 5.11.2-beta.6 → 5.11.2-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/device-detector.esm.d.ts +1 -0
- package/plugins/device-detector/device-detector.esm.js +17 -19
- package/plugins/device-detector/device-detector.umd.js +2 -2
- package/plugins/device-detector/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.d.ts +69 -13
- package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +29 -28
- package/trtc.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,r,t)=>r in e?__defProp(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t,__spreadValues=(e,r)=>{for(var t in r||(r={}))__hasOwnProp.call(r,t)&&__defNormalProp(e,t,r[t]);if(__getOwnPropSymbols)for(var t of __getOwnPropSymbols(r))__propIsEnum.call(r,t)&&__defNormalProp(e,t,r[t]);return e},__publicField=(e,r,t)=>__defNormalProp(e,"symbol"!=typeof r?r+"":r,t),layerProperty={x:{required:!1,type:"number"},y:{required:!1,type:"number"},width:{required:!1,type:"number",notLessThanZero:!0,min:1},height:{required:!1,type:"number",notLessThanZero:!0,min:1}};function startValidateRule(e){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{container:{type:"object",required:!0,properties:{width:{required:!0,type:"number",notLessThanZero:!0,min:1},height:{required:!0,type:"number",notLessThanZero:!0,min:1}}},camera:{type:"object",required:!1,properties:__spreadValues({},layerProperty)},screen:{type:"object",required:!1,properties:__spreadValues({},layerProperty)}}}}function updateValidateRule(e){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{container:{type:"object",required:!1,properties:{width:{required:!0,type:"number",notLessThanZero:!0,min:1},height:{required:!0,type:"number",notLessThanZero:!0,min:1}}},camera:{type:"object",required:!1,properties:__spreadValues({},layerProperty)},screen:{type:"object",required:!1,properties:__spreadValues({},layerProperty)}}}}function stopValidateRule(e){return{name:"StopVideoMixerOptions",required:!1}}var videoMixSeq=0,_VideoMixer=class e{constructor(e){this.core=e,__publicField(this,"seq"),__publicField(this,"log"),videoMixSeq+=1,this.seq=videoMixSeq,this.log=e.log.createChild({id:`${this.getAlias()}${videoMixSeq}`}),this.log.info("created")}getName(){return e.Name}getAlias(){return"vmix"}getValidateRule(e){switch(e){case"start":return startValidateRule(this.core);case"update":return updateValidateRule(this.core);case"stop":return stopValidateRule(this.core)}}getGroup(){return"vmix"}get subStream(){return this.core.trtc.getVideoTrack({streamType:this.core.TRTC.TYPE.STREAM_TYPE_SUB})}get mainStream(){return this.core.trtc.getVideoTrack()}start(e={}){return this.subStream&&(this.core.trtc.updateScreenShare({publish:!1}),this.core.trtc.updateLocalVideo({publish:!0})),this.core.trtc.on(this.core.TRTC.EVENT.PUBLISH_STATE_CHANGED,this.stopSubStream,this),this.core.room.videoManager.setVideoMixer(e)}update(e){return this.core.room.videoManager.updateVideoMixer(e)}stop(){return this.core.trtc.off(this.core.TRTC.EVENT.PUBLISH_STATE_CHANGED,this.stopSubStream,this),this.subStream&&this.core.trtc.updateScreenShare({publish:!0}),this.core.room.videoManager.deleteVideoMixer()}stopSubStream(e){const{mediaType:r,state:t,reason:i}=e;"screen"===r&&"started"===t&&(this.core.trtc.updateScreenShare({publish:!1}),this.core.trtc.updateLocalVideo({publish:!0}))}};__publicField(_VideoMixer,"Name","VideoMixer");var VideoMixer=_VideoMixer,index_default=VideoMixer;export{index_default as default};export{VideoMixer};
|
|
1
|
+
var __create=Object.create,__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropNames=Object.getOwnPropertyNames,__getOwnPropSymbols=Object.getOwnPropertySymbols,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=(e,t,i)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,__spreadValues=(e,t)=>{for(var i in t||(t={}))__hasOwnProp.call(t,i)&&__defNormalProp(e,i,t[i]);if(__getOwnPropSymbols)for(var i of __getOwnPropSymbols(t))__propIsEnum.call(t,i)&&__defNormalProp(e,i,t[i]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t)),__commonJS=(e,t)=>function(){return t||(0,e[__getOwnPropNames(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var i in t)__defProp(e,i,{get:t[i],enumerable:!0})},__copyProps=(e,t,i,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of __getOwnPropNames(t))__hasOwnProp.call(e,s)||s===i||__defProp(e,s,{get:()=>t[s],enumerable:!(r=__getOwnPropDesc(t,s))||r.enumerable});return e},__toESM=(e,t,i)=>(i=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?i:__defProp(i,"default",{value:e,enumerable:!0}),e)),__decorateClass=(e,t,i,r)=>{for(var s,n=r>1?void 0:r?__getOwnPropDesc(t,i):t,a=e.length-1;a>=0;a--)(s=e[a])&&(n=(r?s(t,i,n):s(n))||n);return r&&n&&__defProp(t,i,n),n},__publicField=(e,t,i)=>__defNormalProp(e,"symbol"!=typeof t?t+"":t,i),require_eventemitter3=__commonJS({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,t){"use strict";var i=Object.prototype.hasOwnProperty,r="~";function s(){}function n(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,i,s,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,s||e,a),d=r?r+t:t;return e._events[d]?e._events[d].fn?e._events[d]=[e._events[d],o]:e._events[d].push(o):(e._events[d]=o,e._eventsCount++),e}function o(e,t){0==--e._eventsCount?e._events=new s:delete e._events[t]}function d(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(r=!1)),d.prototype.eventNames=function(){var e,t,s=[];if(0===this._eventsCount)return s;for(t in e=this._events)i.call(e,t)&&s.push(r?t.slice(1):t);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},d.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},d.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},d.prototype.emit=function(e,t,i,s,n,a){var o=r?r+e:e;if(!this._events[o])return!1;var d,l,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,i),!0;case 4:return c.fn.call(c.context,t,i,s),!0;case 5:return c.fn.call(c.context,t,i,s,n),!0;case 6:return c.fn.call(c.context,t,i,s,n,a),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var h,_=c.length;for(l=0;l<_;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,i);break;case 4:c[l].fn.call(c[l].context,t,i,s);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];c[l].fn.apply(c[l].context,d)}}return!0},d.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},d.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},d.prototype.removeListener=function(e,t,i,s){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==t||s&&!a.once||i&&a.context!==i||o(this,n);else{for(var d=0,l=[],c=a.length;d<c;d++)(a[d].fn!==t||s&&!a[d].once||i&&a[d].context!==i)&&l.push(a[d]);l.length?this._events[n]=1===l.length?l[0]:l:o(this,n)}return this},d.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&o(this,t)):(this._events=new s,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=r,d.EventEmitter=d,void 0!==t&&(t.exports=d)}}),require_grammar=__commonJS({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/grammar.js"(e,t){"use strict";var i=t.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(e){return e.encoding?"rtpmap:%d %s/%s/%s":e.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(e){return null!=e.address?"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(e){return null!=e.subtype?"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(e){return"extmap:%d"+(e.direction?"/%s":"%v")+(e["encrypt-uri"]?" %s":"%v")+" %s"+(e.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(e){return null!=e.sessionConfig?"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(e){var t="candidate:%s %d %s %d %s %d typ %s";return t+=null!=e.raddr?" raddr %s rport %d":"%v%v",t+=null!=e.tcptype?" tcptype %s":"%v",null!=e.generation&&(t+=" generation %d"),t+=null!=e["network-id"]?" network-id %d":"%v",t+=null!=e["network-cost"]?" network-cost %d":"%v"}},{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(e){var t="ssrc:%d";return null!=e.attribute&&(t+=" %s",null!=e.value&&(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(e){return null!=e.maxMessageSize?"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(e){return e.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(e){return"imageattr:%s %s %s"+(e.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(e){return"simulcast:%s %s"+(e.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(e){return"ts-refclk:%s"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){var t="mediaclk:";return t+=null!=e.id?"id=%s %s":"%v%s",t+=null!=e.mediaClockValue?"=%s":"",t+=null!=e.rateNumerator?" rate=%s":"",t+=null!=e.rateDenominator?"/%s":""}},{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(i).forEach((function(e){i[e].forEach((function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")}))}))}}),require_parser=__commonJS({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/parser.js"(e){"use strict";var t=function(e){return String(Number(e))===e?Number(e):e},i=function(e,i,r){var s=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:s&&!i[e.name]&&(i[e.name]={});var n=e.push?{}:s?i[e.name]:i;!function(e,i,r,s){if(s&&!r)i[s]=t(e[1]);else for(var n=0;n<r.length;n+=1)null!=e[n+1]&&(i[r[n]]=t(e[n+1]))}(r.match(e.reg),n,e.names,e.name),e.push&&i[e.push].push(n)},r=require_grammar(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],a=t;return e.split(/(\r\n|\r|\n)/).filter(s).forEach((function(e){var t=e[0],s=e.slice(2);"m"===t&&(n.push({rtp:[],fmtp:[]}),a=n[n.length-1]);for(var o=0;o<(r[t]||[]).length;o+=1){var d=r[t][o];if(d.reg.test(s))return i(d,a,s)}})),t.media=n,t};var n=function(e,i){var r=i.split(/=(.+)/,2);return 2===r.length?e[r[0]]=t(r[1]):1===r.length&&i.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(n,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(e){for(var i=[],r=e.split(" ").map(t),s=0;s<r.length;s+=3)i.push({component:r[s],ip:r[s+1],port:r[s+2]});return i},e.parseImageAttributes=function(e){return e.split(" ").map((function(e){return e.substring(1,e.length-1).split(",").reduce(n,{})}))},e.parseSimulcastStreamList=function(e){return e.split(";").map((function(e){return e.split(",").map((function(e){var i,r=!1;return"~"!==e[0]?i=t(e):(i=t(e.substring(1,e.length)),r=!0),{scid:i,paused:r}}))}))}}}),require_writer=__commonJS({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(e,t){"use strict";var i=require_grammar(),r=/%[sdv%]/g,s=function(e){var t=1,i=arguments,s=i.length;return e.replace(r,(function(e){if(t>=s)return e;var r=i[t];switch(t+=1,e){case"%%":return"%";case"%s":return String(r);case"%d":return Number(r);case"%v":return""}}))},n=function(e,t,i){var r=[e+"="+(t.format instanceof Function?t.format(t.push?i:i[t.name]):t.format)];if(t.names)for(var n=0;n<t.names.length;n+=1){var a=t.names[n];t.name?r.push(i[t.name][a]):r.push(i[t.names[n]])}else r.push(i[t.name]);return s.apply(null,r)},a=["v","o","s","i","u","e","p","c","b","t","r","z","a"],o=["i","c","b","a"];t.exports=function(e,t){t=t||{},null==e.version&&(e.version=0),null==e.name&&(e.name=" "),e.media.forEach((function(e){null==e.payloads&&(e.payloads="")}));var r=t.outerOrder||a,s=t.innerOrder||o,d=[];return r.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?d.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){d.push(n(t,i,e))}))}))})),e.media.forEach((function(e){d.push(n("m",i.m[0],e)),s.forEach((function(t){i[t].forEach((function(i){i.name in e&&null!=e[i.name]?d.push(n(t,i,e)):i.push in e&&null!=e[i.push]&&e[i.push].forEach((function(e){d.push(n(t,i,e))}))}))}))})),d.join("\r\n")+"\r\n"}}}),require_lib=__commonJS({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js"(e){"use strict";var t=require_parser(),i=require_writer(),r=require_grammar();e.grammar=r,e.write=i,e.parse=t.parse,e.parseParams=t.parseParams,e.parseFmtpConfig=t.parseFmtpConfig,e.parsePayloads=t.parsePayloads,e.parseRemoteCandidates=t.parseRemoteCandidates,e.parseImageAttributes=t.parseImageAttributes,e.parseSimulcastStreamList=t.parseSimulcastStreamList}}),utils_exports={};__export(utils_exports,{bytes2ms:()=>bytes2ms,calculateScaleResolutionDownNumber:()=>calculateScaleResolutionDownNumber,convertObjectNumberToInt:()=>convertObjectNumberToInt,copyProperties:()=>copyProperties,deepClone:()=>deepClone,deepMerge:()=>deepMerge,delay:()=>delay,fibonacci:()=>fibonacci,formatedTime:()=>formatedTime,getConstructorName:()=>getConstructorName,getContainerFromElement:()=>getContainerFromElement,getEnv:()=>getEnv,getInternalVersion:()=>getInternalVersion,getLoggerUrl:()=>getLoggerUrl,getMediaStreamTrackInfo:()=>getMediaStreamTrackInfo,getMuteStateFromFlag:()=>getMuteStateFromFlag,getNetworkType:()=>getNetworkType,getNumNetworkType:()=>getNumNetworkType,getReconnectionTimeout:()=>getReconnectionTimeout,getStringByteLength:()=>getStringByteLength,getTurnServer:()=>getTurnServer,getUint32Version:()=>getUint32Version,getValueType:()=>getValueType,getViewListFromView:()=>getViewListFromView,glog:()=>glog,ipv4ToUint32:()=>ipv4ToUint32,isArray:()=>isArray,isAudioWorkletSupported:()=>isAudioWorkletSupported,isBoolean:()=>isBoolean,isConstructor:()=>isConstructor,isEmpty:()=>isEmpty,isFunction:()=>isFunction,isLangChinese:()=>isLangChinese,isMediaStreamTrack:()=>isMediaStreamTrack,isNumber:()=>isNumber,isObject:()=>isObject,isOverseaSdkAppId:()=>isOverseaSdkAppId,isPlainObject:()=>isPlainObject,isPortrait:()=>isPortrait,isPromise:()=>isPromise,isRemoteTrack:()=>isRemoteTrack,isRotate90Or270:()=>isRotate90Or270,isString:()=>isString,isUndefined:()=>isUndefined,loadImage:()=>loadImage,loadVideo:()=>loadVideo,ms2bytes:()=>ms2bytes,ms2samples:()=>ms2samples,normalizeUrl:()=>normalizeUrl,performanceNow:()=>performanceNow,promiseAny:()=>promiseAny,samples2ms:()=>samples2ms,setNetworkType:()=>setNetworkType,stringify:()=>stringify,stringifyIncludeValue:()=>stringifyIncludeValue,throttlePromise:()=>throttlePromise});var version="5.0.0",IS_WORKER="undefined"!=typeof importScripts,IS_WORKLET="undefined"!=typeof registerProcessor,loggerProxy="",BASE_HOST="web.sdk.qcloud.com",BASE_DOC_URL=`https://${BASE_HOST}/trtc/webrtc/v5/doc`,DOC_URL=`${BASE_DOC_URL}/zh-cn/`,LOGGER_DOMAIN="https://yun.tim.qq.com",LOGGER_DOMAIN_OVERSEA="https://apisgp.my-imcloud.com",TRTC_ERROR_ASSISTANCE="trtc_error_assistance",LOGGER_CMD_TYPE={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ENV_NAME={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},LOG_LEVEL=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(LOG_LEVEL||{}),NETWORK_TYPE={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},STORAGE_EXPIRES_TIME=6048e5,videoProfileMap={"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}},defaultBigVideoProfile=videoProfileMap["480p_2"],defaultSmallVideoProfile=videoProfileMap["120p_2"],screenProfileMap={"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}},NAME={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"},VIDEO_STAT_BIT=1,SMALL_STAT_BIT=2,AUX_STAT_BIT=4,AUDIO_STAT_BIT=8,AUDIO_MUTE_BIT=64,VIDEO_MUTE_BIT=16,REMOTE_STREAM_TYPE_MAIN=NAME.MAIN,REMOTE_STREAM_TYPE_AUX=NAME.AUXILIARY,KIBANA_EVENT={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"},SDP_SEMANTICS_UNIFIED_PLAN="unified-plan",STREAM_TYPE_BIG=NAME.BIG,STREAM_TYPE_SMALL=NAME.SMALL,PEERCONNECTION_CONNECTING_TIMEOUT=1e4,PAUSED_RETRY_COUNT=5,MICROPHONE_DEFAULT="default",LOG_LEVEL_NAME=Object.keys(LOG_LEVEL),RECOVER_CAPTURE_INTERVAL=2e3,CAPABILITIES_KEYS=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],MAX_RTT=1e4,ErrorCode=(e=>(e[e.INVALID_PARAMETER=4096]="INVALID_PARAMETER",e[e.INVALID_OPERATION=4097]="INVALID_OPERATION",e[e.NOT_SUPPORTED=4098]="NOT_SUPPORTED",e[e.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",e[e.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",e[e.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",e[e.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",e[e.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",e[e.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",e[e.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",e[e.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",e[e.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",e[e.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",e[e.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",e[e.CLIENT_BANNED=16448]="CLIENT_BANNED",e[e.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",e[e.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",e[e.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",e[e.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",e[e.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",e[e.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",e[e.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",e[e.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",e[e.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",e[e.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",e[e.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",e[e.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",e[e.API_CALL_ABORTED=16461]="API_CALL_ABORTED",e[e.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",e[e.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",e[e.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",e[e.UNKNOWN=65535]="UNKNOWN",e))(ErrorCode||{}),error_code_default=ErrorCode,getErrorName=function(e){for(const t in error_code_default)if(error_code_default[t]===e)return t;return"UNKNOWN"},RtcError=class extends Error{constructor({name:e="RtcError",message:t,code:i=error_code_default.UNKNOWN,extraCode:r=0,constraint:s}){const n=`<${getErrorName(i)} 0x${i.toString(16)}>`,a=`${t}${s?` constraint: ${s}`:""}${(null==t?void 0:t.includes(n))?"":` ${n}`}`;super(a),__publicField(this,"code"),__publicField(this,"extraCode"),__publicField(this,"message"),__publicField(this,"originMessage"),__publicField(this,"name"),__publicField(this,"constraint"),this.code=i,this.extraCode=r,this.name=e,this.message=a,this.constraint=s,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},rtc_error_default=RtcError,getEnv=function(){return new URLSearchParams(location.search).get("trtc_env")||""},isOverseaSdkAppId=e=>Number(e)<14e8,getLoggerUrl=function(e,t){let i;i=loggerProxy||(isOverseaSdkAppId(e)?LOGGER_DOMAIN_OVERSEA:LOGGER_DOMAIN);return`${i}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${e}&cmdtype=${t}`},networkType="unknown";function getNetworkType(){if("unknown"!==networkType)return networkType;const{userAgent:e,connection:t}=navigator;let i=(e.match(/NetType\/\S+/)||[])[0]||"";i=i.toLowerCase().replace("nettype/",""),"3gnet"===i&&(i="3g");const r=t&&t.type&&t.type.toLowerCase();let s=t&&t.effectiveType&&t.effectiveType.toLowerCase();return"slow-2"===s&&(s="2g"),r&&(networkType=convertNetworkType(r,s)),networkType}function convertNetworkType(e,t){if(NETWORK_TYPE[e])return e;switch(e){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function setNetworkType(e){networkType=convertNetworkType(e)}function getNumNetworkType(){return NETWORK_TYPE[getNetworkType()]}function copyProperties(e,t){for(const i of Reflect.ownKeys(t))if("constructor"!==i&&"prototype"!==i&&"name"!==i){const r=Object.getOwnPropertyDescriptor(t,i)||"";Object.defineProperty(e,i,r)}return e}function bytes2ms(e,t=48e3){return samples2ms(e/4,t)}function samples2ms(e,t=48e3){return 1e3*e/t}function ms2bytes(e,t=48e3){return 4*ms2samples(e,t)}function ms2samples(e,t=48e3){return e*t/1e3}var glog="undefined"!=typeof window&&"function"==typeof window.glog?window.glog:()=>{},isLangChinese=()=>{let e=navigator.language;return e=e.substring(0,2),"zh"===e},isPlainObject=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;const i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function fibonacci(e,t=1,i=1){return e<=1?i:fibonacci(e-1,i,t+i)}function getReconnectionTimeout(e){return e>8?3e4:1e3*fibonacci(e)}function getValueType(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var isFunction=e=>"function"==typeof e,isUndefined=e=>void 0===e,isString=e=>"string"==typeof e,isNumber=e=>"number"==typeof e,isBoolean=e=>"boolean"==typeof e,isObject=e=>"object"===getValueType(e),isArray=e=>"array"===getValueType(e),isMediaStreamTrack=e=>getValueType(e)==="MediaStreamTrack".toLowerCase(),isRemoteTrack=e=>e.isRemote,isPromise=e=>"promise"===getValueType(e),isConstructor=e=>isFunction(e)&&e.prototype.constructor===e,getConstructorName=e=>isConstructor(e)?e.prototype.constructor.name:"",isAudioWorkletSupported="undefined"!=typeof AudioWorkletNode;function promiseAny(e){return new Promise(((t,i)=>{const r=[];e.forEach((s=>{s.then(t).catch((t=>{r.push(t),r.length===e.length&&i(r)}))}))}))}function performanceNow(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var fillZero=e=>+e<10?`0${e}`:e,getInternalVersion=e=>{const t=e.match(/^\d+\.\d+\.\d+/)[0];if(!t)return e;const i=t.split("."),r=fillZero(i[1])+fillZero(i[2]);i[1]-15>0&&(i[1]="15"),i[2]-15>0&&(i[2]="15");return`${i.join(".")}.${r}`},has=Object.prototype.hasOwnProperty,{toString:toString}=Object.prototype;function isEmpty(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(isPlainObject(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(const t in e)if(has.call(e,t))return!1;return!0}return!1}function getMuteStateFromFlag(e,t){return{userId:t,hasAudio:!!(e&AUDIO_STAT_BIT),hasVideo:!!(e&VIDEO_STAT_BIT),hasAuxiliary:!!(e&AUX_STAT_BIT),hasSmall:!!(e&SMALL_STAT_BIT),audioMuted:!!(e&AUDIO_MUTE_BIT),videoMuted:!!(e&VIDEO_MUTE_BIT),audioAvailable:!(!(e&AUDIO_STAT_BIT)||e&AUDIO_MUTE_BIT),videoAvailable:!(!(e&VIDEO_STAT_BIT)||e&VIDEO_MUTE_BIT)}}function getTurnServer(e){const t={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:`turn:${e.url}`};return isUndefined(e.username)||isUndefined(e.credential)||(t.username=e.username,t.credential=e.credential,t.credentialType="password",isUndefined(e.credentialType)||(t.credentialType=e.credentialType)),t}function ipv4ToUint32(e,t=!0){if(!isString(e))return 0;const i=e.split(".");return t?(Number(i[0])<<24|Number(i[1])<<16|Number(i[2])<<8|Number(i[3]))>>>0:(Number(i[3])<<24|Number(i[2])<<16|Number(i[1])<<8|Number(i[0]))>>>0}var deepMerge=function(e,t,i,r){if(!isObject(e)||!isObject(t))return 0;let s=0;const n=Object.keys(t);let a;for(let o=0,d=n.length;o<d;o++)if(a=n[o],!(isUndefined(t[a])||i&&i.includes(a)))if(isObject(e[a])&&isObject(t[a]))s+=deepMerge(e[a],t[a],i,r);else{if(r&&r.includes(t[a]))continue;e[a]!==t[a]&&(e[a]=deepClone(t[a]),s+=1)}return s};function deepClone(e){if(isArray(e)){const t=[];return e.forEach(((e,i)=>{t[i]=deepClone(e)})),t}if(isObject(e)){const t={};return Object.keys(e).forEach((i=>{t[i]=deepClone(e[i])})),t}return e}var getViewListFromView=e=>{let t=[];if(isArray(e))t=[...e];else if(isString(e)){const i=document.getElementById(e);i&&t.push(i)}else e&&t.push(e);return t},getContainerFromElement=e=>isString(e)?document.getElementById(e):e,formater=e=>{const t=e=>e<10?`0${e}`:`${e}`;return`${e.getFullYear()}/${e.getMonth()+1}/${e.getDate()} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`},formatedTime=()=>formater(new Date);function stringify(e,{keysToInclude:t,keysToExclude:i}){try{if(isArray(e))return`[${e.map((e=>stringify(e,{keysToInclude:t,keysToExclude:i}))).join(",")}]`;if(!isPlainObject(e)||!isArray(t)&&!isArray(i))return JSON.stringify(e);const r={},s=new Set(t),n=new Set(i);return Object.keys(e).forEach((a=>{(0===n.size&&s.has(a)||0===s.size&&!n.has(a))&&(r[a]=isPlainObject(e[a])||isArray(e[a])?JSON.parse(stringify(e[a],{keysToExclude:i,keysToInclude:t})):e[a])})),JSON.stringify(r)}catch(e){return"{}"}}function stringifyIncludeValue(e,t=!1){const i=[];return Object.keys(e).forEach((r=>{t===e[r]&&i.push(r)})),stringify(e,{keysToInclude:i})}function getStringByteLength(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var isPortrait=()=>{var e,t,i,r;return(null==(e=window.screen)?void 0:e.orientation)?!!(null==(r=null==(i=null==(t=window.screen)?void 0:t.orientation)?void 0:i.type)?void 0:r.includes("portrait")):0===window.orientation||180===window.orientation},loadImage=async e=>new Promise(((t,i)=>{let r;if(isString(e))r=new Image,r.crossOrigin="anonymous",r.src=e;else if(r=e,r.complete)return void t(r);r.onload=()=>t(r),r.onerror=()=>{i(new rtc_error_default({code:error_code_default.INVALID_PARAMETER,message:`load image failed, url: ${e}`}))}})),getUint32Version=e=>{const t=e.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},convertObjectNumberToInt=e=>(Object.keys(e).forEach((t=>{isNumber(e[t])&&(t.startsWith("uint")||t.startsWith("int"))?e[t]=Math.floor(e[t]):(isPlainObject(e[t])||isArray(e[t]))&&convertObjectNumberToInt(e[t])})),e);function delay(e,t){return new Promise((i=>{const r=setTimeout(i,e);t&&t(r)}))}function throttlePromise(e,t){let i=null;return function(...r){return i||(i=e.apply(t||this,r),i.finally((()=>i=null)),i)}}function normalizeUrl(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function getMediaStreamTrackInfo(e){var t;try{const{width:i,height:r,frameRate:s,sampleRate:n,sampleSize:a,channelCount:o}=null==(t=e.getSettings)?void 0:t.call(e),d=e.kind===NAME.AUDIO?`${n}x${a}@${o}`:`${i}x${r}@${s}`,l=e.stats?` stats: ${JSON.stringify(e.stats).replaceAll('"',"")}`:"";return`${e.id} ${e.readyState} muted:${e.muted} ${e.kind} ${e.label} ${d}${l}`}catch(e){return""}}function calculateScaleResolutionDownNumber(e,t){return e.width*e.height==t.width*t.height?1:isPortrait()&&t.width>t.height&&e.height>t.width?Math.max(e.width/t.height,e.height/t.width,1):Math.max(e.width/t.width,e.height/t.height,1)}function isRotate90Or270(e){return 90===e||270===e}async function loadVideo(e){return new Promise(((t,i)=>{const r=document.createElement("video");r.crossOrigin="anonymous",r.src=e,r.muted=!0,r.loop=!0,r.playsInline=!0,r.play(),r.onloadeddata=()=>{t(r)},r.onerror=()=>{i(r.error)}}))}var rtc_detection_exports={};__export(rtc_detection_exports,{HTTPS_API:()=>HTTPS_API,IS_GET_CAPABILITIES_SUPPORTED:()=>IS_GET_CAPABILITIES_SUPPORTED,IS_GET_SETTINGS_SUPPORTED:()=>IS_GET_SETTINGS_SUPPORTED,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED,IS_INSERTABLE_STREAM_SUPPORTED:()=>IS_INSERTABLE_STREAM_SUPPORTED,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>IS_JITTER_BUFFER_TARGET_SUPPORTED,IS_RTC_RTP_SENDER_SUPPORTED:()=>IS_RTC_RTP_SENDER_SUPPORTED,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>IS_SCRIPT_TRANSFORM_SUPPORTED,IS_SEI_SUPPORTED:()=>IS_SEI_SUPPORTED,IS_SPC_SUPPORTED:()=>IS_SPC_SUPPORTED,basis:()=>basis,capabilityCheck:()=>capabilityCheck,checkSystemRequirementsInternal:()=>checkSystemRequirementsInternal,decodeSupportStatus:()=>decodeSupportStatus,encodeSupportStatus:()=>encodeSupportStatus,getBrowserInfo:()=>getBrowserInfo2,getDisplayResolution:()=>getDisplayResolution,isAddTransceiverSupported:()=>isAddTransceiverSupported,isBrowserSupported:()=>isBrowserSupported,isCanvasCaptureStreamAPISupported:()=>isCanvasCaptureStreamAPISupported,isCanvasSmallStreamSupported:()=>isCanvasSmallStreamSupported,isGetReceiversSupported:()=>isGetReceiversSupported,isGetSendersSupported:()=>isGetSendersSupported,isGetTransceiversSupported:()=>isGetTransceiversSupported,isGetUserMediaSupported:()=>isGetUserMediaSupported,isMediaDevicesSupported:()=>isMediaDevicesSupported,isMediaSessionSupported:()=>isMediaSessionSupported,isMediaStreamTrackProcessorSupported:()=>isMediaStreamTrackProcessorSupported,isReplaceTrackSupported:()=>isReplaceTrackSupported,isRequestVideoFrameCallbackSupported:()=>isRequestVideoFrameCallbackSupported,isSIMDSupported:()=>isSIMDSupported,isScaleResolutionDownBySupported:()=>isScaleResolutionDownBySupported,isScreenCaptureApiAvailable:()=>isScreenCaptureApiAvailable,isSelectedCandidatePair:()=>isSelectedCandidatePair,isSetParametersSupported:()=>isSetParametersSupported,isSmallStreamSupported:()=>isSmallStreamSupported,isStopTransceiverSupported:()=>isStopTransceiverSupported,isTRTCSupported:()=>isTRTCSupported,isUnifiedPlanDefault:()=>isUnifiedPlanDefault,isUsedInHttpProtocol:()=>isUsedInHttpProtocol,isWebAudioSupported:()=>isWebAudioSupported,isWebCodecSupported:()=>isWebCodecSupported,isWebCodecsSupported:()=>isWebCodecsSupported,isWebRTCSupported:()=>isWebRTCSupported,isWebTransportSupported:()=>isWebTransportSupported});var USER_AGENT="undefined"==typeof navigator?"":navigator.userAgent,isUserAgentMatch=e=>new RegExp(e,"i").test(USER_AGENT),getBrowserVersion=e=>{if(isUserAgentMatch(e)){const t=new RegExp(`${e}\\/([\\d.]+)`),i=USER_AGENT.match(t);if(i&&i[1])return i[1]}return""},getBrowserMajorVersion=e=>{if(isUserAgentMatch(e)){const t=new RegExp(`${e}\\/(\\d+)`),i=USER_AGENT.match(t);if(i&&i[1])return parseFloat(i[1])}return NaN},webkitVersionMap=/AppleWebKit\/([\d.]+)/i.exec(USER_AGENT),appleWebkitVersion=webkitVersionMap?parseFloat(webkitVersionMap[1]):NaN,IS_IPAD=isUserAgentMatch("iPad"),IS_IPAD_PRO="undefined"!=typeof navigator&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&isUserAgentMatch("Macintosh"),IS_IPHONE=isUserAgentMatch("iPhone")&&!IS_IPAD,IS_IPOD=isUserAgentMatch("iPod"),IS_IOS=IS_IPHONE||IS_IPAD||IS_IPOD||IS_IPAD_PRO,IS_ANDROID=isUserAgentMatch("Android"),ANDROID_VERSION=function(){if(IS_ANDROID){const e=USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){const t=e[1]&&parseFloat(e[1]),i=e[2]&&parseFloat(e[2]);if(t&&i)return parseFloat(`${e[1]}.${e[2]}`);if(t)return t}}return NaN}(),IS_OLD_ANDROID=IS_ANDROID&&isUserAgentMatch("webkit")&&ANDROID_VERSION<2.3,IS_NATIVE_ANDROID=IS_ANDROID&&ANDROID_VERSION<5&&appleWebkitVersion<537,IS_FIREFOX=isUserAgentMatch("Firefox"),FIREFOX_VERSION=getBrowserVersion("Firefox"),FIREFOX_MAJOR_VERSION=getBrowserMajorVersion("Firefox"),IS_EDGE=isUserAgentMatch("Edge"),EDGE_VERSION=getBrowserVersion("Edge"),IS_EDG=isUserAgentMatch("Edg"),EDG_VERSION=getBrowserVersion("Edg"),EDG_MAJOR_VERSION=getBrowserMajorVersion("Edg"),IS_SOGOUM=isUserAgentMatch("SogouMobileBrowser"),SOGOUM_VERSION=getBrowserVersion("SogouMobileBrowser"),IS_SOGOU=isUserAgentMatch("MetaSr\\s"),SOGOU_VERSION=getBrowserVersion("MetaSr\\s"),IS_TBS=isUserAgentMatch("TBS"),TBS_VERSION=getBrowserVersion("TBS"),IS_XWEB=isUserAgentMatch("XWEB"),XWEB_VERSION=getBrowserVersion("XWEB"),IS_IE8=isUserAgentMatch("MSIE\\s8\\.0"),IS_IE=isUserAgentMatch("MSIE\\/\\d+"),IE_VERSION=function(){if(IS_IE){const e=/MSIE\s(\d+)\.\d/.exec(USER_AGENT);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(USER_AGENT)&&/rv:11.0/.test(USER_AGENT)&&(t=11),t}return NaN}(),IS_WECHAT=isUserAgentMatch("(micromessenger|webbrowser)"),WECHAT_VERSION=getBrowserVersion("MicroMessenger"),IS_X5MQQB=!IS_TBS&&isUserAgentMatch("MQQBrowser")&&isUserAgentMatch("COVC"),IS_MQQB=!IS_TBS&&isUserAgentMatch("MQQBrowser")&&!isUserAgentMatch("COVC"),MQQB_VERSION=IS_MQQB||IS_X5MQQB?getBrowserVersion("MQQBrowser"):"",IS_WQQB=!IS_TBS&&isUserAgentMatch(" QQBrowser"),WQQB_VERSION=getBrowserVersion(" QQBrowser"),IS_MACQQB=!IS_TBS&&isUserAgentMatch("QQBrowserLite"),MACQQB_VERSION=getBrowserVersion("QQBrowserLite"),IS_IPADQQB=!IS_TBS&&isUserAgentMatch("MQBHD"),IPADQQB_VERSION=getBrowserVersion("MQBHD"),IS_WIN=isUserAgentMatch("Windows"),IS_MAC=!IS_IOS&&isUserAgentMatch("MAC OS X"),IS_LINUX=!IS_ANDROID&&isUserAgentMatch("Linux"),IS_CHROME_OS=isUserAgentMatch("CrOS"),IS_WX=isUserAgentMatch("MicroMessenger"),IS_UCBROWSER=isUserAgentMatch("UCBrowser"),IS_ELECTRON=isUserAgentMatch("Electron"),IS_MIBROWSER=isUserAgentMatch("MiuiBrowser"),MI_VERSION=getBrowserVersion("MiuiBrowser"),IS_HUAWEIBROWSER=isUserAgentMatch("HuaweiBrowser"),IS_HUAWEI=isUserAgentMatch("Huawei")||isUserAgentMatch("HUAWEI"),IS_HONOR=isUserAgentMatch("Honor")||isUserAgentMatch("HONOR"),HUAWEI_VERSION=getBrowserVersion("HuaweiBrowser"),IS_SAMSUNGBROWSER=isUserAgentMatch("SamsungBrowser"),SAMSUNG_VERSION=getBrowserVersion("SamsungBrowser"),IS_OPPOBROWSER=isUserAgentMatch("HeyTapBrowser"),OPPO_VERSION=getBrowserVersion("HeyTapBrowser"),IS_VIVOBROWSER=isUserAgentMatch("VivoBrowser"),VIVO_VERSION=getBrowserVersion("VivoBrowser"),IS_OPENHARMONY=isUserAgentMatch("OpenHarmony"),OPENHARMONY_VERSION=getBrowserVersion("OpenHarmony"),getChromeMajorVersion=()=>getBrowserMajorVersion("Chrome"),IS_CHROMIUM_BASE=isUserAgentMatch("Chrome"),IS_CHROME=!IS_EDGE&&!IS_SOGOU&&!IS_SOGOUM&&!IS_TBS&&!IS_XWEB&&!IS_EDG&&!IS_WQQB&&!IS_MIBROWSER&&!IS_HUAWEIBROWSER&&!IS_SAMSUNGBROWSER&&!IS_OPPOBROWSER&&!IS_VIVOBROWSER&&IS_CHROMIUM_BASE,IS_HEADLESS_CHROME=isUserAgentMatch("HeadlessChrome"),CHROME_MAJOR_VERSION=getChromeMajorVersion(),CHROME_VERSION=getBrowserVersion("Chrome"),IS_SAFARI=!IS_CHROMIUM_BASE&&!IS_MQQB&&!IS_X5MQQB&&!IS_MACQQB&&!IS_IPADQQB&&isUserAgentMatch("Safari"),IS_ANY_SAFARI=IS_SAFARI||IS_IOS,SAFARI_VERSION=getBrowserVersion("Version"),IS_ANDROID_WEBVIEW=/Android.*(wv|.0.0.0)/.test(USER_AGENT),IOS_VERSION=(()=>{if(IS_IPAD_PRO)return SAFARI_VERSION;if(IS_IOS){const e=USER_AGENT.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let t=e[1];return e[2]&&(t+=`.${e[2]}`),t}}return""})();function isVersionSmallerThan(e,t){const i=e.split(".").map((e=>Number(e))),r=t.split(".").map((e=>Number(e)));for(let e=0;e<Math.max(i.length,r.length);e++){const t=i[e]||0,s=r[e]||0;if(t<s)return!0;if(t>s)return!1}return!1}function isVersionLargerThan(e,t,i=!1){const r=e.split(".").map((e=>Number(e))),s=t.split(".").map((e=>Number(e)));for(let e=0;e<Math.max(r.length,s.length);e++){const t=r[e]||0,i=s[e]||0;if(t>i)return!0;if(t<i)return!1}return i}var IOS_MAIN_VERSION=Number(IOS_VERSION.split(".")[0]),IS_IOS_15_1="15.1"===IOS_VERSION,IS_IOS_13_OR_14=(()=>{const e=Number(IOS_VERSION.split(".")[0]);return 14===e||13===e})(),IS_IOS_CHROME=isUserAgentMatch("CriOS"),IS_DESKTOP_IOS_CHROME=IS_IOS_CHROME&&"11.1.1"===SAFARI_VERSION,IS_LOCAL="undefined"!=typeof location&&("file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname),isLocalStorageEnabled=(()=>{let e;return()=>{if(void 0===e)try{e=!!window.localStorage}catch(t){e=!1}return e}})(),browserInfo=getBrowserInfo();function getBrowserInfo(){const e=new Map([[IS_FIREFOX,["Firefox",FIREFOX_VERSION]],[IS_EDG,["Edg",EDG_VERSION]],[IS_CHROME,["Chrome",CHROME_VERSION]],[IS_SAFARI,["Safari",SAFARI_VERSION]],[IS_TBS,["TBS",TBS_VERSION]],[IS_XWEB,["XWEB",XWEB_VERSION]],[IS_WECHAT&&IS_IPHONE,["WeChat",WECHAT_VERSION]],[IS_WQQB,["QQ(Win)",WQQB_VERSION]],[IS_MQQB,["QQ(Mobile)",MQQB_VERSION]],[IS_X5MQQB,["QQ(Mobile X5)",MQQB_VERSION]],[IS_MACQQB,["QQ(Mac)",MACQQB_VERSION]],[IS_IPADQQB,["QQ(iPad)",IPADQQB_VERSION]],[IS_MIBROWSER,["MI",MI_VERSION]],[IS_HUAWEIBROWSER,["HW",HUAWEI_VERSION]],[IS_SAMSUNGBROWSER,["Samsung",SAMSUNG_VERSION]],[IS_OPPOBROWSER,["OPPO",OPPO_VERSION]],[IS_VIVOBROWSER,["VIVO",VIVO_VERSION]],[IS_EDGE,["EDGE",EDGE_VERSION]],[IS_SOGOUM,["SogouMobile",SOGOUM_VERSION]],[IS_SOGOU,["Sogou",SOGOU_VERSION]]]);let t="unknown",i="unknown";return e.has(!0)&&([t,i]=e.get(!0)),{name:t,version:i}}var userAgentData=null;function isMobile(){return userAgentData&&"boolean"==typeof userAgentData.mobile?userAgentData.mobile:IS_ANDROID||IS_IOS||IS_IPHONE||IS_IPAD||IS_OPENHARMONY}var UA_DATA_STRING="";function getDeviceModel(){return(null==userAgentData?void 0:userAgentData.model)||""}var OSNameMap=new Map([[IS_ANDROID,"Android"],[IS_IOS,"iOS"],[IS_WIN,"Windows"],[IS_MAC,"MacOS"],[IS_LINUX,"Linux"],[IS_CHROME_OS,"ChromeOS"]]),getOSName=function(){return OSNameMap.get(!0)?OSNameMap.get(!0):userAgentData?userAgentData.platform:"unknown"};function getOSNumber(){return IS_WIN?1:IS_ANDROID?2:IS_MAC?3:IS_IOS?4:IS_LINUX?5:IS_CHROME_OS?6:0}var getOSString=()=>{let e=getOSName();return e+=`/${browserInfo.name}/${IS_SAFARI?browserInfo.version:browserInfo.version.split(".")[0]}`,(null==userAgentData?void 0:userAgentData.platformVersion)&&(e+=`/${userAgentData.platformVersion}`),(null==userAgentData?void 0:userAgentData.architecture)&&(e+=`/${userAgentData.architecture}`),e},ErrorName={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"},ErrorInfo={AVOID_REPEATED_CALL:e=>`previous ${e.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:e,rule:t,fnName:i,value:r})=>`'${e||t.name}' is a required param when calling ${i}(), received: ${r}.`,INVALID_PARAMETER_TYPE({key:e,rule:t,fnName:i,value:r}){const s=`${e||t.name}`;let n="";return n=Array.isArray(t.type)?t.type.join("|"):t.type,`'${s}' must be type of ${n} when calling ${i}(), received type: ${getValueType(r)}.`},INVALID_PARAMETER_EMPTY:({key:e,rule:t,fnName:i,value:r})=>`'${e||t.name}' cannot be '${r}' when calling ${i}().`,INVALID_PARAMETER_INSTANCE:({key:e,rule:t,fnName:i,value:r})=>`'${`${e||t.name}`}' must be instanceof ${`${t.instanceOf.name||t.instanceOf}`} when calling ${i}(), received type: ${getValueType(r)}.`,INVALID_PARAMETER_RANGE:({key:e,rule:t,fnName:i,value:r})=>`'${e||t.name}' must be one of ${t.values.join("|")} when calling ${i}(), received: ${r}.`,INVALID_PARAMETER_MIN:({key:e,rule:t,fnName:i,value:r})=>`the min value of ${e||t.name} is ${t.min}, received: ${r}.`,INVALID_PARAMETER_MAX:({key:e,rule:t,fnName:i,value:r})=>`the max value of ${e||t.name} is ${t.max}, received: ${r}.`,API_CALL_TIMEOUT:e=>`${e.commandDesc||e.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>`SignalChannel setup failure: (errorCode: ${e.errorCode}, errorMsg: ${e.errorMsg} }).`,ERROR_MESSAGE(e){let t=`${e.type} failed`;return e.message&&(t=`${t}: ${e.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:e=>`exchange sdp failed ${e.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:e=>`'${e}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:e=>`'${e}' 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:e,code:t})=>`Failed to join room - ${e} code: ${t}`,REJOIN_ROOM_FAILED:e=>`reJoin room: ${e.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:e=>`duplicate ${e} stream publishing, please unpublish your prev ${e} 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:e,userId:t,streamType:i})=>`failed to subscribe ${t} ${i} stream, reason: ${e}.`,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:e=>`switchRole failed, errCode: ${e.code} errMsg: ${e.message}.`,CLIENT_BANNED:e=>`client was banned because of ${e.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:e=>`startPublishCDNStream failed, errMsg: ${e.message}.`,STOP_PUBLISH_CDN_FAILED:e=>`stopPublishCDNStream failed, errMsg: ${e.message}.`,INVALID_STREAM_ID:e=>`'${e}' 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:e=>`cannot replace ${e.kind} track because stream has not ${e.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>`startMixTranscode failed, errMsg: ${e.message}.`,STOP_MIX_TRANSCODE_FAILED:e=>`stopMixTranscode failed, errMsg: ${e.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:e,rule:t,fnName:i,value:r})=>`'${e||t.name}' cannot be less than 0 when calling ${i}().`,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:e=>`'${e}' 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:e,fnName:t})=>`'${e}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:e,fnName:t,type:i})=>`the element corresponding to '${e}' must be instanceof HTMLElement when calling ${t}(), received: ${i}.`,PLAY_FAILED:e=>`${e.media} play failed, browser exception: ${e.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:e=>`${e}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:e=>`${e.signalResponse} failed, response code is ${e.code} , errMsg: ${e.message}.`,CATCH_HANDLER_ERROR:({name:e,event:t})=>`an error was caught in ${e}.on('${t}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:e})=>`experimental api ${e} does not exist.`,REPEAT_JOIN:e=>"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:e})=>`failed to call ${e}() because client was destroyed.`,SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage"+(!1===e?" 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:e,name:t,timesInSecond:i,maxSizeInSecond:r})=>`api ${t} call ${e?"size":"times"} is over ${e?`${r} bytes`:i} in a second.`,CONNECTION_ABORTED:e=>`connection aborted due to: ${e}`,API_CALL_ABORTED(e){let t;return t=e.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${e.userId} ${e.streamType} stream aborted, reason: remote user ${e.userId} unpublished stream.`:`API aborted, reason: ${e.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:e=>`'streamType' is required when 'userId' is not '*', calling ${e}()`},baseTime=(new Date).getTime(),offset=0,getCurrentTime=function(){return(new Date).getTime()+offset},getTimestamp=function(){const e=new Date;return e.setTime(getCurrentTime()),e.toLocaleString()},formatDate=function(e){let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};function http({url:e,body:t,method:i="POST",timeout:r,priority:s}){return new Promise(((n,a)=>{if("fetch"in window)return fetch(e,{method:i,body:t,priority:s}).then((e=>e.text())).then((e=>{try{n({data:JSON.parse(e)})}catch(t){n({data:e})}}),a);const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(4===o.readyState)if(o.status>=200&&o.status<300)try{const e=JSON.parse(o.response);n({data:e})}catch(e){n({data:o.response})}else a({status:o.status,statusText:o.statusText||"request failed!"})},o.timeout=r||5e3,o.open(i,e,!0),o.send(t)}))}var has2=Object.prototype.hasOwnProperty,isFunction2=e=>"function"==typeof e,isUndefined2=e=>void 0===e,isBoolean2=e=>"boolean"==typeof e,isRemoteTrack2=e=>e.isRemote,isPlainObject2=function(e){if(!e||"object"!=typeof e||"[object Object]"!=Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;const i=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&Function.prototype.toString.call(i)===Function.prototype.toString.call(Object)};function isEmpty2(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(isPlainObject2(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(const t in e)if(has2.call(e,t))return!1;return!0}return!1}var RETRY_STATE_NOT_START=0,RETRY_STATE_STARTED=1,RETRY_STATE_STOPPED=2;function promiseRetry({retryFunction:e,settings:t,onError:i,onRetrying:r,onRetryFailed:s,onRetrySuccess:n,context:a}){return function(...o){const{retries:d=5,timeout:l=1e3}=t;let c=0,u=-1,h=RETRY_STATE_NOT_START;const _=async(t,p)=>{const m=a||this;try{const i=await e.apply(m,o);c>0&&n&&n.call(this,c),c=0,t(i)}catch(e){const n=()=>{clearTimeout(u),c=0,h=RETRY_STATE_STOPPED,p(e)},a=()=>{h!==RETRY_STATE_STOPPED&&c<(isFunction2(d)?d():d)?(c++,h=RETRY_STATE_STARTED,isFunction2(r)&&r.call(this,c,n),u=window.setTimeout((()=>{u=-1,_(t,p)}),isFunction2(l)?l(c):l)):(n(),isFunction2(s)&&s.call(this,e))};isFunction2(i)?i.call(this,{error:e,retry:a,reject:p,retryFuncArgs:o,retriedCount:c}):a()}};return new Promise(_)}}var retry_default=promiseRetry,Logger=class{constructor(e){__publicField(this,"userId"),__publicField(this,"remoteUserId"),__publicField(this,"id"),__publicField(this,"sdkAppId"),__publicField(this,"type"),__publicField(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!isBoolean2(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}createChild(e){return Object.setPrototypeOf(e,this)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,t){const i=this.isLocal?this.userId:this.remoteUserId;t.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&"main"!==this.type?"*":""}${this.id}${i?`|${i}`:""}]`),logger_manager_default.log(e,t,isUndefined2(this.userId)||isEmpty2(this.userId),this.userId,this.sdkAppId)}info(...e){this.log(2,e)}debug(...e){this.log(1,e)}warn(...e){this.log(3,e)}error(...e){this.log(4,e)}},import_eventemitter3=__toESM(require_eventemitter3(),1),innerEmitter=new import_eventemitter3.default,inner_emitter_default=innerEmitter,INNER_EVENT=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(INNER_EVENT||{}),inner_event_default=INNER_EVENT,LOG_PRE_TAG="%cTRTC%c%s",LOG_PRE_TAG_STYLE="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",LOG_STYLE="display: inline",_LoggerManager=class e{constructor(){__publicField(this,"_isEnableUploadLog",!0),__publicField(this,"_localJoinedUser",new Map),__publicField(this,"_queue",[]),__publicField(this,"_timeoutId",-1),__publicField(this,"_logLevel",1),__publicField(this,"_logLevelToUpload",2),IS_WORKER||IS_WORKLET||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&-1!==this._timeoutId}installEvents(){inner_emitter_default.on(inner_event_default.JOIN_SCHEDULE_SUCCESS,(({schedule:e})=>{var t;(null==(t=null==e?void 0:e.config)?void 0:t.logLevelToUpload)&&LOG_LEVEL[e.config.logLevelToUpload]&&(this._logLevelToUpload=e.config.logLevelToUpload)})),inner_emitter_default.on(inner_event_default.JOIN_SUCCESS,(({room:e})=>{this.addJoinedUser({userId:e.userId,sdkAppId:e.sdkAppId}),this.startUpload()})),inner_emitter_default.once(inner_event_default.JOIN_FAILED,(()=>{this.startUpload()})),inner_emitter_default.on(inner_event_default.LEAVE_SUCCESS,(({room:e})=>{this.deleteJoinedUser(e.userId)}))}startUpload(){-1===this._timeoutId&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch((()=>{})),this._timeoutId=window.setTimeout((()=>this.uploadInterval()),5e3)}getLogsToUpload(){const e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&0===this._localJoinedUser.size)return e;let t=0;for(;t<this._queue.length&&50!==t;t++){const i=this._queue[t];if(i.forAllJoinedClients)this._localJoinedUser.forEach((({userId:t,sdkAppId:r})=>{e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}));else if(isString(i.userId)&&isNumber(i.sdkAppId)){const{userId:t,sdkAppId:r}=i;e.map.has(t)?e.map.get(t).logs.push(i):e.map.set(t,{userId:t,sdkAppId:r,logs:[i]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,t)),e}async upload(){if(0===this._queue.length||!this._isEnableUploadLog)return;const{map:e,splicedQueue:t}=this.getLogsToUpload();if(0===e.size)return;try{const t=[...e.values()];for(let e=0;e<t.length;e++){const{userId:i,sdkAppId:r,logs:s}=t[e];await this.uploadLogWithRetry(JSON.stringify({timestamp:getTimestamp(),sdkAppId:String(r),userId:i,version:version,log:s.map((e=>e.log)).join("\n")}),r),s.forEach((e=>e.uploaded=!0))}}catch(e){}const i=t.filter((e=>!e.uploaded));i.length>0&&(this._queue=i.concat(this._queue))}uploadLogWithRetry(e,t){return retry_default({retryFunction:()=>http({url:getLoggerUrl(t,LOGGER_CMD_TYPE.LOG),body:e,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:e})=>{e()}})()}getPrefix(e){const t=new Date;return t.setTime(getCurrentTime()),`[${formatDate(t)}] <${LOG_LEVEL[e]}>`}getLogLevel(){return this._logLevel}setLogLevel(e){isUndefined(LOG_LEVEL[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(isString(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch(e){return""}}log(t,i,r=!0,s,n){var a;i.unshift(this.getPrefix(t));const o={log:i.reduce(((e,t)=>`${e} ${this.logChunkToString(t)}`.trim()),""),level:t,userId:s,sdkAppId:n,forAllJoinedClients:r};if(inner_emitter_default.emit(inner_event_default.LOG,{log:o}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(o),t<this._logLevel)return;const d=(null==(a=LOG_LEVEL[t])?void 0:a.toLowerCase())||"info";e.PRINT_LOG_TAG?console[d](LOG_PRE_TAG,LOG_PRE_TAG_STYLE,LOG_STYLE,...i):console[d](...i)}debug(...e){this.log(1,e)}info(...e){this.log(2,e)}warn(...e){this.log(3,e)}error(...e){this.log(4,e)}createLogger(e){return new Logger(e)}checkURLParam(){const e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;LOG_LEVEL[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};__publicField(_LoggerManager,"PRINT_LOG_TAG",!(IS_IOS||IS_ANDROID||IS_HEADLESS_CHROME));var LoggerManager=_LoggerManager,logger_manager_default=new LoggerManager,getDocUrl=(e,t)=>t?`${BASE_DOC_URL}/${e}/${t}`:`${BASE_DOC_URL}/${e}/index.html`,getErrorDataFromLocalStorage=()=>{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 e=null==localStorage?void 0:localStorage.getItem(TRTC_ERROR_ASSISTANCE);if(e){e=JSON.parse(e);const t=document.createElement("script");t.type="text/javascript",t.text=e.message,document.body.appendChild(t);const i=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:i,TRTC_ERROR_LINK:r}}return{}};function generateErrorMessage(e){const{key:t,data:i,link:r,addDocLink:s=!0}=e;let n="",a="",o="";isFunction(ErrorInfo[t])?n=ErrorInfo[t](i):isString(ErrorInfo[t])&&(n=ErrorInfo[t]);const{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:l}=getErrorDataFromLocalStorage();r?o=`${r.className}.html#${r.fnName}`:l&&l[t]&&(isFunction(l[t])?o=l[t](i):isString(l[t])&&(o=l[t]));let c=n;return isLangChinese()&&(d&&d[t]&&(isFunction(d[t])?a=d[t](i):isString(d[t])&&(a=d[t])),a&&(c=s?`${a}\n请查看文档: ${getDocUrl("zh-cn",o)}\n\n`:`${a}\n\n`,c+=n)),s&&(c+=` \nRefer to: ${getDocUrl("en",o)}\n`),c}var Storage=class{constructor(){__publicField(this,"_prefix","TRTC"),__publicField(this,"_queue",new Map)}getRealKey(e){return`${this._prefix}_${e}`}checkStorage(){if(!isLocalStorageEnabled())return;setInterval(this.doFlush.bind(this),2e4);Object.keys(localStorage).filter((e=>{if(e.startsWith(this._prefix))try{const t=localStorage.getItem(e);if(!t)return!1;const i=JSON.parse(t);if(i&&i.expiresIn<Date.now())return!0}catch(e){return!1}return!1})).forEach((e=>localStorage.removeItem(e)))}doFlush(){if(isLocalStorageEnabled())try{for(const[e,t]of this._queue)localStorage.setItem(e,JSON.stringify(t))}catch(e){logger_manager_default.warn(e)}}getItem(e){if(!isLocalStorageEnabled())return null;try{const t=localStorage.getItem(this.getRealKey(e));if(!t)return null;const i=JSON.parse(t);return i&&i.expiresIn>=Date.now()?i.value:null}catch(e){logger_manager_default.warn(e)}}setItem(e,t){if(isLocalStorageEnabled())try{const i={expiresIn:Date.now()+STORAGE_EXPIRES_TIME,value:t};this._queue.set(this.getRealKey(e),i)}catch(e){logger_manager_default.warn(e)}}deleteItem(e){if(!isLocalStorageEnabled())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(e){return logger_manager_default.warn(e),!1}}clear(){if(isLocalStorageEnabled())try{localStorage.clear()}catch(e){logger_manager_default.warn(e)}}},storage_default=new Storage,import_sdp_transform=__toESM(require_lib(),1),SUCCESS_KEY=1,FAILED_KEY=0,KVStatManager=class{constructor(e=!0){__publicField(this,"countMap",new Map),__publicField(this,"distributionMap",new Map),__publicField(this,"version"),__publicField(this,"log",logger_manager_default.createLogger({id:"kv"})),e&&(inner_emitter_default.on("102",(({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===NAME.AUDIO?501700:511700,cost:t})})),inner_emitter_default.on("103",(({track:e,error:t})=>{this.addFailedEvent({key:e.kind===NAME.AUDIO?501700:511700,error:t})})))}getReportData(){const e={msg_sdk_basic_info:{uint32_sdk_version:getUint32Version(this.version||version),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((([e,t])=>({uint32_item_key:e,uint32_item_value:t})))})))};return this.countMap.clear(),this.distributionMap.clear(),e}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){const t=+String(e).slice(-3);return t>=700&&t<799}isErrorCodeKey(e){const t=+String(e).slice(-3);return t>=600&&t<699}isCountKey(e){const t=+String(e).slice(-3);return t>=0&&t<599}isNumberKey(e){const t=+String(e).slice(-3);return t>=800&&t<899}addCount({key:e,useUV:t=!1}){this.isCountKey(e)?t&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug(`${e} is not count key, last 3 number should be 0~599`)}addEnum({key:e,value:t,useUV:i=!0}){var r;if(!this.isEnumKey(e))return this.log.debug(`${e} is not enum key, last 3 number should be 700~799`);if(i&&this.countMap.has(e))return;this.countMap.set(e,(this.countMap.get(e)||0)+1);const s=(null==(r=this.distributionMap)?void 0:r.get(e))||new Map;s.set(t,(s.get(t)||0)+1),this.distributionMap.set(e,s)}addNumber({key:e,value:t,split:i=100,useUV:r=!1,max:s=5e3}){var n;if(!this.isNumberKey(e))return this.log.debug(`${e} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(e))return;t>s&&(t=s),this.countMap.set(e,(this.countMap.get(e)||0)+1);const a=(null==(n=this.distributionMap)?void 0:n.get(e))||new Map;let o=0;if(isNumber(i))o=Math.floor(t/i);else for(let e=i.length-1;e>0;e--)if(t>i[e]){o=e;break}a.set(o,(a.get(o)||0)+1),this.distributionMap.set(e,a)}addSuccessEvent({key:e,cost:t,timeKey:i,split:r}){if(e&&(this.addEnum({key:e,value:SUCCESS_KEY,useUV:!1}),t)){const s=+String(e).slice(-3);s<800&&s>=700?this.addNumber({key:i||e+100,value:t,split:r}):i||this.log.debug(`time stat ignored, ${e}`)}}addFailedEvent({key:e,error:t}){if(!e)return;let i=error_code_default.UNKNOWN;t&&(isNumber(t)?i=t:isUndefined(t.extraCode)&&isUndefined(t.code)||(i=t.extraCode||t.code)),this.addEnum({key:e,value:FAILED_KEY,useUV:!1}),this.addEnum({key:e,value:Math.abs(i),useUV:!1})}},kvStatManager=new KVStatManager(!0),outterKVStatManager=new KVStatManager(!1),kv_stat_manager_default=kvStatManager,checkResult={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},browserInfoMap=new Map([[IS_FIREFOX,["Firefox",FIREFOX_VERSION]],[IS_EDG,["Edg",EDG_VERSION]],[IS_CHROME,["Chrome",CHROME_VERSION]],[IS_SAFARI,["Safari",SAFARI_VERSION]],[IS_TBS,["TBS",TBS_VERSION]],[IS_XWEB,["XWEB",XWEB_VERSION]],[IS_WECHAT&&IS_IPHONE,["WeChat",WECHAT_VERSION]],[IS_WQQB,["QQ(Win)",WQQB_VERSION]],[IS_MQQB,["QQ(Mobile)",MQQB_VERSION]],[IS_X5MQQB,["QQ(Mobile X5)",MQQB_VERSION]],[IS_MACQQB,["QQ(Mac)",MACQQB_VERSION]],[IS_IPADQQB,["QQ(iPad)",IPADQQB_VERSION]],[IS_MIBROWSER,["MI",MI_VERSION]],[IS_HUAWEIBROWSER,["HW",HUAWEI_VERSION]],[IS_SAMSUNGBROWSER,["Samsung",SAMSUNG_VERSION]],[IS_OPPOBROWSER,["OPPO",OPPO_VERSION]],[IS_VIVOBROWSER,["VIVO",VIVO_VERSION]],[IS_EDGE,["EDGE",EDGE_VERSION]],[IS_SOGOUM,["SogouMobile",SOGOUM_VERSION]],[IS_SOGOU,["Sogou",SOGOU_VERSION]]]);function getBrowserInfo2(){const e=browserInfoMap.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var isBrowserSupported=function(){return!IS_UCBROWSER&&!IS_EDGE&&(!(IS_EDG&&EDG_MAJOR_VERSION<80)&&!(IS_FIREFOX&&FIREFOX_MAJOR_VERSION<56))},isWebCodecsSupported=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every((e=>e in window))},isMediaDevicesSupported=function(){if(!navigator.mediaDevices)return isUsedInHttpProtocol()||logger_manager_default.error(ErrorInfo.NOT_SUPPORTED_MEDIA),!1;const e=["getUserMedia","enumerateDevices"];return e.filter((e=>e in navigator.mediaDevices)).length===e.length},IS_HTTP_WARN_LOGGED=!1;function isUsedInHttpProtocol(){return"http:"===location.protocol&&!IS_LOCAL&&(IS_HTTP_WARN_LOGGED||logger_manager_default.error(generateErrorMessage({key:ErrorName.NOT_SUPPORTED_HTTP})),IS_HTTP_WARN_LOGGED=!0,!0)}var isMediaStreamTrackProcessorSupported=function(){return(null==window?void 0:window.OffscreenCanvas)&&(null==window?void 0:window.MediaStreamTrackProcessor)&&(null==window?void 0:window.MediaStreamTrackGenerator)},encodeSupportStatus=async function(){if(checkResult.detail.isH264EncodeSupported&&checkResult.detail.isVp8EncodeSupported)return{isH264EncodeSupported:checkResult.detail.isH264EncodeSupported,isVp8EncodeSupported:checkResult.detail.isVp8EncodeSupported};let e,t=!1,i=!1;try{const r=new RTCPeerConnection,s=document.createElement(NAME.CANVAS);s.getContext("2d");const n=s.captureStream(0);return r.addTrack(n.getVideoTracks()[0],n),e=await r.createOffer(),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),checkResult.detail.isH264EncodeSupported=t,checkResult.detail.isVp8EncodeSupported=i,{isH264EncodeSupported:checkResult.detail.isH264EncodeSupported,isVp8EncodeSupported:checkResult.detail.isVp8EncodeSupported}}catch(e){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}},decodeSupportStatus=async function(){if(checkResult.detail.isH264DecodeSupported&&checkResult.detail.isVp8DecodeSupported)return{isH264DecodeSupported:checkResult.detail.isH264DecodeSupported,isVp8DecodeSupported:checkResult.detail.isVp8DecodeSupported};let e,t=!1,i=!1;try{const r=new RTCPeerConnection;return isAddTransceiverSupported()?(r.addTransceiver(NAME.VIDEO,{direction:"recvonly"}),e=await r.createOffer()):e=await r.createOffer({offerToReceiveVideo:!0}),-1!==e.sdp.toLowerCase().indexOf("h264")&&(t=!0),-1!==e.sdp.toLowerCase().indexOf("vp8")&&(i=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:i}}catch(e){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}},checkSystemRequirementsInternal=throttlePromise((async()=>{if(checkResult.result&&checkResult.detail.isH264EncodeSupported&&checkResult.detail.isVp8EncodeSupported&&checkResult.detail.isH264DecodeSupported&&checkResult.detail.isVp8DecodeSupported)return checkResult;const e=Date.now(),t=isBrowserSupported(),i=isWebRTCSupported(),r=isWebCodecsSupported(),s=isMediaDevicesSupported();let[{isH264EncodeSupported:n,isVp8EncodeSupported:a},{isH264DecodeSupported:o,isVp8DecodeSupported:d}]=await Promise.all([encodeSupportStatus(),decodeSupportStatus()]);if(!n||!a){const e=await encodeSupportStatus();logger_manager_default.warn(`detect encode again h264:${n} vp8:${a} result: ${JSON.stringify(e)}`),n=e.isH264EncodeSupported,a=e.isVp8EncodeSupported}if(n&&o&&IS_ANDROID&&IS_CHROMIUM_BASE&&!IS_XWEB&&!IS_TBS){const{encode:e,decode:t}=await detectH264Supported();n=e,o=t}return checkResult.result=t&&i&&s&&(n||a)&&(o||d),checkResult.detail.isBrowserSupported=t,checkResult.detail.isWebRTCSupported=i,checkResult.detail.isWebCodecsSupported=r,checkResult.detail.isMediaDevicesSupported=s,checkResult.detail.isScreenShareSupported=isScreenCaptureApiAvailable(),checkResult.detail.isSmallStreamSupported=isSmallStreamSupported(),checkResult.detail.isH264EncodeSupported=n,checkResult.detail.isVp8EncodeSupported=a,checkResult.detail.isH264DecodeSupported=o,checkResult.detail.isVp8DecodeSupported=d,checkResult.result||logger_manager_default.error(`${navigator.userAgent} ${stringifyIncludeValue(checkResult.detail,!1)}`),setCheckResultToStorage(),kv_stat_manager_default.addNumber({key:523800,value:Date.now()-e}),checkResult})),isTRTCSupported=function(){return checkResult.result},isScreenCaptureApiAvailable=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},detectH264SupportedPromise=null;async function detectH264Supported(){return detectH264SupportedPromise||(detectH264SupportedPromise=new Promise((async e=>{const t={encode:!1,decode:!1};let i=()=>{};try{const r=document.createElement("canvas"),s=r.getContext("2d");r.width=320,r.height=240;const n=setInterval((()=>{s.fillText("test",Math.floor(320*Math.random()),Math.floor(240*Math.random()))}),66);let a=-1,o=-1;i=()=>{clearInterval(a),clearInterval(n),clearTimeout(o),l.close(),c.close(),d.getTracks().forEach((e=>e.stop()))},o=setTimeout((()=>{i(),e(t)}),2e3);const d=r.captureStream(),l=new RTCPeerConnection({}),c=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",(e=>c.addIceCandidate(e.candidate))),c.addEventListener("icecandidate",(e=>l.addIceCandidate(e.candidate))),l.addTrack(d.getVideoTracks()[0],d);const u=await l.createOffer();await l.setLocalDescription(u),await c.setRemoteDescription(u);const h=await c.createAnswer(),_=import_sdp_transform.default.parse(h.sdp),p=_.media[0].rtp.findIndex((e=>"H264"===e.codec));_.media[0].rtp=[_.media[0].rtp[p]],_.media[0].fmtp=_.media[0].fmtp.filter((e=>e.payload===_.media[0].rtp[0].payload)),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter((e=>e.payload===_.media[0].rtp[0].payload))),h.sdp=import_sdp_transform.default.write(_),await c.setLocalDescription(h),await l.setRemoteDescription(h),a=setInterval((async()=>{t.encode&&t.decode&&(i(),e(t));const[r,s]=await Promise.all([l.getSenders()[0].getStats(),c.getReceivers()[0].getStats()]);t.encode||r.forEach((e=>{"outbound-rtp"===e.type&&e.mediaType===NAME.VIDEO&&e.bytesSent>0&&(t.encode=!0)})),t.decode||s.forEach((e=>{"inbound-rtp"===e.type&&e.mediaType===NAME.VIDEO&&e.bytesReceived>0&&(t.decode=!0)}))}),100)}catch(t){i(),logger_manager_default.warn("detectH264Supported failed",t),e({encode:!0,decode:!0})}})).then((e=>(e.encode||(e.decode=!0),e.encode&&e.decode||logger_manager_default.warn(`detectH264Supported encode: ${e.encode} decode: ${e.decode} ${UA_DATA_STRING}`),e))))}var HTTPS_API=(e,t,i)=>{"http:"!==location.protocol||IS_LOCAL||(e[t]=()=>{throw new rtc_error_default({code:error_code_default.INVALID_OPERATION,message:ErrorInfo.NOT_SUPPORTED_HTTP})})},isSelectedCandidatePair=function(e){return!("candidate-pair"!==e.type||!e.nominated||"in-progress"!==e.state&&"succeeded"!==e.state)&&!(isBoolean(e.selected)&&!e.selected)};function getDisplayResolution(){let e="";if(screen.width){e+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`}return e}function isGetUserMediaSupported(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function isWebAudioSupported(){const e={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let i=0;i<t.length;i++)if(t[i]in window){e.isSupported=!0;break}return e.isSupported}function isCanvasCaptureStreamAPISupported(){return"captureStream"in HTMLCanvasElement.prototype}function isCanvasSmallStreamSupported(){return!(IS_WECHAT||IS_IOS||CHROME_MAJOR_VERSION&&CHROME_MAJOR_VERSION<63)&&!(!isBrowserSupported()||!isCanvasCaptureStreamAPISupported())}function isScaleResolutionDownBySupported(){return!(CHROME_MAJOR_VERSION<74||IS_EDGE||IOS_MAIN_VERSION<11||FIREFOX_MAJOR_VERSION<46)}function isSmallStreamSupported(){return isCanvasSmallStreamSupported()||isScaleResolutionDownBySupported()}var isUnifiedPlanDefault=function(){if(isUndefined(window.RTCRtpTransceiver)||!isAddTransceiverSupported())return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let e=null,t=!1;try{e=new RTCPeerConnection({sdpSemantics:SDP_SEMANTICS_UNIFIED_PLAN}),e.addTransceiver(NAME.AUDIO),t=!0}catch(e){}return null==e||e.close(),t};function isGetReceiversSupported(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function isGetSendersSupported(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function isGetTransceiversSupported(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function isAddTransceiverSupported(){return!(11===IOS_MAIN_VERSION&&!IS_DESKTOP_IOS_CHROME)&&("RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype)}var IS_SPC_SUPPORTED=!(!isAddTransceiverSupported()||IS_CHROMIUM_BASE&&CHROME_MAJOR_VERSION<86);function isStopTransceiverSupported(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var IS_RTC_RTP_SENDER_SUPPORTED="RTCRtpSender"in window;function isReplaceTrackSupported(){return IS_RTC_RTP_SENDER_SUPPORTED&&"replaceTrack"in window.RTCRtpSender.prototype}function isSetParametersSupported(){return IS_RTC_RTP_SENDER_SUPPORTED&&"setParameters"in window.RTCRtpSender.prototype&&isGetSendersSupported()}var IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,IS_GET_SETTINGS_SUPPORTED=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,IS_GET_CAPABILITIES_SUPPORTED=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,IS_INSERTABLE_STREAM_SUPPORTED=IS_RTC_RTP_SENDER_SUPPORTED&&"createEncodedStreams"in window.RTCRtpSender.prototype&&getChromeMajorVersion()>=86,IS_SCRIPT_TRANSFORM_SUPPORTED="RTCRtpScriptTransform"in window,IS_SEI_SUPPORTED=IS_RTC_RTP_SENDER_SUPPORTED&&(IS_INSERTABLE_STREAM_SUPPORTED||IS_SCRIPT_TRANSFORM_SUPPORTED),isWebRTCSupported=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter((e=>e in window)).length>0};function isWebCodecSupported(){const e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return isUndefined(window.AudioDecoder)||(e.AudioDecoder=!0),isUndefined(window.AudioEncoder)||(e.AudioEncoder=!0),isUndefined(window.VideoDecoder)||(e.VideoDecoder=!0),isUndefined(window.VideoEncoder)||(e.VideoEncoder=!0),isUndefined(window.ImageDecoder)||(e.ImageDecoder=!0),e}function isMediaSessionSupported(){return"mediaSession"in navigator&&!isUndefined(navigator.mediaSession.setActionHandler)}function isWebTransportSupported(){return!isUndefined(window.WebTransport)}function isSIMDSupported(){return"undefined"!=typeof WebAssembly&&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 basis(){const e={browser:`${browserInfo.name}/${browserInfo.version}`,os:getOSName(),displayResolution:getDisplayResolution(),isScreenShareSupported:isScreenCaptureApiAvailable(),isWebRTCSupported:isWebRTCSupported(),isGetUserMediaSupported:isGetUserMediaSupported(),isWebAudioSupported:isWebAudioSupported(),isWebSocketsSupported:"WebSocket"in window&&2===window.WebSocket.CLOSING,isWebCodecSupported:isWebCodecSupported(),isMediaSessionSupported:isMediaSessionSupported(),isWebTransportSupported:isWebTransportSupported()};return navigator.userAgent.includes("miniProgram")&&(e.browser=`mini/${e.browser}`),e}var CACHE_KEY="checkResult";function setCheckResultToStorage(){storage_default.setItem(CACHE_KEY,{ua:navigator.userAgent,checkResult:checkResult})}function capabilityCheck(){isUsedInHttpProtocol();const e=storage_default.getItem(CACHE_KEY);e&&e.ua===navigator.userAgent&&e.checkResult&&checkStorageResultVersion(e.checkResult.detail,checkResult.detail)&&(checkResult=e.checkResult),checkSystemRequirementsInternal()}function checkStorageResultVersion(e,t){return!!isObject(e)&&Object.keys(t).every((t=>t in e))}function isRequestVideoFrameCallbackSupported(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var IS_JITTER_BUFFER_TARGET_SUPPORTED="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype,layoutProperty={x:{required:!0,type:"number"},y:{required:!0,type:"number"},width:{required:!0,type:"number",notLessThanZero:!0,min:1},height:{required:!0,type:"number",notLessThanZero:!0,min:1},zIndex:{required:!0,type:"number"},fillMode:{required:!1,type:"string"},mirror:{required:!1,type:"boolean"},rotation:{required:!1,type:"number"}},canvasValidateRule=(e,t=!1)=>({type:"object",required:t,properties:{canvasColor:{required:!1,type:["string",CanvasGradient,CanvasPattern]},width:{required:!0,type:"number",notLessThanZero:!0,min:1},height:{required:!0,type:"number",notLessThanZero:!0,min:1},frameRate:{required:!1,type:"number",notLessThanZero:!0}}}),viewValidateRule=e=>({required:!1,type:["string",HTMLElement,null],validate(t,i,r){const{RtcError:s,ErrorCode:n,ErrorCodeDictionary:a}=e.errorModule;if(isString(t)){if(!document.getElementById(t))throw new s({code:n.INVALID_PARAMETER,extraCode:a.INVALID_ELEMENT_ID,fnName:r,messageParams:{key:i}})}}}),layoutValidateRule=(e,t=!0)=>({type:"object",required:t,properties:__spreadValues({},layoutProperty),validate(t,i,r,s){const{RtcError:n,ErrorCode:a,ErrorCodeDictionary:o}=e.errorModule;if(t){if(t.fillMode&&!["contain","cover","fill"].includes(t.fillMode))throw new n({code:a.INVALID_PARAMETER,extraCode:o.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:r});if(t.rotation&&![0,90,180,270].includes(t.rotation))throw new n({code:a.INVALID_PARAMETER,extraCode:o.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:r})}}}),cameraValidateRule=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},cameraId:{required:!1,type:"string"},videoTrack:{required:!1,instanceof:MediaStreamTrack},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},layout:__spreadValues({},layoutValidateRule(e))}}}),screenValidateRule=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},captureElement:{required:!1,type:HTMLElement},preferDisplaySurface:{required:!1,type:"string"},layout:__spreadValues({},layoutValidateRule(e))},validate(t,i,r){const{RtcError:s,ErrorCode:n,ErrorCodeDictionary:a}=e.errorModule;if(!isScreenCaptureApiAvailable())throw new s({code:n.ENV_NOT_SUPPORTED,fnName:r,extraCode:a.NOT_SUPPORTED_SCREEN_SHARE})}}}),textValidateRule=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},content:{required:!0,type:"string"},font:{required:!1,type:"string"},color:{required:!1,type:["string",CanvasGradient,CanvasPattern]},layout:__spreadValues({},layoutValidateRule(e))}}}),imageValidateRule=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:__spreadValues({},layoutValidateRule(e))}}}),videoValidateRule=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:__spreadValues({},layoutValidateRule(e))}}});function startValidateRule(e){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:__spreadValues({},viewValidateRule(e)),canvasInfo:__spreadValues({},canvasValidateRule(e,!0)),camera:__spreadValues({},cameraValidateRule(e)),screen:__spreadValues({},screenValidateRule(e)),text:__spreadValues({},textValidateRule(e)),image:__spreadValues({},imageValidateRule(e)),video:__spreadValues({},videoValidateRule(e))}}}function updateValidateRule(e){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:__spreadValues({},viewValidateRule(e)),canvasInfo:__spreadValues({},canvasValidateRule(e)),camera:__spreadValues({},cameraValidateRule(e)),screen:__spreadValues({},screenValidateRule(e)),text:__spreadValues({},textValidateRule(e)),image:__spreadValues({},imageValidateRule(e)),video:__spreadValues({},videoValidateRule(e))}}}function stopValidateRule(e){return{name:"StopVideoMixerOptions",required:!1}}var generateUUID=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},uuid_default=generateUUID,import_eventemitter32=__toESM(require_eventemitter3(),1),instance=Symbol("instance"),abortCtrl=Symbol("abortCtrl"),cacheResult=Symbol("cacheResult"),MiddleState=class{constructor(e,t,i){this.oldState=e,this.newState=t,this.action=i,this.aborted=!1}abort(e){this.aborted=!0,setState.call(e,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},FSMError=class extends Error{constructor(e,t,i){super(t),this.state=e,this.message=t,this.cause=i}};function thenAble(e){return"object"==typeof e&&e&&"then"in e}var stateDiagram=new Map;function ChangeState(e,t,i={}){return(r,s,n)=>{const a=i.action||s;if(!i.context){const i=stateDiagram.get(r)||[];stateDiagram.has(r)||stateDiagram.set(r,i),i.push({from:e,to:t,action:a})}const o=n.value;n.value=function(...r){let s=this;if(i.context&&(s=FSM.get("function"==typeof i.context?i.context.call(this,...r):i.context)),s.state===t)return i.sync?s[cacheResult]:Promise.resolve(s[cacheResult]);s.state instanceof MiddleState&&s.state.action==i.abortAction&&s.state.abort(s);let n=null;Array.isArray(e)?0==e.length?s.state instanceof MiddleState&&s.state.abort(s):"string"==typeof s.state&&e.includes(s.state)||(n=new FSMError(s._state,`${s.name} ${a} to ${t} failed: current state ${s._state} not from ${e.join("|")}`)):e!==s.state&&(n=new FSMError(s._state,`${s.name} ${a} to ${t} failed: current state ${s._state} not from ${e}`));const d=e=>{if(i.fail&&i.fail.call(this,e),i.sync){if(i.ignoreError)return e;throw e}return i.ignoreError?Promise.resolve(e):Promise.reject(e)};if(n)return d(n);const l=s.state,c=new MiddleState(l,t,a);setState.call(s,c);const u=e=>{var r;return s[cacheResult]=e,c.aborted||(setState.call(s,t),null===(r=i.success)||void 0===r||r.call(this,s[cacheResult])),e},h=e=>(setState.call(s,l,e),d(e));try{const e=o.apply(this,r);return thenAble(e)?e.then(u).catch(h):i.sync?u(e):Promise.resolve(u(e))}catch(i){return h(new FSMError(s._state,`${s.name} ${a} from ${e} to ${t} failed: ${i}`,i instanceof Error?i:new Error(String(i))))}}}}var sendDevTools=(()=>{const e="undefined"!=typeof window&&window.__AFSM__,t="undefined"!=typeof importScripts;return e?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:t?(e,t)=>{postMessage({type:e,payload:t})}:()=>{}})();function setState(e,t){const i=this._state;this._state=e;const r=e.toString();e&&this.emit(r,i),this.emit(FSM.STATECHANGED,e,i,t),this.updateDevTools({value:e,old:i,err:t instanceof Error?t.message:String(t)})}var FSM=class e extends import_eventemitter32.default{constructor(t,i,r){super(),this.name=t,this.groupName=i,this._state=e.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),i||(this.groupName=this.constructor.name);const s=r[instance];s?this.name=s.name+"-"+s.count++:r[instance]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const e=Object.getPrototypeOf(this),t=stateDiagram.get(e)||[];let i=new Set,r=[],s=[];const n=new Set,a=Object.getPrototypeOf(e);stateDiagram.has(a)&&(a.stateDiagram.forEach((e=>i.add(e))),a.allStates.forEach((e=>n.add(e)))),t.forEach((({from:e,to:t,action:i})=>{"string"==typeof e?r.push({from:e,to:t,action:i}):e.length?e.forEach((e=>{r.push({from:e,to:t,action:i})})):s.push({to:t,action:i})})),r.forEach((({from:e,to:t,action:r})=>{n.add(e),n.add(t),n.add(r+"ing"),i.add(`${e} --\x3e ${r}ing : ${r}`),i.add(`${r}ing --\x3e ${t} : ${r} 🟢`),i.add(`${r}ing --\x3e ${e} : ${r} 🔴`)})),s.forEach((({to:e,action:t})=>{i.add(`${t}ing --\x3e ${e} : ${t} 🟢`),n.forEach((r=>{r!==e&&i.add(`${r} --\x3e ${t}ing : ${t}`)}))}));const o=[...i];return Object.defineProperties(e,{stateDiagram:{value:o},allStates:{value:n}}),o}static get(t){let i;return"string"==typeof t?(i=e.instances.get(t),i||e.instances.set(t,i=new e(t,void 0,Object.create(e.prototype)))):(i=e.instances2.get(t),i||e.instances2.set(t,i=new e(t.constructor.name,void 0,Object.create(e.prototype)))),i}static getState(t){var i;return null===(i=e.get(t))||void 0===i?void 0:i.state}updateDevTools(t={}){sendDevTools(e.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(e){setState.call(this,e)}};FSM.STATECHANGED="stateChanged",FSM.UPDATEAFSM="updateAFSM",FSM.INIT="[*]",FSM.ON="on",FSM.OFF="off",FSM.instances=new Map,FSM.instances2=new WeakMap;var hasWindow="undefined"!=typeof window,requestIC=hasWindow&&window.requestIdleCallback||function(e){const t=Date.now();return setTimeout((()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})}),1e3)},cancelIC=hasWindow&&window.cancelIdleCallback||function(e){clearTimeout(e)},cancelAnimationFrame2=hasWindow&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),_Timer=class e{static generateTaskID(){return this.currentTaskID++}static run(e,t,i){(null==i?void 0:i.fps)&&(i.delay=i.delay||Number((1e3/i.fps).toFixed(2))),i=__spreadValues(__spreadValues({},"interval"===e?{delay:2e3,count:0,backgroundTask:!0}:"ric"===e?{delay:1e4,count:0}:"raf"===e?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),i);const r=__spreadProps(__spreadValues({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:t},i),{delay:i.delay});return this.taskMap.set(r.taskID,r),this[e](r),r.taskID}static interval(t){return t.intervalID=setInterval((()=>{t.callback(),t.loopCount+=1,e.isBreakLoop(t)}),t.delay)}static intervalInWorker(t){e.sharedWorker||(e.sharedWorker=new Worker(URL.createObjectURL(new Blob(["\n const timers = new Map();\n self.onmessage = function(e) {\n const { taskId, delay, type } = e.data;\n if (type === 'start') {\n timers.set(taskId, setInterval(() => {\n self.postMessage({ type: 'tick', taskId });\n }, delay));\n } else if (type === 'stop') {\n clearInterval(timers.get(taskId));\n timers.delete(taskId);\n }\n };\n "],{type:"application/javascript"}))),e.sharedWorker.onmessage=t=>{var i;if("tick"===t.data.type){const r=e.workerTasks.get(t.data.taskId);r&&(e.isBreakLoop(r)?(null==(i=e.sharedWorker)||i.postMessage({type:"stop",taskId:r.taskID}),e.workerTasks.delete(r.taskID)):(r.callback(),r.loopCount+=1))}}),e.workerTasks.set(t.taskID,t),e.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){const i=()=>{if(t.callback(),t.loopCount+=1,!e.isBreakLoop(t))return t.timeoutID=setTimeout(i,t.delay)};return t.timeoutID=setTimeout(i,t.delay)}static ric(t){let i,r=performanceNow();const s=()=>{if(i=performanceNow()-r,i>=t.delay&&(r=performanceNow()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.ricID=requestIC(s,{timeout:t.delay})};return t.ricID=requestIC(s,{timeout:t.delay})}static raf(t){let i,r=performanceNow();const s=()=>{if(document.hidden&&t.backgroundTask){if(i=performanceNow()-r,r=performanceNow(),t.callback(),t.loopCount+=1,e.isBreakLoop(t))return;return t.timeoutID=setTimeout(s,t.delay-Math.floor(i%t.delay))}if(i=performanceNow()-r,i>=t.delay&&(r=performanceNow()-Math.floor(i%t.delay),t.callback(),t.loopCount+=1),!e.isBreakLoop(t))return t.rafID=requestAnimationFrame(s)};if(t.rafID=requestAnimationFrame(s),t.backgroundTask){const e=()=>{if(document.hidden){const e=performanceNow()-r;e>=t.delay?s():t.timeoutID=setTimeout(s,t.delay-e)}};document.addEventListener("visibilitychange",e),t.onVisibilitychange=e,document.hidden&&e()}return t.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;const{intervalID:t,timeoutID:i,rafID:r,ricID:s,onVisibilitychange:n}=this.taskMap.get(e);return t&&clearInterval(t),i&&clearTimeout(i),r&&cancelAnimationFrame2&&cancelAnimationFrame2(r),s&&cancelIC(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||0!==e.count&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};__publicField(_Timer,"taskMap",new Map),__publicField(_Timer,"currentTaskID",1),__publicField(_Timer,"sharedWorker",null),__publicField(_Timer,"workerTasks",new Map);var Timer=_Timer,timer_default=Timer,ClientEvent={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:NAME.SEI_MESSAGE,ERROR:"error"},PlayerEvent={LOADED_DATA:NAME.LOADEDDATA,LOADED_META_DATA:NAME.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"},event_manager_exports={};__export(event_manager_exports,{create:()=>create,remove:()=>remove});var contextMap=new WeakMap;function create(e,t){contextMap.has(e)||contextMap.set(e,[]);const i=contextMap.get(e),r={add:(e,s)=>("addEventListener"in t?(i.push(t.removeEventListener.bind(t,e,s)),t.addEventListener(e,s)):(i.push(t.off.bind(t,e,s)),t.on(e,s)),r)};return r}function remove(e){const t=contextMap.get(e);t&&(t.forEach((e=>e())),contextMap.delete(e))}var EventLogger=class{constructor(){__publicField(this,"_roomIdMap",new Map),__publicField(this,"_configs"),"undefined"==typeof registerProcessor&&(this._configs={sdkAppId:"",userId:"",version:version,env:ENV_NAME.QCLOUD,browserVersion:browserInfo.name+browserInfo.version,ua:navigator.userAgent})}setConfig({sdkAppId:e,env:t,userId:i,roomId:r}){e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=t,this._configs.userId=i,this._roomIdMap.set(i,String(r))}logSuccessEvent(e){!IS_LOCAL&&logger_manager_default.isAbleToUpload&&this._configs.env===ENV_NAME.QCLOUD&&this.uploadEventToKibana(__spreadProps(__spreadValues({},e),{result:"success"}))}logFailedEvent(e){if(IS_LOCAL||!logger_manager_default.isAbleToUpload)return;const{eventType:t,code:i,error:r,userId:s}=e,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:t,result:"failed",code:i||(null==r?void 0:r.extraCode)||(null==r?void 0:r.code)||error_code_default.UNKNOWN};this._configs.env===ENV_NAME.QCLOUD&&this.uploadEventToKibana(__spreadProps(__spreadValues({},n),{error:r}))}uploadEventToKibana(e){let t=`stat-${e.eventType}-${e.result}`;"delta-join"!==e.eventType&&"delta-leave"!==e.eventType&&"delta-publish"!==e.eventType||(t=`${e.eventType}:${e.delta}`),this.uploadEvent({log:t,userId:e.userId}),"failed"===e.result&&(t=`stat-${e.eventType}-${e.result}-${e.code}`,this.uploadEvent({log:t,userId:e.userId,error:e.error}))}uploadEvent({log:e,userId:t,error:i}){const r={timestamp:getTimestamp(),sdkAppId:this._configs.sdkAppId,userId:t||this._configs.userId,version:version,log:e};i&&(r.errorInfo=i.message,i.stack&&(r.errorInfo+=`\n${i.stack}`)),this.sendRequest(getLoggerUrl(this._configs.sdkAppId,LOGGER_CMD_TYPE.LOG),r)}sendRequest(e,t){setTimeout((()=>http({url:e,body:JSON.stringify(t),priority:"low"}).catch((()=>{}))),2e3)}},event_log_default=new EventLogger,retryingMap=new WeakMap;function addPromiseRetry({settings:e={retries:5,timeout:2e3},onError:t,onRetrying:i,onRetryFailed:r}){return function(s,n,a){const o=retry_default({retryFunction:a.value,settings:e,onError({error:e,retry:i,reject:r,retryFuncArgs:a}){var o;t?t.call(this,e,(()=>{var t;(null==(t=retryingMap.get(s))?void 0:t.has(n))?i():r(e)}),r,a):(null==(o=retryingMap.get(s))?void 0:o.has(n))?i():r(e)},onRetrying(e,t){var r;isFunction2(i)&&i.call(this,e,t),(null==(r=retryingMap.get(s))?void 0:r.has(n))&&(retryingMap.get(s).get(n).stopRetry=t)},onRetryFailed:r});return a.value=function(...e){const t=retryingMap.get(s);return t?t.set(n,{args:e}):retryingMap.set(s,new Map([[n,{args:e}]])),o.apply(this,e).finally((()=>{var e;return null==(e=retryingMap.get(s))?void 0:e.delete(n)}))},a}}var Player=class extends FSM{constructor(e,t){super(e.id,`${t}-player`),this.kind=t,__publicField(this,"id"),__publicField(this,"element",null),__publicField(this,"track"),__publicField(this,"url"),__publicField(this,"attr"),__publicField(this,"mode"),__publicField(this,"muted"),__publicField(this,"_log"),__publicField(this,"_pausedRetryCount"),__publicField(this,"_isElementPlayingFired",!1),__publicField(this,"_interval"),__publicField(this,"_delayDestroyTimeoutId",0),__publicField(this,"_playSuccessResolve"),__publicField(this,"_isReplayByRecreateMediaStreamCalled",!1),__publicField(this,"isInAutoPlayFailedState",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=PAUSED_RETRY_COUNT,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return"PLAYING"===this._state&&!1===(null==(e=this.element)?void 0:e.paused)}get isPaused(){var e;return"PAUSED"===this._state||!0===(null==(e=this.element)?void 0:e.paused)}get isStopped(){return"STOPPED"===this._state}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,null!==e&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}async play(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),await new Promise(((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)}))}catch(e){const t=generateErrorMessage({key:ErrorName.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new rtc_error_default({code:error_code_default.PLAY_NOT_ALLOWED,message:t})}}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!IS_ANY_SAFARI?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout((()=>this.destroyElement()),3*e)):this.destroyElement(),this.handleStopped(NAME.ENDED),this._interval>0&&timer_default.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&(null==(e=this.element)||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():IS_IOS_15_1?this.replay():this.play().catch((()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch((()=>{}))}bindElementEvents(){if(this.element){const e=this.handleElementEvent.bind(this);return create(this.element,this.element).add(NAME.PLAYING,e).add(NAME.ENDED,e).add(NAME.PAUSE,e).add(NAME.ERROR,e).add(NAME.LOADEDDATA,e).add(NAME.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){const t=this.handleTrackEvent.bind(this);null==event_manager_exports||event_manager_exports.create(e,e).add(NAME.ENDED,t).add(NAME.MUTE,t).add(NAME.UNMUTE,t),e.readyState===NAME.ENDED&&this.handleTrackEvent({type:NAME.ENDED}),e.muted&&this.handleTrackEvent({type:NAME.MUTE})}}bindAutoPlayEvent(){inner_emitter_default.on(inner_event_default.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&remove(e)}unbindEvents(){this.element&&remove(this.element),this.unbindTrackEvents(),inner_emitter_default.off(inner_event_default.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case NAME.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(NAME.PLAYING),this._interval&&(timer_default.clearTask(this._interval),this._interval=-1);break;case NAME.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(NAME.ENDED);break;case NAME.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(NAME.PAUSE),IS_IOS&&(this._interval=timer_default.run("timeout",(()=>{this.element&&"PAUSED"===this._state&&this.resume()}),{delay:3e3}));break;case NAME.ERROR:if(this.element&&this.element.error){this.handlePaused(NAME.ERROR);const{code:e,message:t}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${e} message: ${t} userAgent: ${navigator.userAgent}`),event_log_default.uploadEvent({log:`stat-${this.kind}-${KIBANA_EVENT.PLAYER_ERROR}-${e}-${navigator.userAgent}`,error:this.element.error}),IS_HONOR||IS_HUAWEI?this.emit(PlayerEvent.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case NAME.LOADEDDATA:this.kind===NAME.VIDEO&&this.emit(PlayerEvent.LOADED_DATA);break;case NAME.LOADEDMETADATA:this.kind===NAME.VIDEO&&this.emit(PlayerEvent.LOADED_META_DATA)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then((()=>{this._log.warn("replayByRecreateMediaStream success"),event_log_default.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),kv_stat_manager_default.addSuccessEvent({key:this.kind===NAME.AUDIO?506700:516700})})).catch((()=>{var t;this._log.error("replayByRecreateMediaStream failed"),event_log_default.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),kv_stat_manager_default.addFailedEvent({key:this.kind===NAME.AUDIO?506700:516700,error:null==(t=this.element)?void 0:t.error}),this.emit(PlayerEvent.ERROR,e)}))}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise(((t,i)=>{delay(e).then((()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var e,t,r;this._log.warn(`element onerror ${null==(t=null==(e=this.element)?void 0:e.error)?void 0:t.code} fired after recreated mediaStream`),i(null==(r=this.element)?void 0:r.error)}),delay(5e3).then((()=>{var e,r;this.isPlaying&&!(null==(e=this.element)?void 0:e.error)||i(null==(r=this.element)?void 0:r.error),t()}))}))})).finally((()=>{this.element&&(this.element.onerror=null)}))}async handleTrackEvent(e){switch(e.type){case NAME.ENDED:this.handleStopped(NAME.ENDED);break;case NAME.MUTE:this.handlePaused(NAME.MUTE);break;case NAME.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&(this._log.warn("track unmuted and element is paused, resume"),await this.resume()),!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(NAME.UNMUTE))}}handlePlaying(e){var t;this._log.debug("handlePlaying",e),null==(t=this._playSuccessResolve)||t.call(this,e),this.emit(PlayerEvent.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this._log.debug("handlePaused",e),this.emit(PlayerEvent.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this._log.debug("handleStopped",e),this.emit(PlayerEvent.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};__decorateClass([addPromiseRetry({settings:{retries:2,timeout:0},onError(e,t,i,r){r[0]=(r[0]||1e3)+1e3,t()}})],Player.prototype,"doReplayByRecreateMediaStream",1),__decorateClass([ChangeState([],"PLAYING",{sync:!0})],Player.prototype,"handlePlaying",1),__decorateClass([ChangeState("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Player.prototype,"handlePaused",1),__decorateClass([ChangeState([],"STOPPED",{sync:!0})],Player.prototype,"handleStopped",1);var AudioContextClass,context,CLASS_PREFIX="trtc_autoplay",CLASS_MASK=`${CLASS_PREFIX}_mask`,CLASS_WRAPPER=`${CLASS_PREFIX}_wrapper`,CLASS_HEADER=`${CLASS_PREFIX}_header`,CLASS_CONTENT=`${CLASS_PREFIX}_content`,CLASS_ACTION_WRAPPER=`${CLASS_PREFIX}_action_wrapper`,CLASS_ACTION_QUESTION=`${CLASS_PREFIX}_question`,CLASS_ACTION_COLLAPSE=`${CLASS_PREFIX}_collapse`,CLASS_ACTION_CONFIRM=`${CLASS_PREFIX}_action_confirm`,CLASS_DETAIL=`${CLASS_PREFIX}_detail`,COLOR_BLUE="#2473E8",DIALOG="dialog",STAT_SHOW_DIALOG=`${DIALOG}-show`,STAT_CLICK_DETAIL=`${DIALOG}-1`,STAT_CLICK_QUESTION=`${DIALOG}-2`,isStyleAdded=!1,isAutoPlayDialogShowing=()=>!!document.querySelector(`.${CLASS_WRAPPER}`),DOC_LINK=`${BASE_DOC_URL}/${isLangChinese()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,OTHER_SOLUTION_LINK=`<br><a href='${DOC_LINK}' target='_blank'>${isLangChinese()?"其他方案?":"Any other solution?"}</a>`,DETAIL_TEXT=""+(isLangChinese()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${OTHER_SOLUTION_LINK}`:`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. ${OTHER_SOLUTION_LINK}`),AutoPlayDialog=class{constructor(){if(__publicField(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),__publicField(this,"_dialogNode",null),__publicField(this,"_bodyPosition",""),__publicField(this,"_showDetail",!1),__publicField(this,"_isCollapseClicked",!1),__publicField(this,"_isQuestionClicked",!1),isLangChinese()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!isStyleAdded){const e=document.createElement("style");e.innerHTML=`.${CLASS_MASK}{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;}.${CLASS_MASK} div:not(.${CLASS_ACTION_WRAPPER}){display:block !important;}.${CLASS_WRAPPER}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${CLASS_WRAPPER} a{color:${COLOR_BLUE};}.${CLASS_HEADER}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${CLASS_CONTENT}{margin:8px 0;}.${CLASS_ACTION_WRAPPER}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${CLASS_ACTION_COLLAPSE}{margin-right:auto;cursor:pointer}.${CLASS_ACTION_QUESTION}{height:100%;line-height:16px;cursor:pointer;}.${CLASS_ACTION_CONFIRM}{margin-left:8px;color:#fff;background:${COLOR_BLUE};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${CLASS_ACTION_CONFIRM}:hover{opacity:0.9;}.${CLASS_ACTION_COLLAPSE},.${CLASS_ACTION_CONFIRM},.${CLASS_CONTENT},.${CLASS_ACTION_QUESTION}{font-size:14px;}@media screen and (max-width:750px){.${CLASS_WRAPPER}{width:80vw;}}`,document.head.appendChild(e),isStyleAdded=!0}this.addDiaLog()}createDiaLog(){const e=document.createElement("template");e.innerHTML=`<div class="${CLASS_MASK}"><div class='${CLASS_WRAPPER}'><div class='${CLASS_HEADER}'>${location.host}</div><div class='${CLASS_CONTENT}'>${this.content}</div><div class='${CLASS_DETAIL}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${DETAIL_TEXT}</div><div class='${CLASS_ACTION_WRAPPER}'></div></div></div>`.trim();const t=document.createElement("button");t.className=CLASS_ACTION_CONFIRM,t.innerText=isLangChinese()?"恢复播放":"Resume",t.onclick=this.onConfirm.bind(this);const i=document.createElement("div");i.className=CLASS_ACTION_QUESTION,i.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n <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">\n <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"/>\n <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"/>\n <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"/>\n </svg>\n ',i.onclick=this.onQuestionClick.bind(this);const r=document.createElement("div");r.className=CLASS_ACTION_COLLAPSE,r.innerText=""+(isLangChinese()?"详情 >":"Detail >"),r.onclick=this.onCollapseClick.bind(this);const s=e.content.firstChild,n=s.querySelector(`.${CLASS_ACTION_WRAPPER}`);return n.appendChild(r),n.appendChild(i),n.appendChild(t),s}addDiaLog(){isAutoPlayDialogShowing()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${CLASS_WRAPPER}`).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",logger_manager_default.info("show autoplay dialog"),event_log_default.uploadEvent({log:STAT_SHOW_DIALOG}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){logger_manager_default.warn("confirm clicked, try resume stream"),inner_emitter_default.emit(inner_event_default.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){const e=this._dialogNode.querySelector(`.${CLASS_DETAIL}`);e.style.visibility=""+(this._showDetail?"hidden":"visible"),e.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||event_log_default.uploadEvent({log:STAT_CLICK_DETAIL}),this._isCollapseClicked=!0}onQuestionClick(){window.open(DOC_LINK,"_blank"),this._isQuestionClicked||event_log_default.uploadEvent({log:STAT_CLICK_QUESTION}),this._isQuestionClicked=!0}},autoplay_dialog_default=AutoPlayDialog,VideoPlayer=class extends Player{constructor(e){super(e,NAME.VIDEO),__publicField(this,"stat",{}),__publicField(this,"_calculateTimeout",-1),__publicField(this,"viewMirror",!1),__publicField(this,"objectFit"),__publicField(this,"container"),__publicField(this,"canvas"),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,isUndefined(e.viewMirror)||(this.viewMirror=e.viewMirror),isUndefined(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return"PLAYING"===this._state&&((!this.element||!this.element.paused)&&("live"===(null==(e=this.track)?void 0:e.readyState)&&!this.track.muted))}initializeElement(){var e;const t=document.createElement(NAME.VIDEO);this.track&&2!==this.mode&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id",`video_${this.id}`),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,null==(e=this.container)||e.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&&(null==(t=this.container)||t.appendChild(this.elementToRender))}bindElementEvents(){const e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(NAME.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(NAME.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===NAME.MUTE&&(null==(t=this.stat)?void 0:t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var t,i;if(2===this.mode)return;super.handleElementEvent(e);const r=e.type;if(r===NAME.PAUSE){this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${null==(t=this.container)?void 0:t.id}`),this.container&&this.container!==document.getElementById(this.container.id)&&(this._pausedRetryCount=PAUSED_RETRY_COUNT,this._log.info(`view container ${null==(i=this.container)?void 0:i.id} is recreated`)),this._pausedRetryCount>0&&!isAutoPlayDialogShowing()&&(this._log.info(`[${PAUSED_RETRY_COUNT-this._pausedRetryCount+1}/${PAUSED_RETRY_COUNT}] ${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)}if(this.viewMirror&&this.element){const e=this.element.style.transform;r===NAME.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=e.replace("scaleX(-1)",""):r!==NAME.LEAVE_PICTURE_IN_PICTURE||e.includes("scaleX")||(this.element.style.transform=`${e} scaleX(-1)`)}}setCanvas(e,t=1){var i,r,s,n;this.canvas!==e&&(null==(i=this.canvas)||i.remove(),null==e||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,2===this.mode&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?(null==(r=this.element)||r.remove(),null==(s=this.container)||s.appendChild(e)):this.element&&(null==(n=this.container)||n.appendChild(this.element)))}setAttr(e){const 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),null==(t=this.canvas)||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),2===this.mode?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(PlayerEvent.MEDIA_TRACK_CHANGED,e),null!==e&&(this.bindTrackEvents(),this.element&&2!==this.mode&&(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"";const e=document.createElement("canvas");e.width=this.element.videoWidth,e.height=this.element.videoHeight;return e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(isRequestVideoFrameCallbackSupported()&&this.element&&this._calculateTimeout<0){let e=0,t=null;const i=(r,s)=>{this.stat.width=s.width,this.stat.height=s.height,t&&(this.stat.fps=Math.round((s.presentedFrames-t.presentedFrames)/(r-e)*1e3)),e=r,t=s,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout((()=>{var e;return null==(e=this.element)?void 0:e.requestVideoFrameCallback(i)}),2e3))};this.element.requestVideoFrameCallback(i)}}catch(e){this._log.warn("init stat failed",e)}}};async function loadWorklet(e,t){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await e.audioWorklet.addModule(t),logger_manager_default.info("worklet addModule success")}catch(e){throw logger_manager_default.info(`worklet addModule catch error. ${e.message}`),e}}"undefined"!=typeof AudioContext?AudioContextClass=AudioContext:"undefined"!=typeof webkitAudioContext?AudioContextClass=webkitAudioContext:"undefined"!=typeof mozAudioContext&&(AudioContextClass=mozAudioContext);var retryTimeoutId=-1;function initAudioContext(){try{if(context)return;(context=new AudioContextClass({sampleRate:48e3})).onstatechange=()=>{logger_manager_default.info(`context state: ${context.state}${"running"!==context.state?` visibilityState: ${document.visibilityState}`:""}`),resumeWhenSuspended()},clearTimeout(retryTimeoutId)}catch(e){logger_manager_default.error(`initAudioContext failed: ${e} typeof AudioContextClass: ${typeof AudioContextClass}`),retryTimeoutId=setTimeout(initAudioContext,1e3)}}initAudioContext();var resumeWhenSuspended=()=>{"suspended"===context.state?(resumeContext(),document.addEventListener("click",resumeWhenSuspended)):"interrupted"===context.state?resumeContext():(document.removeEventListener("visibilitychange",resumeWhenSuspended),document.removeEventListener("click",resumeWhenSuspended))},lastResumeTime=0,resumeTimeoutId=-1;function resumeContext(){return new Promise(((e,t)=>{if("running"===context.state)return e();Date.now()-lastResumeTime<1e3?(clearTimeout(resumeTimeoutId),resumeTimeoutId=setTimeout((()=>{lastResumeTime=Date.now(),context.resume().then(e,t)}),1e3)):(clearTimeout(resumeTimeoutId),lastResumeTime=Date.now(),context.resume().then(e,t))})).catch((e=>{logger_manager_default.warn(`context resume failed: ${e}`),document.addEventListener("visibilitychange",resumeWhenSuspended)}))}document.addEventListener("click",resumeWhenSuspended);var getAudioContext=e=>context,AudioNodeConnector=class{constructor(e){this.name=e,__publicField(this,"node"),__publicField(this,"node2"),__publicField(this,"pre",new Set),__publicField(this,"next",new Set),__publicField(this,"context"),__publicField(this,"connectedNodes",new Set),__publicField(this,"nextInputChannelMap",new Map),__publicField(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach((t=>t.channelCount=e))}setChannelCount(e,t){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=t||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&(null==(e=this.context)||e.reduceMixWeight()),delete this.context}replaceNode(e){var t;if(e!==this.node)try{this.node?this._disconnect():null==(t=this.context)||t.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(e){logger_manager_default.error(e)}}setNode(e,t){var i;if(!this.node)try{null==(i=this.context)||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),kv_stat_manager_default.addSuccessEvent({key:502701})}catch(e){logger_manager_default.error(e),kv_stat_manager_default.addFailedEvent({key:502701,error:e})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,null==(e=this.context)||e.reduceMixWeight(),this.preNodeReconnect(),kv_stat_manager_default.addSuccessEvent({key:502702})}catch(e){logger_manager_default.error(e),kv_stat_manager_default.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach((e=>{e.node?e.reconnect():e.preNodeReconnect()}))}connectNext(e){this.next.forEach((t=>{const i=this.nextInputChannelMap.get(t);e._connect(t.node,i)||t.connectNext(e)}))}_connect(e,t=0){return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,t),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach((e=>{var t;return null==(t=this.node2||this.node)?void 0:t.disconnect(e)})),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e,t=0){return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,t),e}},AnalyserNodeConnector=class extends AudioNodeConnector{constructor(e=256){super(),this.fftSize=e,__publicField(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return null==(e=this.node)||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const e=this.getByteTimeDomainData();let t=0,i=0,r=`M${t},${i}`;for(let s=0;s<e.length;s++){i=100*(e[s]/128)/2,r+=`L${t},${i}`,t+=1}return r}},AudioPipeline=class{constructor(){__publicField(this,"source",new AudioNodeConnector),__publicField(this,"gain",new AudioNodeConnector),__publicField(this,"destination",new AudioNodeConnector)}get volume(){var e;return(null==(e=this.gain.node)?void 0:e.gain.value)||1}setVolume(e){1!==e?(this.gain.node||this.gain.setNode(getAudioContext().createGain()),this.gain.node.gain.value=e):this.gain.node&&this.gain.deleteNode()}replaceSource(e){this.source.replaceNode(createAudioNode(e))}get track(){var e;return null==(e=this.stream)?void 0:e.getAudioTracks()[0]}get stream(){var e;return null==(e=this.destination.node)?void 0:e.stream}},audioNodeCache=new WeakMap;function createAudioNode(e){let t=audioNodeCache.get(e);if(t)return t;const i=getAudioContext();if(e instanceof HTMLAudioElement)t=i.createMediaElementSource(e);else{if(!(e instanceof MediaStreamTrack))return e;t=i.createMediaStreamSource(new MediaStream([e]))}return audioNodeCache.set(e,t),t}var _VolumeMeter=class e{constructor(e){__publicField(this,"_volume",0),__publicField(this,"_volumeDb",0),__publicField(this,"_log"),__publicField(this,"_scriptProcessorNode",null),__publicField(this,"_audioWorkletNode",null),__publicField(this,"_interval",200),__publicField(this,"ready",this.preload());const{log:t}=e;this._log=t,inner_emitter_default.on(inner_event_default.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-e.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!e.workletReady){const 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);';e.workletReady=loadWorklet(e.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return e.workletReady.then((()=>this.initAudioWorklet())).catch((e=>(this._log.error(`volumeMeter preload error: ${e}`),this.initScriptProcessor())))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(e.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=i=>{e.lastMessageTime=Date.now(),this._volume=i.data.volume||0,this._volumeDb=i.data.volumeDb||0,!t&&i.data.cacheLen&&i.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){this._log.error(`volumeMeter init audio worklet error: ${e}`),event_log_default.logFailedEvent({userId:this._log.userId,eventType:KIBANA_EVENT.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=getAudioContext("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{e.lastMessageTime=Date.now();const i=t.inputBuffer.getChannelData(0);let r=0;for(let e=0;e<i.length;++e)r+=i[e]*i[e];this._volume=Math.sqrt(r/i.length)||0}}catch(e){this._log.error(`volumeMeter init script processor error: ${e}`)}}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,inner_emitter_default.off(inner_event_default.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(100*this._volumeDb)}handleAudioLevelInterval(e){var t;const{interval:i}=e;this._interval=i,null==(t=this._audioWorkletNode)||t.port.postMessage({name:"setIntervalTime",intervalTime:i})}};__publicField(_VolumeMeter,"lastMessageTime",0),__publicField(_VolumeMeter,"audioContext",getAudioContext("volume-meter")),__publicField(_VolumeMeter,"workletReady");var VolumeMeter=_VolumeMeter,VolumeMeterConnector=class extends AudioNodeConnector{constructor(e){super(),__publicField(this,"_volumeMeter"),this._volumeMeter=new VolumeMeter(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}async init(){await 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){const t=e.allocationSize({planeIndex:0}),i=new Float32Array(t>>2);e.copyTo(i,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:i},[i.buffer]),e.close()}}},import_eventemitter33=__toESM(require_eventemitter3(),1),findByDeviceID=e=>t=>t.deviceId===e,Device=class{constructor(e,t="Input"){__publicField(this,"kind"),__publicField(this,"type"),__publicField(this,"devices",[]),this.kind=e,this.type=t}update(e,t){const i=e.filter((e=>e.kind===`${this.kind}${this.type.toLocaleLowerCase()}`));1===this.devices.length&&isDeviceGotFromWithoutPermission(this.devices[0])||t&&(i.forEach((e=>{if(e.deviceId&&!this.devices.find(findByDeviceID(e.deviceId))){const i=`${this.kind}${this.type}Added`;logger_manager_default.warn(`${i}: ${JSON.stringify(e)}`),t.emit(i,e)}})),this.devices.forEach((e=>{if(e.deviceId&&!i.find(findByDeviceID(e.deviceId))){const i=`${this.kind}${this.type}Removed`;logger_manager_default.warn(`${i}: ${JSON.stringify(e)}`),t.emit(i,e)}}))),this.devices=i}hasDevice(e){return!!this.devices.find((t=>t.deviceId===e))}},DeviceDetector=class extends import_eventemitter33.EventEmitter{constructor(){super(),__publicField(this,"audioInputs",new Device(NAME.AUDIO)),__publicField(this,"videoInputs",new Device(NAME.VIDEO)),__publicField(this,"audioOutputs",new Device(NAME.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",(()=>this.update())),"ondevicechange"in navigator.mediaDevices||timer_default.run("interval",(()=>{this.update()}),{delay:1e4}))}init(){getDevices().then((e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)}))}async update(e=0){const t=await getDevices(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this}},deviceDetector=IS_WORKLET||IS_WORKER?null:new DeviceDetector;function isDeviceGotFromWithoutPermission(e){return e.deviceId===e.groupId&&""===e.groupId}async function getDevices(e=0){if(isUsedInHttpProtocol()||!isMediaDevicesSupported())return[];let t=await navigator.mediaDevices.enumerateDevices();if(0!==e){const i={audio:!1,video:!1};if(t.forEach((e=>{isDeviceGotFromWithoutPermission(e)&&(e.kind===NAME.AUDIO_INPUT?i.audio=!0:e.kind===NAME.VIDEO_INPUT&&(i.video=!0))})),2===e&&(i.audio=!1),1===e&&(i.video=!1),i.audio||i.video){let e;try{e=await navigator.mediaDevices.getUserMedia(i),i.audio&&resumeContext()}catch(e){logger_manager_default.debug("capture before getDevices failed: ",e)}t=await navigator.mediaDevices.enumerateDevices(),null==e||e.getTracks().forEach((e=>e.stop()))}}return t.map(((e,t)=>{const i={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&historyDeviceIdSet.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(i.getCapabilities=()=>e.getCapabilities()),i}))}function getMicrophones(e=!1){return deviceDetector.update(e?1:0).then((e=>e.audioInputs.devices))}function getCameras(e=!1){return deviceDetector.update(e?2:0).then((e=>e.videoInputs.devices))}var isSpeakerLogged=!1;async function logSpeakers(){try{isSpeakerLogged||(isSpeakerLogged=!0,logger_manager_default.info(`speakers:${(await getSpeakers()).map((e=>` ${e.deviceId.slice(0,8)}: ${e.label}`))}`))}catch(e){}}async function getSpeakers(e=!1){return(IS_IOS||IS_SAFARI)&&(e=!1),deviceDetector.update(e?1:0).then((e=>e.audioOutputs.devices))}var cachedElement,historyDeviceIdSet=new Set;function isCameraTrack(e){if(e instanceof CanvasCaptureMediaStreamTrack)return!1;if(!(e instanceof MediaStreamTrack))return!1;const t=e.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;const i=`${((null==e?void 0:e.getSettings())||{}).deviceId}_${NAME.VIDEO_INPUT}`;return!!historyDeviceIdSet.has(i)}function isMicrophoneTrack(e){if(e instanceof CanvasCaptureMediaStreamTrack)return!1;if(!(e instanceof MediaStreamTrack))return!1;const t=e.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("麦克风"))return!0;const i=`${((null==e?void 0:e.getSettings())||{}).deviceId}_${NAME.AUDIO_INPUT}`;return!!historyDeviceIdSet.has(i)}async function isSameDefaultMicrophone(e,t){const i=(await getMicrophones()).find((e=>e.deviceId===MICROPHONE_DEFAULT));return!t&&(null==i?void 0:i.groupId)===e||(null==i?void 0:i.groupId)===e&&i.label===t}async function isSameDevice({newDeviceId:e,oldDeviceId:t,oldGroupId:i,oldLabel:r,kind:s}){return e===t&&(s!==NAME.AUDIO||e!==MICROPHONE_DEFAULT||await isSameDefaultMicrophone(i,r))}var PlayerPipeline=class extends AudioPipeline{constructor(e){super(),this.log=e,__publicField(this,"volumeMeter"),__publicField(this,"volumeDestination"),__publicField(this,"analyser",new AnalyserNodeConnector),this.volumeMeter=new VolumeMeterConnector({log:this.log}),this.volumeDestination=new AudioNodeConnector,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},AudioPlayer=class extends Player{constructor(e){super(e,NAME.AUDIO),__publicField(this,"_outputDeviceId"),__publicField(this,"_volume",1),__publicField(this,"_destination",getAudioContext("player").createMediaStreamDestination()),__publicField(this,"pipeline"),__publicField(this,"volumeMeterMode","worklet"),this.mode=0,this.pipeline=new PlayerPipeline(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if(("15.2"===IOS_VERSION||"15.3"===IOS_VERSION||"15.4"===IOS_VERSION)&&this.muted)return void this._log.info("audioElement is muted.");const t=cachedElement||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,isNumber(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),t===cachedElement&&(cachedElement=void 0),this.bindElementEvents()}async play(e){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(null==e?void 0:e.volume),this._outputDeviceId&&await this.setSinkId(this._outputDeviceId),"worklet"===this.volumeMeterMode?this.pipeline.volumeMeter.init():"analyser"===this.volumeMeterMode&&this.pipeline.analyser.setNode(getAudioContext("player").createAnalyser()),logSpeakers(),super.play()}stop(e=0){this.pipeline.destroy(),super.stop(e)}async setSinkId(e){var t,i;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&await(null==(i=(t=this.element).setSinkId)?void 0:i.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()}},RemoteAudioPlayer=class extends AudioPlayer{constructor(e){super(e),__publicField(this,"_sourceElement"),__publicField(this,"_output",new AudioNodeConnector),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(getAudioContext("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,i,r;(null==(i=null==(t=this.element)?void 0:t.error)?void 0:i.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(PlayerEvent.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=(null==(r=e.getSettings())?void 0:r.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):IS_IOS||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),remove(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();const t=this._sourceElement||this.element;t&&IS_ANY_SAFARI&&(cachedElement=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},Track=class extends FSM{constructor({userId:e,sdkAppId:t,mediaType:i,room:r,PlayerClass:s=(1===i?RemoteAudioPlayer:VideoPlayer)}){var n;super(),__publicField(this,"id",uuid_default()),__publicField(this,"userId",""),__publicField(this,"isRemote"),__publicField(this,"mediaType"),__publicField(this,"room"),__publicField(this,"user"),__publicField(this,"_log"),__publicField(this,"_inputTrack"),__publicField(this,"_outputTrack"),__publicField(this,"isPlayCalled"),__publicField(this,"container",null),__publicField(this,"player"),__publicField(this,"subVideoPlayerMap"),__publicField(this,"muted",!1),__publicField(this,"abortCtrl"),__publicField(this,"objectFit","cover"),__publicField(this,"mirror"),__publicField(this,"rotation"),__publicField(this,"isScreen",!1),__publicField(this,"manager"),__publicField(this,"trackSettings"),__publicField(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=i,this._log=logger_manager_default.createLogger({id:`${this.kind[0]}t`,userId:null==(n=r||this.room)?void 0:n.userId,remoteUserId:this instanceof LocalTrack?void 0:this.userId,sdkAppId:t,type:2===this.mediaType?"auxiliary":"main",isLocal:this instanceof LocalTrack}),this.player=new s({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(PlayerEvent.PLAYER_STATE_CHANGED,(e=>{inner_emitter_default.emit(inner_event_default.PLAYER_STATE_CHANGED,__spreadValues({track:this},e)),this.emit("player-state-changed",e)})),this.kind===NAME.VIDEO&&(this.player.on(PlayerEvent.LOADED_DATA,(()=>{this.emitFirstVideoFrameEvent(PlayerEvent.LOADED_DATA),inner_emitter_default.emit(inner_event_default.VIDEO_LOADED_DATA,{track:this})})),this.player.on(PlayerEvent.LOADED_META_DATA,(()=>{this.emitFirstVideoFrameEvent(PlayerEvent.LOADED_META_DATA)})),this.player.on(PlayerEvent.MEDIA_TRACK_CHANGED,(e=>{var t;null==(t=this.subVideoPlayerMap)||t.forEach((t=>t.setTrack(e)))}))),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(PlayerEvent.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||logger_manager_default}get kind(){return 1===this.mediaType?NAME.AUDIO:NAME.VIDEO}get strMediaType(){return 4===this.mediaType?NAME.VIDEO:2===this.mediaType?NAME.SCREEN:NAME.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&(!this.mediaTrack.muted&&"live"===this.mediaTrack.readyState&&this.mediaTrack.enabled)}async play(e,t){const i=isArray(e)?e[0]:e;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!isUndefined(t.muted)&&this.setPlayerMute(t.muted),t&&!isUndefined(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof VideoPlayer&&(this.player.setObjectFit(this.objectFit),this.container!==i&&i&&(this.container=i,this.player.setContainer(i)),isArray(e)&&e.length>=1&&await this.playSubContainer(e.slice(1),t)));if(t&&!isUndefined(t.muted)?this.setPlayerMute(t.muted):this.isRemote&&this.kind!==NAME.VIDEO||this.setPlayerMute(!0),t&&!isUndefined(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof VideoPlayer&&(this.player.setObjectFit(this.objectFit),t&&!isUndefined(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,i&&(this.container=i,this.player instanceof VideoPlayer&&this.player.setContainer(i)),inner_emitter_default.emit(inner_event_default.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),await this.player.play(t),isArray(e)&&e.length>1&&await this.playSubContainer(e.slice(1),t)}catch(e){throw this.handleAutoPlayFailed(e),e}}else this.log.info("play has not mediaTrack, abort")}setMirror(e,t){if(this.isScreen)return;if(this.kind!==NAME.VIDEO)return;if(isUndefined(e))return;if(e===this.mirror)return;this.mirror=e;let i=this.player;t&&(i=t);const r=this.manager;if(isBoolean(this.mirror))return i.setViewMirror(this.mirror),void(!this.isRemote&&r&&(r.mirror=!1));switch(this.mirror){case"view":r&&(r.mirror=!1),i.setViewMirror(!0);break;case"publish":r&&(r.mirror=!0),i.setViewMirror(!0);break;case"both":r&&(r.mirror=!0),i.setViewMirror(!1)}}async playSubContainer(e,t){if(!this._outputTrack||this.kind===NAME.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach(((t,i)=>{var r;e.find((e=>i===e))||(t.stop(),null==(r=this.subVideoPlayerMap)||r.delete(i))}));for(const[i,r]of e.entries()){const e=this.subVideoPlayerMap.get(r);e?t&&(isUndefined(t.objectFit)||e.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(r,new VideoPlayer({id:this.userId||this.id,track:this.playerMediaTrack,container:r,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${i+1}`})}))}const i=[...this.subVideoPlayerMap.values()];for(const e of i)e.setViewMirror(this.player.mirror),await e.play()}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return(null==(e=this.player)?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(isRemoteTrack2(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach((e=>{e.stop()})),this.container=null)}async resume(){var e;this.isPlayCalled&&await(null==(e=this.player)?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),inner_emitter_default.emit(e?inner_event_default.TRACK_MUTED:inner_event_default.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){create(e,e).add(NAME.MUTE,this.onTrackMuted).add(NAME.UNMUTE,this.onTrackUnmuted).add(NAME.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===NAME.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){remove(e)}setInputMediaStreamTrack(e){var t;const i=this._inputTrack;if(e!==i)return this._inputTrack=e,this.trackSettings=null==(t=e.getSettings)?void 0:t.call(e),e.enabled=!this.muted,i&&this.uninstallTrackEvent(i),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,i||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;e!==this._outputTrack&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",null==(t=e.getSettings)?void 0:t.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)return this.player.play().catch((e=>this.handleAutoPlayFailed(e))),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return this.player.stop(isRemoteTrack2(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`);this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new autoplay_dialog_default;else{const e=()=>{this.resume().then((()=>{document.removeEventListener("click",e,!0)}))};document.addEventListener("click",e,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof VideoPlayer?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var t,i,r;if(this.isFirstVideoFrameEmitted)return;const s=null==(t=this.mediaTrack)?void 0:t.getSettings();let n=(null==s?void 0:s.width)||(null==(i=this.player.element)?void 0:i.videoWidth)||0,a=(null==s?void 0:s.height)||(null==(r=this.player.element)?void 0:r.videoHeight)||0;(e!==PlayerEvent.LOADED_META_DATA||n||a)&&(e!==PlayerEvent.LOADED_DATA||n||a||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,isRotate90Or270(this.rotation)&&([n,a]=[a,n]),this.emit("first-video-frame",{width:n,height:a,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`)}};__decorateClass([ChangeState([],FSM.INIT,{sync:!0})],Track.prototype,"close",1);var has3=Object.prototype.hasOwnProperty,{toString:toString2}=Object.prototype;function isEmpty3(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(isPlainObject(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return 0===e.size;case"[object Object]":for(const t in e)if(has3.call(e,t))return!1;return!0}return!1}var is_empty_default=isEmpty3,getUserMedia_=async function(e){const t=buildConstraints(e);logger_manager_default.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let i=[],r=[];const s=["label","deviceId","groupId"];t.audio&&(i=await getMicrophones(),logger_manager_default.info(`microphones: ${stringify(i.map((e=>__spreadProps(__spreadValues({},e),{groupId:e.groupId.substring(0,8)}))),{keysToInclude:s})}`)),t.video&&(r=await getCameras(),logger_manager_default.info(`cameras: ${stringify(r,{keysToInclude:s})}`));try{const e=await navigator.mediaDevices.getUserMedia(t);return IS_GET_CAPABILITIES_SUPPORTED&&e.getTracks().forEach((e=>{logger_manager_default.info(`${e.kind} capabilities: ${stringify(e.getCapabilities(),{keysToInclude:CAPABILITIES_KEYS})}`)})),t.audio&&resumeContext(),e}catch(t){let{message:s}=t;throw"NotFoundError"===t.name&&(e.video&&r&&0===r.length&&(s=generateErrorMessage({key:ErrorName.CAMERA_NOT_FOUND})),e.audio&&i&&0===i.length&&(s=generateErrorMessage({key:ErrorName.MICROPHONE_NOT_FOUND}))),new rtc_error_default({code:error_code_default.INITIALIZE_FAILED,name:t.name,message:s,constraint:t.constraint})}},getUserMedia=retry_default({retryFunction:getUserMedia_,settings:{retries:3,timeout:500},onError:({error:e,retry:t,reject:i,retryFuncArgs:r,retriedCount:s})=>{const n=s+1;"NotReadableError"===e.name||"OverconstrainedError"===e.name?(1===n?(r[0].video&&(r[0].maxResolution=!1,(!IS_SAFARI||r[0].width*r[0].height<=2073600)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):2===n?r[0].useDeviceIdOnly=!0:3!==n||r[0].useExactDeviceId||(r[0].useTrueAsConstraint=!0),t()):i(e),r[0].microphoneId&&logCapabilities(r[0].microphoneId,!1),r[0].cameraId&&logCapabilities(r[0].cameraId,!0)},onRetrying:e=>{logger_manager_default.warn(`getUserMedia NotReadableError observed, retrying [${e}/3]`)},onRetryFailed:e=>{event_log_default.logFailedEvent({eventType:KIBANA_EVENT.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{event_log_default.logSuccessEvent({eventType:KIBANA_EVENT.GET_USER_MEDIA_RETRY}),event_log_default.uploadEvent({log:`stat-${KIBANA_EVENT.GET_USER_MEDIA_RETRY}-success-${e}`})}});async function logCapabilities(e,t){const i=(t?await getCameras():await getMicrophones()).find((t=>t.deviceId===e));i&&isFunction(i.getCapabilities)&&logger_manager_default.warn(stringify(i.getCapabilities(),{keysToInclude:CAPABILITIES_KEYS}))}function buildConstraints(e){return{audio:buildAudioConstraint(e),video:buildVideoConstraint(e)}}function buildAudioConstraint(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;const t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!is_empty_default(e.microphoneId)&&(t.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?t:(isNumber(e.channelCount)&&(t.channelCount=e.channelCount),isBoolean(e.echoCancellation)&&!e.echoCancellation&&(t.echoCancellation=!1),isBoolean(e.noiseSuppression)&&!e.noiseSuppression&&(t.noiseSuppression=!1),isBoolean(e.autoGainControl)&&!e.autoGainControl&&(t.autoGainControl=!1),!!is_empty_default(t)||t)}function buildVideoConstraint(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;const{maxResolution:t=!0}=e,i={};return e.cameraId?i.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(i.facingMode=e.facingMode),e.useDeviceIdOnly&&!is_empty_default(i)?i:(e.width&&(i.width={ideal:e.width},t&&!IS_FIREFOX&&(i.width.max=e.width)),e.height&&(i.height={ideal:e.height},t&&!IS_FIREFOX&&(i.height.max=e.height)),IS_FIREFOX&&IS_MAC&&e.width&&e.height&&e.width*e.height<101376&&(i.width=e.width,i.height=e.height),e.frameRate&&(i.frameRate=e.frameRate),!!is_empty_default(i)||i)}var get_user_media_default=getUserMedia;function after(e){return createDecorator(((t,i)=>async function(...i){const r=await t.apply(this,i);return await e.call(this,...i),r}))}function catchError(e){return createDecorator(((t,i)=>async function(...i){try{return await t.apply(this,i)}catch(t){e.call(this,t)}}))}function createDecorator(e){return function(t,i,r){return r.value=e(r.value,i),r}}var logVisibilityState=(()=>{let e=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&logger_manager_default.info(`visibility change: ${document.visibilityState}`),e||(document.addEventListener("visibilitychange",(()=>{logger_manager_default.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState})),e=!0)}})(),seq=0,FunctionQueue=class{constructor(){__publicField(this,"log",logger_manager_default.createLogger({id:"fq"+ ++seq})),__publicField(this,"isRunning",!1),__publicField(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return 0===this.length?null:this.queue[this.length-1]}push(e,t=!1){var i,r;const s=__spreadValues({},e),n=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=n,t?this.length<=1?this.queue.push(s):null==(r=null==(i=this.lastQueueItem)?void 0:i.promise)||r.then(s.resolve,s.reject):this.queue.push(s),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),n}shift(){const e=this.queue.shift();return this.log.debug(`shift ${this.length}`),e}callNext(){if(this.isRunning||0===this.length)return;this.log.debug("callNext ",this.length);const{fn:e,args:t,context:i,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,e.apply(i,t).then(r,s).finally((()=>{this.isRunning=!1,this.shift(),this.callNext()}))}},fnQueueMap=new WeakMap;function addCallQueue(e=!1){return function(t,i,r){const s=r.value;return r.value=function(...t){const i=fnQueueMap.get(this)||new FunctionQueue;return fnQueueMap.set(this,i),i.push({fn:s,args:t,context:this},e)},r}}function reportSuccessRate(e,t){return createDecorator(((i,r)=>function(...r){const s=e;try{const e=i.apply(this,r),n=performanceNow();return isPromise(e)?e.then((e=>(t?kv_stat_manager_default.addSuccessEvent({key:s,cost:performanceNow()-n}):kv_stat_manager_default.addSuccessEvent({key:s}),e))).catch((e=>{throw kv_stat_manager_default.addFailedEvent({key:s,error:e}),e})):(kv_stat_manager_default.addSuccessEvent({key:s}),e)}catch(e){throw kv_stat_manager_default.addFailedEvent({key:s,error:e}),e}}))}var LocalTrack=class extends Track{constructor(e,t){super({mediaType:e,PlayerClass:t}),__publicField(this,"isRemote",!1),__publicField(this,"deviceId"),__publicField(this,"groupId",""),__publicField(this,"label",""),__publicField(this,"sourceTrack"),__publicField(this,"_isRecapturing",!1),__publicField(this,"_lastRecaptureTime",0),__publicField(this,"_onMuteTimeoutId",-1),__publicField(this,"_encodeCheckTimeoutId",-1),__publicField(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return"publishing"===this.state.toString()}get isPublished(){return"publish"===this.state}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){create(e,e).add(NAME.MUTE,this.onTrackMuted).add(NAME.UNMUTE,this.onTrackUnmuted).add(NAME.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===NAME.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){remove(e)}setStateToReady(){}async capture(e){var t;try{const i=performanceNow();let r;inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):(null==(t=this.mediaTrack)||t.stop(),r=await get_user_media_default(e));const s=r.getTracks()[0];return await this.setInputMediaStreamTrack(s),e.customSource||(this.sourceTrack=s,this.updateDeviceIdInUse(),this.listenDeviceChange()),inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:performanceNow()-i}),r}catch(e){throw inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:e}),this.log.error(`getUserMedia error observed ${e}`),e}}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return null==(t=this.room)?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.mediaTrack&&IS_GET_SETTINGS_SUPPORTED){const{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:i}=this.mediaTrack;await isSameDevice({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=e,this.label=i,t&&(this.groupId=t),getDevices().then((t=>{const i=t.find((t=>t.deviceId===e));i&&this.emit("2",i)})))}}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===NAME.AUDIO&&!isMicrophoneTrack(this.mediaTrack)||this.kind===NAME.VIDEO&&!isCameraTrack(this.mediaTrack)||this._isRecapturing||e&&IS_MAC&&IS_SAFARI)}onTrackMuted(){super.onTrackMuted(),logVisibilityState(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTime<RECOVER_CAPTURE_INTERVAL?setTimeout((()=>this.onTrackMuted()),RECOVER_CAPTURE_INTERVAL):this._onMuteTimeoutId=setTimeout((async()=>{var e;if(null==(e=this.mediaTrack)?void 0:e.muted){if((IS_IOS||IS_ANDROID)&&"visible"!==document.visibilityState)return;this.recapture(await this.getRecoverCaptureDeviceId())}}),5e3))}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}async onTrackEnded(){super.onTrackEnded(),this.isNeedToRecapture()&&(Date.now()-this._lastRecaptureTime<RECOVER_CAPTURE_INTERVAL?setTimeout((()=>this.onTrackEnded()),RECOVER_CAPTURE_INTERVAL):(this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())))}async recapture(e){var t;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),null==(t=this._inputTrack)||t.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const i={useExactDeviceId:!0};if("user"===e||"environment"===e)i.facingMode=e;else{let t;("audio"===this.kind?await getMicrophones():await getCameras()).find((t=>t.deviceId===e))&&(t=e),i.deviceId=t}return this.capture(i).then((()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_RECAPTURE,{track:this})})).catch((e=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${e.message}`),this.emit("5",e),inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_RECAPTURE,{track:this,error:e})}))}async getRecoverCaptureDeviceId(){const e=this instanceof LocalVideoTrack;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){const i=(captureFailDeviceIdCountMap.get(t)||0)+1;if(captureFailDeviceIdCountMap.set(t,i),i>=3){const r=e?(await getCameras()).find((e=>!captureFailDeviceIdCountMap.has(e.deviceId))):(await getMicrophones()).find((e=>!captureFailDeviceIdCountMap.has(e.deviceId)));r&&(this.log.warn(`${t} capture fail ${i} times, change new ${r.deviceId}`),t=r.deviceId)}}return t}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),null==(e=this.manager)||e.removeInput(this)}close(){super.close(),this.stopCapture()}};__decorateClass([ChangeState(FSM.INIT,"ready",{ignoreError:!0,sync:!0})],LocalTrack.prototype,"setStateToReady",1),__decorateClass([addCallQueue()],LocalTrack.prototype,"capture",1),__decorateClass([ChangeState("ready","publish",{ignoreError:!0,success(){var e,t;this.room.localTracks.add(this),inner_emitter_default.emit(inner_event_default.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"});((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3||(this._encodeCheckTimeoutId=setTimeout((()=>{var e,t;if(!(((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){const e=this.kind===NAME.AUDIO,t=this.stat.bytesSent>0;kv_stat_manager_default[t?"addSuccessEvent":"addFailedEvent"]({key:e?503700:513702}),t||(kv_stat_manager_default.addEnum({key:e?503701:513703,value:getOSNumber()}),event_log_default.uploadEvent({log:`stat-encode-failed-${this.kind}-${getDeviceModel()||getOSString()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}}),5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){const i=e.cause;i.message.includes("timeout")?t="timeout":i.code===error_code_default.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),reportSuccessRate(521714,!1)],LocalTrack.prototype,"publish",1),__decorateClass([createDecorator((e=>async function(){const t="publish"===this.state?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})),ChangeState([],"ready",{sync:!0})],LocalTrack.prototype,"unpublish",1);var captureFailDeviceIdCountMap=new Map;inner_emitter_default.on(inner_event_default.SWITCH_DEVICE_SUCCESS,(e=>{e.track.deviceId&&captureFailDeviceIdCountMap.delete(e.track.deviceId)}));var NALU=class{constructor(e,t=!1){this.dataView=e,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const e=this.seiPayloadStartIndex,t=this.dataView.byteLength-2,i=[];let r=0;for(let s=e;s<=t;s++){const e=this.dataView.getInt8(s);switch(e){case 0:case 1:case 2:case 3:2===r&&(i.push(3),r=0),0==e?r++:r=0,i.push(e);break;default:r=0,i.push(e)}}i.push(this.dataView.getInt8(this.dataView.byteLength-1));const s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=s}removePreventionByte(){const e=this.seiPayloadStartIndex,t=this.dataView.byteLength-1,i=[];let r=0;for(let s=e;s<=t;s++)switch(this.dataView.getInt8(s)){case 0:r++,i.push(this.dataView.getInt8(s));break;case 3:2!==r&&i.push(this.dataView.getInt8(s)),r=0;break;default:i.push(this.dataView.getInt8(s)),r=0}const s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...i]).buffer);this.dataView=s}get isSEI(){return 6===this.dataView.getUint8(4)}get seiPayloadStartIndex(){let e=6;for(let t=6;t<this.dataView.buffer.byteLength&&(e++,255===this.dataView.getUint8(t));t++);return e}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let e=0,t=6;for(let i=6;i<this.dataView.buffer.byteLength;i++){const r=this.dataView.getUint8(i);if(t++,255!==r){e+=r;break}e+=255}const i=new ArrayBuffer(e),r=new DataView(i);for(let e=0;e<i.byteLength;e++,t++)r.setInt8(e,this.dataView.getInt8(t));return r}},SEIEncoder=class{constructor(){__publicField(this,"_seiMessageList",[]),__publicField(this,"_smallSeiMessageList",[]),__publicField(this,"_seiPayloadType",243)}encodeSEINalu(e){const t=e.byteLength,i=parseInt(String(t/255),10),r=t%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let e=0;e<i;e++)s.push(255);s.push(r);const n=new DataView(e);return s.push(...new Uint8Array(n.buffer)),s.push(128),new NALU(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(e,t){(null==t?void 0:t.seiPayloadType)&&(this._seiPayloadType=t.seiPayloadType),this._seiMessageList.push(e),(null==t?void 0:t.small)&&this._smallSeiMessageList.push(e)}isEmpty(){return!this._seiMessageList.length}getNaluCount(e){let t=0,i=0;const r=new DataView(e);for(let s=0;s<e.byteLength;s++)switch(r.getUint8(s)){case 0:t++;break;case 1:2!==t&&3!==t||i++,t=0;break;default:t=0}return i}encode(e,t){const i=t?this._smallSeiMessageList:this._seiMessageList;if(i.length>0&&e.data.byteLength>0){const t=9-this.getNaluCount(e.data);if(t<=0)return 0;const r=i.splice(0,t).reverse().map(this.encodeSEINalu.bind(this)),s=r.reduce(((e,t)=>e+t.dataView.byteLength),0),n=new ArrayBuffer(s+e.data.byteLength),a=new DataView(n),o=new DataView(e.data);let d=0;for(let e=0;e<r.length;e++)for(let t=0;t<r[e].dataView.byteLength;t++)a.setInt8(d++,r[e].dataView.getInt8(t));for(let t=0;t<e.data.byteLength;t++)a.setInt8(d++,o.getInt8(t));return e.data=n,r.length}return 0}},LocalVideoTrack=class extends LocalTrack{constructor(e,t=4){super(t,VideoPlayer),__publicField(this,"profile",__spreadValues({},defaultBigVideoProfile)),__publicField(this,"avoidCropping",!1),__publicField(this,"_scaleResolutionDownBy"),__publicField(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0}),__publicField(this,"small"),__publicField(this,"isNeedToSetBandwidth"),__publicField(this,"muteImage"),__publicField(this,"manager"),__publicField(this,"_seiCodec",new SEIEncoder),this.manager=e;const i=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&"publish"===this.state&&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(__spreadProps(__spreadValues({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",i),this.on("publish",i),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(IS_GET_SETTINGS_SUPPORTED&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return(null==(e=this._inputTrack)?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return"detail"===(null==(e=this._inputTrack)?void 0:e.contentHint)}async setMute(e){var t,i,r;if(isString(e)){if(this.muteImage===e)return;await(null==(t=this.manager)?void 0:t.deleteWatermark("mute")),await(null==(i=this.manager)?void 0:i.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e})),this.muteImage=e,super.setMute(!1)}else this.muteImage&&(await(null==(r=this.manager)?void 0:r.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(e)}capture({deviceId:e,facingMode:t,useExactDeviceId:i=!0,customSource:r,retryWhenExactFailed:s=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:i,retryWhenExactFailed:s,customSource:r})}setProfile(e){const 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(__spreadProps(__spreadValues({},this.profile),{width:1920,height:1080})))}async applyProfile(){var e;if(!this.mediaTrack)return;const{width:t=0,height:i=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=t*i,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(16===IOS_MAIN_VERSION&&this.deviceId?await this.recapture(this.deviceId):(await(null==(e=this.sourceTrack||this.mediaTrack)?void 0:e.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&&"publish"===this.state&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;const{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),i=e*t;return n&&i&&r&&i===r?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:NAME.VIDEO,videoType:NAME.BIG})}}get settings(){const e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return IS_GET_SETTINGS_SUPPORTED&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:calculateScaleResolutionDownNumber(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||(!!this.isScreen||(e.height*e.width<3686400||1===(null==(t=this.room.scheduleResult.trtcAutoConf)?void 0:t["2k4k"])))}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}async switchDevice(e){try{if(!this.isNeedToSwitchDevice(e))return;const t={useExactDeviceId:!0,retryWhenExactFailed:!1};"user"===e||"environment"===e?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),await this.capture(t),inner_emitter_default.emit(inner_event_default.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(e){throw this.log.error(`switch camera failed ${e}`),this.deviceId&&this.recapture(this.deviceId),e}}updateSmallConfig(e){var t,i;this._log.info(`update small stream config: ${JSON.stringify(e)}`);const r=!this.small;this.small=this.fallbackProfile(e,!0),null==(t=this.manager)||t.update(),r&&(null==(i=this.room)||i.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){const i=e.width>e.height,r=__spreadValues({},e);return e.width*e.height<=19200&&IS_ANDROID&&IS_CHROMIUM_BASE&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),r.width=i?240:180,r.height=i?180:240,r.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&IS_IOS_13_OR_14&&(r.width=i?1280:720,r.height=i?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),isVersionSmallerThan(IOS_VERSION,"14.3")&&isVersionLargerThan(IOS_VERSION,"14.0",!0)&&this.on("7",(()=>{const e=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=e?640:480,this.profile.height=e?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=e?640:360,this.profile.height=e?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))})),!t&&this.avoidCropping&&(IS_CHROMIUM_BASE||IS_FIREFOX)&&!isMobile()&&e.width*e.height<=230400&&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}`)),r}stopSmall(){var e,t;this.small&&(delete this.small,null==(e=this.manager)||e.update(),null==(t=this.room)||t.enableSmall(!1))}listenDeviceChange(){deviceDetector&&!deviceDetector.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&deviceDetector.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(e){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),addMonitorEvent(this.userId,{eventId:2003,param1:7,streamType:2});const t=await getCameras();t[0]?this.recapture(t[0].deviceId):deviceDetector.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(e){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}encodeFrame(e,t){if(!this.manager)return e;const i=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight(((e,t)=>t?t({frame:e,mediaType:i}):e),e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some((e=>e))}play(e,t){return isUndefined(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){deviceDetector.off("videoInputAdded",this.handleCameraAdded,this),deviceDetector.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(e){try{await super.recapture(e)}catch(t){const i=(await getCameras()).find((t=>t.deviceId!==e));if(!i)throw t;await super.recapture(i.deviceId)}}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||isUndefined(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};__decorateClass([after((function(e){this.setContentHint(e.contentHint||"motion")}))],LocalVideoTrack.prototype,"capture",1);var positions=[-1,-1,1,-1,-1,1,1,1],texCoords=[0,0,1,0,0,1,1,1],VideoNode=class extends FSM{constructor(e,t){if(super(),this.context=e,__publicField(this,"name"),__publicField(this,"input"),__publicField(this,"output"),__publicField(this,"texture"),__publicField(this,"ctx2d",null),__publicField(this,"fbo"),__publicField(this,"width",0),__publicField(this,"height",0),__publicField(this,"x",0),__publicField(this,"y",0),__publicField(this,"program"),__publicField(this,"vertexShader"),__publicField(this,"fragmentShader"),__publicField(this,"totalFrames",0),__publicField(this,"dropFrames",0),__publicField(this,"matchInputSize",!0),__publicField(this,"texCoordBuffer"),__publicField(this,"positionBuffer"),__publicField(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),__publicField(this,"cost",0),__publicField(this,"_canvas",null),__publicField(this,"_image"),__publicField(this,"log"),this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=!1!==t.matchInputSize,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Video2dContext)e.ctx&&t.create2d&&("function"==typeof OffscreenCanvas&&16!==IOS_MAIN_VERSION?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);else try{const i=e.ctx;this.texCoordBuffer=this.createBuffer(texCoords),this.positionBuffer=this.createBuffer(positions),!1!==t.createTexture&&(this.texture=i.createTexture(),this.useTexture(),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.pixelStorei(i.PACK_ALIGNMENT,1),i.pixelStorei(i.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=i.createFramebuffer(),this.useBufferFrame(),this.useTexture(),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,this.width,this.height,0,i.RGBA,i.UNSIGNED_BYTE,null),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(i.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(i.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(e){this.context.destroy(new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${e.message||e}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){const t=this.context.ctx,i=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),i}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){const t=Date.now();return!!(this.context instanceof VideoGlContext&&this.render(e)||this.context instanceof Video2dContext&&this.render2d(e))&&(this.totalFrames++,this.cost=Date.now()-t,!0)}render2d(e){var t;return!!(null==(t=this.input)?void 0:t.requestFrame(e))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(e=0){var t;null==(t=this.output)||t.update(e)}disconnect(...e){var t;null==(t=this.output)||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),null==(e=this.output)||e.removeInput(this),delete this.output,null==(t=this.input)||t.disconnect(),this.context instanceof VideoGlContext){const e=this.context.ctx;e.deleteBuffer(this.texCoordBuffer),e.deleteBuffer(this.positionBuffer),this.fbo&&e.deleteFramebuffer(this.fbo),this.texture&&e.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&e.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&e.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&e.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(null==(e=this.input)?void 0:e.texture)}useTextures(...e){const t=this.context.ctx;e.forEach(((e,i)=>{e&&(t.activeTexture(t.TEXTURE0+i),t.bindTexture(t.TEXTURE_2D,e))}))}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){const t=this.context.ctx,i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),i}setTexBuffer(e){const t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){const 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){const i=this.context.ctx;i.bindBuffer(i.ARRAY_BUFFER,e),i.bufferData(i.ARRAY_BUFFER,new Float32Array(t),i.STATIC_DRAW)}setAttributes(...e){const t=this.context.ctx;e.forEach(((e,i)=>{t.enableVertexAttribArray(i),t.bindBuffer(t.ARRAY_BUFFER,e),t.vertexAttribPointer(i,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();const i=this.context.ctx;i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);const i=this.context.ctx;i.drawArrays(i.TRIANGLE_STRIP,0,4)}draw2d(e,t,i,r,s,n,a,o,d){const l=!(isUndefined(n)||isUndefined(a)||isUndefined(o)||isUndefined(d));return!(!this.ctx2d||!e)&&(e instanceof ImageData?l?this.ctx2d.putImageData(e,t,i,n,a,o,d):this.ctx2d.putImageData(e,t,i):(l?this.ctx2d.drawImage(e,n,a,o,d,t,i,r,s):this.ctx2d.drawImage(e,t,i,r,s),"undefined"!=typeof VideoFrame&&e instanceof VideoFrame&&e.close()),!0)}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 e;const{totalFrames:t,x:i,y:r,width:s,height:n,name:a,cost:o}=this,d=Date.now(),l=(t-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:t,x:i,y:r,width:s,height:n,timestamp:d,fps:l,name:a,cost:o},__spreadValues({parent:null==(e=this.input)?void 0:e.getInfo()},this.lastInfo)}createTexture(e){const t=this.context.ctx,i=t.createTexture();return this.useTextures(i),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),i}};function nothing(...e){}__decorateClass([ChangeState(FSM.INIT,"connected",{sync:!0})],VideoNode.prototype,"connect",1),__decorateClass([ChangeState("connected",FSM.INIT,{ignoreError:!0,sync:!0})],VideoNode.prototype,"disconnect",1),__decorateClass([ChangeState([],"closed",{sync:!0})],VideoNode.prototype,"close",1);var call=e=>e();function dispose(){this.dispose()}var inspect=()=>"undefined"!=typeof __FASTRX_DEVTOOLS__,obids=1,Inspect=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(e){const t=new NodeSink(e,this,this.streamId++);return Events.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},LastSink=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=nothing,this.error=nothing,this.next=nothing,this.dispose=nothing,this.subscribe=nothing,this.doDefer()}subscribe(e){return e instanceof Inspect?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(call),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}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}},Sink=class extends LastSink{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}},Subscribe=class extends LastSink{constructor(e,t=nothing,i=nothing,r=nothing){if(super(),this._next=t,this._error=i,this._complete=r,this.then=nothing,e instanceof Inspect){const s={toString:()=>"subscribe",id:0,source:e};this.defer((()=>{Events.defer(s,0)})),Events.create(s),Events.pipe(s),this.sourceId=s.id,this.subscribe(e),Events.subscribe({id:s.id,end:!0}),t==nothing?this._next=e=>Events.next(s,0,e):this.next=e=>{Events.next(s,0,e),t(e)},r==nothing?this._complete=()=>Events.complete(s,0):this.complete=()=>{this.dispose(),Events.complete(s,0),r()},i==nothing?this._error=e=>Events.complete(s,0,e):this.error=e=>{this.dispose(),Events.complete(s,0,e),i()}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function pipe(e,...t){return t.reduce(((e,t)=>t(e)),e)}function create2(e,t,i){if(inspect()){const r=Object.defineProperties(Object.setPrototypeOf(e,Inspect.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:i,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Events.create(r);for(let e=0;e<i.length;e++){const t=i[e];"function"==typeof t&&t instanceof Inspect&&Events.addSource(r,t)}return r}return e}function deliver(e,t){return function(...i){return r=>{if(r instanceof Inspect){const s=create2((t=>{const n=new e(t,...i);n.sourceId=s.id,n.subscribe(r)}),t,arguments);return s.source=r,Events.pipe(s),s}return t=>r(new e(t,...i))}}}function send(e,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:t}})}var NodeSink=class extends Sink{constructor(e,t,i){super(e),this.source=t,this.id=i,this.sourceId=e.sourceId,this.defer((()=>{Events.defer(this.source,this.id)}))}next(e){Events.next(this.source,this.id,e),this.sink.next(e)}complete(){Events.complete(this.source,this.id),this.sink.complete()}error(e){Events.complete(this.source,this.id,e),this.sink.error(e)}},Events={addSource(e,t){send("addSource",{id:e.id,name:e.toString(),source:{id:t.id,name:t.toString()}})},next(e,t,i){send("next",{id:e.id,streamId:t,data:i&&i.toString()})},subscribe({id:e,end:t},i){send("subscribe",{id:e,end:t,sink:{nodeId:i&&i.nodeId,streamId:i&&i.streamId}})},complete(e,t,i){send("complete",{id:e.id,streamId:t,err:i?i.toString():null})},defer(e,t){send("defer",{id:e.id,streamId:t})},pipe(e){send("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){send("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=obids++),send("create",{name:e.toString(),id:e.id})}},TimeoutError=class extends Error{constructor(e){super(`timeout after ${e}ms`),this.timeout=e}},Share=class extends LastSink{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer((()=>this.remove(e))),1===this.sinks.add(e).size&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),0===this.sinks.size&&this.dispose()}next(e){this.sinks.forEach((t=>t.next(e)))}complete(){this.sinks.forEach((e=>e.complete())),this.sinks.clear()}error(e){this.sinks.forEach((t=>t.error(e))),this.sinks.clear()}};function share(){return e=>{const t=new Share(e);if(e instanceof Inspect){const i=create2((e=>{t.add(e)}),"share",arguments);return t.sourceId=i.id,i.source=e,Events.pipe(i),i}return create2(t.add.bind(t),"share",arguments)}}function merge(...e){return create2((t=>{const i=new Sink(t);let r=e.length;i.complete=()=>{0==--r&&t.complete()},e.forEach(i.bindSubscribe)}),"merge",arguments)}function race(...e){return create2((t=>{const i=new Map;e.forEach((e=>{const r=new Sink(t);i.set(e,r),r.complete=()=>{i.delete(e),0===i.size?t.complete():r.dispose()},r.next=t=>{i.delete(e),i.forEach((e=>e.dispose())),r.resetNext(),r.resetComplete(),r.next(t)}})),e.forEach((e=>i.get(e).subscribe(e)))}),"race",arguments)}function combineLatest(...e){return create2((t=>{const i=e.length;let r=i,s=i;const n=new Array(i),a=()=>{0==--s&&t.complete()};e.forEach(((e,i)=>{const s=new Sink(t);s.next=e=>{0==--r?(s.next=e=>{n[i]=e,t.next(n)},s.next(e)):n[i]=e},s.complete=a,s.subscribe(e)}))}),"combineLatest",arguments)}function startWith(...e){return t=>create2(((i,r=0,s=e.length)=>{for(;r<s&&!i.disposed;)i.next(e[r++]);i.disposed||i.subscribe(t)}),"startWith",arguments)}var WithLatestFrom=class extends Sink{constructor(e,...t){super(e);const i=new Sink(this.sink);i.next=e=>this.buffer=e,i.complete=nothing,i.subscribe(combineLatest(...t))}next(e){this.buffer&&this.sink.next([e,...this.buffer])}},withLatestFrom=deliver(WithLatestFrom,"withLatestFrom"),BufferCount=class extends Sink{constructor(e,t,i){super(e),this.bufferSize=t,this.startBufferEvery=i,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(e){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach((t=>{t.push(e)})),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(e),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((e=>this.sink.next(e))),super.complete()}},bufferCount=deliver(BufferCount,"bufferCount"),Buffer2=class extends Sink{constructor(e,t){super(e),this.buffer=[];const i=new Sink(e);i.next=t=>{e.next(this.buffer),this.buffer=[]},i.complete=nothing,i.subscribe(t)}next(e){this.buffer.push(e)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},buffer=deliver(Buffer2,"buffer");function subject(e){const t=arguments,i=share()(create2((t=>{i.next=e=>t.next(e),i.complete=()=>t.complete(),i.error=e=>t.error(e),e&&t.subscribe(e)}),"subject",t));return i.next=nothing,i.complete=nothing,i.error=nothing,i}function interval(e){return create2((t=>{let i=0;const r=setInterval((()=>t.next(i++)),e);return t.defer((()=>{clearInterval(r)})),"interval"}),"interval",arguments)}function timer(e,t){return create2((i=>{let r=0;const s=setTimeout((()=>{if(i.removeDefer(n),i.next(r++),t){const e=setInterval((()=>i.next(r++)),t);i.defer((()=>{clearInterval(e)}))}else i.complete()}),e),n=()=>{clearTimeout(s)};i.defer(n)}),"timer",arguments)}function _fromEventPattern(e,t){return i=>{const r=e=>i.next(e);i.defer((()=>t(r))),e(r)}}function fromEvent(e,t){if("on"in e&&"off"in e)return create2(_fromEventPattern((i=>e.on(t,i)),(i=>e.off(t,i))),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return create2(_fromEventPattern((i=>e.addListener(t,i)),(i=>e.removeListener(t,i))),"fromEvent",arguments);if("addEventListener"in e)return create2(_fromEventPattern((i=>e.addEventListener(t,i)),(i=>e.removeEventListener(t,i))),"fromEvent",arguments);throw"target is not a EventDispachter"}function empty(){return create2((e=>e.complete()),"empty",arguments)}var Reduce=class extends Sink{constructor(e,t,i){super(e),this.f=t;const r=()=>{this.sink.next(this.acc),this.sink.complete()};void 0===i?this.next=e=>{this.acc=e,this.complete=r,this.resetNext()}:(this.acc=i,this.complete=r)}next(e){this.acc=this.f(this.acc,e)}},reduce=deliver(Reduce,"reduce"),Filter=class extends Sink{constructor(e,t,i){super(e),this.filter=t,this.thisArg=i}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},filter=deliver(Filter,"filter"),Ignore=class extends Sink{next(e){}},ignoreElements=deliver(Ignore,"ignoreElements"),Take=class extends Sink{constructor(e,t){super(e),this.count=t}next(e){this.sink.next(e),0==--this.count&&this.complete()}},take=deliver(Take,"take"),TakeUntil=class extends Sink{constructor(e,t){super(e);const i=new Sink(e);i.next=()=>e.complete(),i.complete=dispose,i.subscribe(t)}},takeUntil=deliver(TakeUntil,"takeUntil"),TakeWhile=class extends Sink{constructor(e,t){super(e),this.f=t}next(e){this.f(e)?this.sink.next(e):this.complete()}},takeWhile=deliver(TakeWhile,"takeWhile"),Skip=class extends Sink{constructor(e,t){super(e),this.count=t}next(e){0==--this.count&&(this.next=super.next)}},skip=deliver(Skip,"skip"),SkipUntil=class extends Sink{constructor(e,t){super(e),e.next=nothing;const i=new Sink(e);i.next=()=>{i.dispose(),e.resetNext()},i.complete=dispose,i.subscribe(t)}},skipUntil=deliver(SkipUntil,"skipUntil"),SkipWhile=class extends Sink{constructor(e,t){super(e),this.f=t}next(e){this.f(e)||(this.next=super.next,this.next(e))}},skipWhile=deliver(SkipWhile,"skipWhile"),defaultThrottleConfig={leading:!0,trailing:!1},_Throttle=class extends Sink{constructor(e,t,i){super(e),this.durationSelector=t,this.trailing=i}cacheValue(e){this.last=e,this.disposed&&this.throttle(e)}send(e){this.sink.next(e),this.throttle(e)}throttle(e){this.reset(),this.subscribe(this.durationSelector(e))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Throttle=class extends Sink{constructor(e,t,i=defaultThrottleConfig){super(e),this.durationSelector=t,this.config=i,this._throttle=new _Throttle(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(e){this._throttle.disposed&&this.config.leading?this._throttle.send(e):this._throttle.cacheValue(e)}complete(){this._throttle.throttle=nothing,this._throttle.complete(),super.complete()}},throttle=deliver(Throttle,"throttle"),_Debounce=class extends Sink{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Debounce=class extends Sink{constructor(e,t){super(e),this.durationSelector=t,this._debounce=new _Debounce(this.sink),this._debounce.dispose()}next(e){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=e,this._debounce.subscribe(this.durationSelector(e))}complete(){this._debounce.complete(),super.complete()}},debounce=deliver(Debounce,"debounce"),ElementAt=class extends Sink{constructor(e,t,i){super(e),this.count=t,this.defaultValue=i}next(e){0==this.count--&&(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},elementAt=deliver(ElementAt,"elementAt"),FindIndex=class extends Sink{constructor(e,t){super(e),this.f=t,this.i=0}next(e){this.f(e)?(this.sink.next(this.i++),this.complete()):++this.i}},findIndex=deliver(FindIndex,"findIndex"),First=class extends Sink{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){this.f&&!this.f(e,this.index++)||(this.defaultValue=e,this.complete())}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},first=deliver(First,"first"),Last=class extends Sink{constructor(e,t,i){super(e),this.f=t,this.defaultValue=i,this.index=0}next(e){this.f&&!this.f(e,this.index++)||(this.defaultValue=e)}complete(){void 0!==this.defaultValue?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},last=deliver(Last,"last"),Every=class extends Sink{constructor(e,t){super(e),this.predicate=t,this.index=0}next(e){this.predicate(e,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){void 0!==this.result?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},every=deliver(Every,"every"),Scan=class extends Sink{constructor(e,t,i){super(e),this.f=t,void 0===i?this.next=e=>{this.acc=e,this.resetNext(),this.sink.next(this.acc)}:this.acc=i}next(e){this.sink.next(this.acc=this.f(this.acc,e))}},scan=deliver(Scan,"scan"),Pairwise=class extends Sink{constructor(){super(...arguments),this.hasLast=!1}next(e){this.hasLast?this.sink.next([this.last,e]):this.hasLast=!0,this.last=e}},pairwise=deliver(Pairwise,"pairwise"),MapObserver=class extends Sink{constructor(e,t,i){super(e),this.mapper=t,this.thisArg=i}next(e){super.next(this.mapper.call(this.thisArg,e))}},map=deliver(MapObserver,"map"),InnerSink=class extends Sink{constructor(e,t,i){super(e),this.data=t,this.context=i}next(e){const t=this.context.combineResults;t?this.sink.next(t(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},Maps=class extends Sink{constructor(e,t,i){super(e),this.makeSource=t,this.combineResults=i,this.index=0}subInner(e,t){const i=this.currentSink=new t(this.sink,e,this);this.complete=this.tryComplete,i.complete=i.tryComplete,i.subscribe(this.makeSource(e,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},_SwitchMap=class extends InnerSink{},SwitchMap=class extends Maps{next(e){this.subInner(e,_SwitchMap),this.next=e=>{this.currentSink.dispose(),this.subInner(e,_SwitchMap)}}},switchMap=deliver(SwitchMap,"switchMap");function makeMapTo(e){return(t,i)=>e((()=>t),i)}var switchMapTo=makeMapTo(deliver(SwitchMap,"switchMapTo")),_ConcatMap=class extends InnerSink{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},ConcatMap=class extends Maps{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(e){this.next2(e),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),_ConcatMap),this.disposed&&0===this.sources.length&&this.currentSink.resetComplete()}tryComplete(){0===this.sources.length&&this.currentSink.resetComplete(),this.dispose()}},concatMap=deliver(ConcatMap,"concatMap"),concatMapTo=makeMapTo(deliver(ConcatMap,"concatMapTo")),_MergeMap=class extends InnerSink{tryComplete(){this.context.inners.delete(this),super.dispose(),0===this.context.inners.size&&this.context.resetComplete()}},MergeMap=class extends Maps{constructor(){super(...arguments),this.inners=new Set}next(e){this.subInner(e,_MergeMap),this.inners.add(this.currentSink)}tryComplete(){1===this.inners.size?this.inners.forEach((e=>e.resetComplete())):this.dispose()}},mergeMap=deliver(MergeMap,"mergeMap"),mergeMapTo=makeMapTo(deliver(MergeMap,"mergeMapTo")),_ExhaustMap=class extends InnerSink{dispose(){this.context.resetNext(),super.dispose()}},ExhaustMap=class extends Maps{next(e){this.next=nothing,this.subInner(e,_ExhaustMap)}},exhaustMap=deliver(ExhaustMap,"exhaustMap"),exhaustMapTo=makeMapTo(deliver(ExhaustMap,"exhaustMapTo")),GroupBy=class extends Sink{constructor(e,t){super(e),this.f=t,this.groups=new Map}next(e){const t=this.f(e);let i=this.groups.get(t);void 0===i&&(i=subject(),i.key=t,this.groups.set(t,i),super.next(i)),i.next(e)}complete(){this.groups.forEach((e=>e.complete())),super.complete()}error(e){this.groups.forEach((t=>t.error(e))),super.error(e)}},groupBy=deliver(GroupBy,"groupBy"),TimeInterval=class extends Sink{constructor(){super(...arguments),this.start=new Date}next(e){this.sink.next({value:e,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},timeInterval=deliver(TimeInterval,"timeInterval"),BufferTime=class extends Sink{constructor(e,t){super(e),this.miniseconds=t,this.buffer=[],this.id=setInterval((()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0}),this.miniseconds)}next(e){this.buffer.push(e)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},bufferTime=deliver(BufferTime,"bufferTime"),Delay=class extends Sink{constructor(e,t){super(e),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(e){this.timeoutId=setTimeout((()=>{const e=this.buffer.shift();if(e){const{time:t,data:i}=e;super.next(i),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}}),e)}next(e){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:e})}complete(){this.timeoutId=setTimeout((()=>super.complete()),this.delayTime)}},delay2=deliver(Delay,"delay"),CatchError=class extends Sink{constructor(e,t){super(e),this.selector=t}error(e){this.dispose(),this.selector(e)(this.sink)}},catchError2=deliver(CatchError,"catchError"),subscribe=(e=nothing,t=nothing,i=nothing)=>r=>new Subscribe(r,e,t,i),Tap=class extends Sink{constructor(e,t){super(e),t instanceof Function?this.next=i=>{t(i),e.next(i)}:(t.next&&(this.next=i=>{t.next(i),e.next(i)}),t.complete&&(this.complete=()=>{t.complete(),e.complete()}),t.error&&(this.error=i=>{t.error(i),e.error(i)}))}},tap=deliver(Tap,"tap"),Timeout=class extends Sink{constructor(e,t){super(e),this.timeout=t,this.id=setTimeout((()=>this.error(new TimeoutError(this.timeout))),this.timeout)}next(e){super.next(e),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},timeout=deliver(Timeout,"timeout"),tick250msOb=pipe(interval(250),map((()=>performance.now())),share()),mcTimeout=e=>t=>{const i=performance.now();pipe(tick250msOb,skipWhile((t=>t-i<e)),take(1))(t)},texCoords2=[0,1,1,1,0,0,1,0],VideoDestinationNode=class extends VideoNode{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),__publicField(this,"_intervalId",0),__publicField(this,"_sequence",0),__publicField(this,"checkGLError",!1),__publicField(this,"checkVisibilityChange"),e instanceof Video2dContext?this.ctx2d=e.ctx||null:e.available&&(null==t?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(texCoords2)}start(e){this.log.info(`${this.name} start render ${e} fps`),timer_default.clearTask(this._intervalId),this._intervalId=timer_default.run("intervalInWorker",(()=>{if(e!==this.context.frameRate&&(timer_default.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof VideoGlContext){const e=this.context.ctx.getError();e&&this.context.destroy(new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${e}`}))}}),{fps:this.context.frameRate})}render(e){var t;return!!(null==(t=this.input)?void 0:t.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this._intervalId&&(timer_default.clearTask(this._intervalId),this._intervalId=0,1===e&&(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),timer_default.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),timer_default.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},VideoTrackDestination=class extends VideoDestinationNode{constructor(e,t){super(e,t),__publicField(this,"_videoTrack"),__publicField(this,"_muteOb"),__publicField(this,"_closedOb",fromEvent(this,"closed")),__publicField(this,"_subscription"),__publicField(this,"_canvasContainer"),Number(SAFARI_VERSION)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=fromEvent(this._videoTrack,"mute"),pipe(fromEvent(this._videoTrack,"ended"),takeUntil(this._closedOb),subscribe((()=>{this.context.destroy(new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))})))}enableCheckMute(){this._subscription=pipe(this._muteOb,takeUntil(this._closedOb),switchMapTo(mcTimeout(5e3)),filter((()=>{var e;return!!(null==(e=this._videoTrack)?void 0:e.muted)&&!document.hidden})),subscribe((()=>{this.context.destroy(new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))})))}disableCheckMute(){var e;null==(e=this._subscription)||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(),null==(e=this._videoTrack)||e.stop(),delete this._videoTrack,null==(t=this._canvasContainer)||t.remove()}},VideoImageSourceNode=class extends VideoNode{constructor(e,t){super(e,__spreadValues({name:"imageSource"},t)),__publicField(this,"_lastImage"),__publicField(this,"_totalFrames",0),__publicField(this,"_autoResize",!1),__publicField(this,"_canvasRendered"),__publicField(this,"_videoCallbackId",0),__publicField(this,"waitingFirstFrame",!0),__publicField(this,"shouldUpdate",!0),this._autoResize=!1!==(null==t?void 0:t.autoResize),16===IOS_MAIN_VERSION&&(this._canvasRendered=subject(),pipe(this._canvasRendered,startWith(this._image),switchMap((e=>e instanceof HTMLCanvasElement?fromEvent(e,"rendered"):empty())),takeUntil(fromEvent(this,"closed")),subscribe((()=>{this.update()}))))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),isRequestVideoFrameCallbackSupported()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback(((e,t)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=t.presentedFrames,this.update(1))})))}_render(e,t){var i;let{width:r,height:s}=this;const{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):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame&&(({displayWidth:r,displayHeight:s}=n),null==(i=this._lastImage)||i.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();const e=this.context.ctx;e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();const e=this.context.ctx;e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;null==(t=this._canvasRendered)||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},VideoPlayerSourceNode=class extends VideoImageSourceNode{constructor(e,t,i){super(e,i),this._player=t,this.name="videoPlayerSource",pipe(fromEvent(this._player,PlayerEvent.PLAYER_STATE_CHANGED),takeUntil(fromEvent(this,"closed")),filter((({state:e})=>"PLAYING"===e)),subscribe((()=>{this.tryVideoFrameCallback()})))}get image(){return this._player.element}},VideoTrackSourceNode=class extends VideoPlayerSourceNode{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,t,i){super(e,new VideoPlayer({id:i.name,track:t,muted:!0,container:null,objectFit:"contain",log:i.logger}),i),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},TextSourceNode=class extends VideoNode{constructor(e,t,i){super(e,__spreadProps(__spreadValues({name:"textSource"},i),{create2d:!0})),__publicField(this,"hasChange",!0),__publicField(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(null==(e=this.ctx2d)?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return(null==(e=this.ctx2d)?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)}render(e){return!1}resize(e,t){if(!this.ctx2d)return;const{color:i,font:r}=this;super.resize(e,t),this.color=i,this.font=r}drawMultilineText(e=0,t=0,i=1.2){if(!this.ctx2d)return;const r=this.ctx2d.measureText(this.content);t+=r.fontBoundingBoxAscent||r.actualBoundingBoxAscent||0;const s=this.font.match(/(\d+)px/),n=(s?parseInt(s[1],10):16)*i,a=this.content.split("\n");for(let i=0;i<a.length;i++)this.ctx2d.fillText(a[i],e,t+i*n)}},vertexShaderSource="\n// 顶点着色器\nattribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_texCoord;\n\nvoid main() {\n gl_Position = a_position;\n v_texCoord = a_texCoord;\n}\n",fragmentShaderSource="\n// 片元着色器\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\n\nvoid main() {\n gl_FragColor = texture2D(u_texture, v_texCoord);\n} ",VideoContext=class extends FSM{constructor(e){super(),__publicField(this,"frameRate"),__publicField(this,"_canvas"),__publicField(this,"log"),__publicField(this,"hasAlpha",!1),__publicField(this,"name"),__publicField(this,"error"),this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return(null==(e=this._canvas)?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return(null==(e=this._canvas)?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new VideoTrackSourceNode(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new VideoTrackDestination(this,e)}createVideoImageSource(e,t){return new VideoImageSourceNode(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new VideoPlayerSourceNode(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new TextSourceNode(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return"created"===this.state}disconnect(){this.emit("disconnect")}};__publicField(VideoContext,"_ids",0);var WEBGL_ATTRIBUTES={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_VideoGlContext=class extends VideoContext{constructor(){super(...arguments),__publicField(this,"defaultProgam"),__publicField(this,"defaultVShader"),__publicField(this,"defaultFShader"),__publicField(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${VideoContext._ids++}`),this.ctx=this._canvas.getContext("webgl2",WEBGL_ATTRIBUTES),!this.ctx)throw new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,vertexShaderSource),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,fragmentShaderSource),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",(()=>{this.destroy(new rtc_error_default({code:error_code_default.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}))}destroy(e){let t="";return e&&(t=e.message,this.error=e,kv_stat_manager_default.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;null==(t=this.ctx)||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;null==(t=this.ctx)||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var i;null==(i=this.ctx)||i.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){const i=this.ctx,r=i.createShader(e);return i.shaderSource(r,t),i.compileShader(r),r}createProgram(e,t){const i=this.ctx,r=i.createProgram();return i.attachShader(r,e),i.attachShader(r,t),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||this.log.error(i.getProgramInfoLog(r)),r}};__publicField(_VideoGlContext,"UNAVAILABLE","unavailable"),__decorateClass([ChangeState(FSM.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),kv_stat_manager_default.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),kv_stat_manager_default.addSuccessEvent({key:512700})}})],_VideoGlContext.prototype,"create",1),__decorateClass([ChangeState("created",FSM.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_VideoGlContext.UNAVAILABLE,e),this.removeAllListeners()}})],_VideoGlContext.prototype,"destroy",1);var VideoGlContext=_VideoGlContext,Video2dContext=class extends VideoContext{constructor(){super(...arguments),__publicField(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${VideoContext._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new rtc_error_default({code:error_code_default.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,kv_stat_manager_default.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(),kv_stat_manager_default.addSuccessEvent({key:512703})}};__decorateClass([ChangeState(FSM.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),kv_stat_manager_default.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),kv_stat_manager_default.addSuccessEvent({key:512701})}})],Video2dContext.prototype,"create",1),__decorateClass([ChangeState("created",FSM.INIT,{ignoreError:!0,sync:!0})],Video2dContext.prototype,"destroy",1);var currentTabID=uuid_default();if("undefined"!=typeof navigator&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:currentTabID,exposeOrigin:!0,permittedOrigins:["*"]})}catch(e){}var getDisplayMedia=async function(e){let t=null;const i=buildScreenConstraints(e);logger_manager_default.info(`getDisplayMedia with constraints: ${JSON.stringify(i)}`);const r=await navigator.mediaDevices.getDisplayMedia(i);e.systemAudio&&0===r.getAudioTracks().length&&(IS_CHROME&&CHROME_MAJOR_VERSION<74||IS_SAFARI||IS_FIREFOX)&&logger_manager_default.warn("Your browser not support capture system audio");const s=r.getVideoTracks()[0];if(s){if(e.frameRate)try{await s.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(e){logger_manager_default.warn(`screen applyConstraints failed: ${e}`)}e.captureElement&&await cropCurrentTabVideoTrackTo(s,e.captureElement)}if(e.audio){const i=buildConstraints2(e);logger_manager_default.info(`getUserMedia with constraints: ${JSON.stringify(i)}`),t=await navigator.mediaDevices.getUserMedia(i),r.addTrack(t.getAudioTracks()[0])}return r};async function cropCurrentTabVideoTrackTo(e,t){var i;if("CropTarget"in window&&"fromElement"in CropTarget&&isFunction(e.cropTo))try{if(!((null==(i=e.getCaptureHandle())?void 0:i.handle)===currentTabID))return;const r=await CropTarget.fromElement(t);await e.cropTo(r)}catch(e){logger_manager_default.warn(`cropTo target failed ${e}`)}}function buildConstraints2(e){const t={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return isUndefined(e.microphoneId)||(t.deviceId=e.microphoneId),{audio:t,video:!1}}function buildScreenConstraints(e){const t={preferCurrentTab:"current-tab"===e.preferDisplaySurface||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},i={width:IS_SAFARI?{max:e.width}:{ideal:e.width,max:e.width},height:IS_SAFARI?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(t.video=i,e.systemAudio){const{echoCancellation:i=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=e;t.audio={echoCancellation:i,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return t}var get_display_media_default=getDisplayMedia,LocalScreenTrack2=class extends LocalVideoTrack{constructor(e){super(e,2),__publicField(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),__publicField(this,"objectFit","contain"),__publicField(this,"isScreen",!0),this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return currentTabID===(null==(t=null==(e=this.mediaTrack)?void 0:e.getCaptureHandle())?void 0:t.handle)}catch(e){return}}async capture({systemAudio:e=!1,autoGainControl:t,echoCancellation:i,noiseSuppression:r,audioTrack:s,videoTrack:n,captureElement:a,preferDisplaySurface:o}){try{let d;n||s?(d=new MediaStream,n&&d.addTrack(n),s&&d.addTrack(s)):d=await get_display_media_default({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:i,noiseSuppression:r,captureElement:a,preferDisplaySurface:o});const l=d.getVideoTracks()[0];return this.sourceTrack=l,await this.setInputMediaStreamTrack(l),d}catch(e){throw this.log.error(`getDisplayMedia error observed ${e}`),e instanceof rtc_error_default?e:new rtc_error_default({code:error_code_default.INITIALIZE_FAILED,name:e.name,message:e.message})}}async switchDevice(e){throw new Error("Method not implemented.")}};function checkPendingPromise(e=30,t=2){return createDecorator(((i,r)=>function(...s){return new Promise(((n,a)=>{const o=setTimeout((()=>{const i=new rtc_error_default({code:error_code_default.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${e}s`});logger_manager_default.warn(i),2===t?a(i):1===t&&n()}),1e3*e);i.apply(this,s).then(n,a).finally((()=>{clearTimeout(o)}))}))}))}__decorateClass([after((function(e){this.setContentHint(e.contentHint||"detail")}))],LocalScreenTrack2.prototype,"capture",1);var _RemoteTrack=class e extends Track{constructor(t,i,r){super({userId:i.userId,sdkAppId:t.sdkAppId,mediaType:r,room:t}),this.room=t,this.user=i,__publicField(this,"tinyId"),__publicField(this,"isRemote",!0),__publicField(this,"jitterBufferDelay",0),__publicField(this,"availableState"),__publicField(this,"remotePublishState"),__publicField(this,"_triggerCheckDecodeSubject",subject(fromEvent(this,e.STATE_SUBSCRIBE))),this.tinyId=i.tinyId,this.availableState=new FSM(`${i.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new FSM(`${i.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),pipe(merge(fromEvent(this,FSM.STATECHANGED),fromEvent(this.remotePublishState,FSM.STATECHANGED)),map((()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing))),subscribe((e=>{this.availableState.state!==(e?FSM.ON:FSM.OFF)&&(this.availableState.state=e?FSM.ON:FSM.OFF),this.updatePlayingState(e)})));const s=pipe(fromEvent(this.player,PlayerEvent.ERROR),filter((e=>e.code===MediaError.MEDIA_ERR_DECODE))),n=pipe(timer(5e3),filter((()=>{if(this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived)return!1;return!(this.player.isPlaying||(this.kind===NAME.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0))||(this.reportDecodeResult(!0),!1)}))),a=pipe(race(s,n),takeUntil(fromEvent(this,FSM.INIT)));pipe(this._triggerCheckDecodeSubject,filter((()=>!this.ignoreDecodeError)),switchMapTo(a),subscribe((e=>{this.reportDecodeResult(!1,e)})))}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 e,t;return((null==(t=null==(e=this.room)?void 0:e.networkQuality)?void 0:t.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return"subscribeing"===this.state.toString()}get isSubscribed(){return this.state===e.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===FSM.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),"main"===this.streamType&&"video"===this.kind&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){const i=this.kind===NAME.AUDIO;kv_stat_manager_default[e?"addSuccessEvent":"addFailedEvent"]({key:i?504700:514702}),e||(kv_stat_manager_default.addEnum({key:i?504701:514703,value:getOSNumber()}),event_log_default.uploadEvent({log:`stat-decode-failed-${this.kind}-${getDeviceModel()||getOSString()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===NAME.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))return void this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?FSM.ON:FSM.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};__publicField(_RemoteTrack,"STATE_SUBSCRIBE","subscribe"),__decorateClass([checkPendingPromise(5,1)],_RemoteTrack.prototype,"waitHasMediaTrack",1),__decorateClass([ChangeState(FSM.INIT,_RemoteTrack.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),inner_emitter_default.emit(inner_event_default.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),reportSuccessRate(521716,!1)],_RemoteTrack.prototype,"subscribe",1),__decorateClass([ChangeState(_RemoteTrack.STATE_SUBSCRIBE,FSM.INIT,{sync:!0,success(){this.log.info("unsubscribed"),inner_emitter_default.emit(inner_event_default.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],_RemoteTrack.prototype,"unsubscribe",1);var RemoteTrack=_RemoteTrack,eventHub=new Map;function addMonitorEvent(e,t){const i=__spreadProps(__spreadValues({},t),{timestamp:getCurrentTime()});eventHub.has(e)?eventHub.get(e).push(i):eventHub.set(e,[i])}inner_emitter_default.on(inner_event_default.JOIN_SUCCESS,(({room:e})=>{addMonitorEvent(e.userId,{eventId:32788})})),inner_emitter_default.on(inner_event_default.LEAVE_START,(({room:e})=>{addMonitorEvent(e.userId,{eventId:32789})})),inner_emitter_default.on(inner_event_default.LOCAL_TRACK_PUBLISHED,(({track:e})=>{if(e.room){let t=32769;4===e.mediaType?t=32768:2===e.mediaType&&(t=32805),addMonitorEvent(e.room.userId,{eventId:t})}})),inner_emitter_default.on(inner_event_default.LOCAL_TRACK_UNPUBLISHED,(({track:e})=>{if(e.room){let t=32771;4===e.mediaType?t=32770:2===e.mediaType&&(t=32806),addMonitorEvent(e.room.userId,{eventId:t})}})),inner_emitter_default.on(inner_event_default.TRACK_MUTED,(({track:e})=>{e.room&&(e.kind===NAME.AUDIO?addMonitorEvent(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):addMonitorEvent(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))})),inner_emitter_default.on(inner_event_default.TRACK_UNMUTED,(({track:e})=>{e.room&&(e.kind===NAME.AUDIO?addMonitorEvent(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):addMonitorEvent(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))})),inner_emitter_default.on(inner_event_default.REMOTE_TRACK_SUBSCRIBED,(({track:e})=>{e.room&&(1===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32777,remoteUserId:e.userId}),4===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32776,remoteUserId:e.userId}),8===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32803,remoteUserId:e.userId}))})),inner_emitter_default.on(inner_event_default.REMOTE_TRACK_UNSUBSCRIBED,(({track:e})=>{e.room&&(1===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32779,remoteUserId:e.userId}),4===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32778,remoteUserId:e.userId}),8===e.mediaType&&addMonitorEvent(e.room.userId,{eventId:32804,remoteUserId:e.userId}))})),inner_emitter_default.on(inner_event_default.SWITCH_DEVICE_SUCCESS,(({track:e})=>{e.room&&addMonitorEvent(e.room.userId,{eventId:e.kind===NAME.VIDEO?32780:32781})})),inner_emitter_default.on(inner_event_default.LOCAL_TRACK_REPLACED,(({track:e})=>{e.room&&addMonitorEvent(e.room.userId,{eventId:e.kind===NAME.VIDEO?32782:32783})})),inner_emitter_default.on(inner_event_default.SIGNAL_CONNECTION_STATE_CHANGED,(({room:e,prevState:t,state:i})=>{let r;switch(i){case"CONNECTED":r="RECONNECTING"===t?32795:32791;break;case"DISCONNECTED":r="RECONNECTING"===t?32796:32790;break;case"RECONNECTING":r=32794}r&&addMonitorEvent(e.userId,{eventId:r})})),inner_emitter_default.on(inner_event_default.PEER_CONNECTION_STATE_CHANGED,(({room:e,prevState:t,state:i,remoteUserId:r})=>{const s=!!r;let n;switch(i){case"CONNECTED":n="RECONNECTING"===t?s?32801:32798:s?32793:32792;break;case"DISCONNECTED":"RECONNECTING"===t&&(n=s?32802:32799);break;case"RECONNECTING":n=s?32800:32797}n&&addMonitorEvent(e.userId,{eventId:n,remoteUserId:r})})),inner_emitter_default.on(inner_event_default.VIDEO_CODEC_IMPLEMENTATION_CHANGED,(({implementation:e,userId:t,remoteUserId:i,codec:r,isHWCodec:s,prevImplementation:n,streamType:a})=>{let o=s?1:0;n||(o=s?3:2);const d="h264"===r?0:2,l={eventId:4004,param1:o,param2:d,streamType:a||2};i&&(l.remoteUserId=i,l.eventId=4005),addMonitorEvent(t,l),kv_stat_manager_default.addEnum({key:i?514701:513701,value:o}),kv_stat_manager_default.addEnum({key:i?514700:513700,value:d})})),inner_emitter_default.on(inner_event_default.LOCAL_TRACK_RECAPTURE,(({track:e,error:t})=>{if(e.userId){const i={eventId:2003,param1:0};e.kind===NAME.AUDIO?(i.streamType=1,t&&(i.param1=2)):(i.streamType="auxiliary"===e.streamType?7:2,t&&(i.param1=8)),addMonitorEvent(e.userId,i)}}));var import_eventemitter34=__toESM(require_eventemitter3(),1),videoMixSeq=0,_VideoMixer=class e{constructor(e){this.core=e,__publicField(this,"seq"),__publicField(this,"log"),__publicField(this,"localMixVideoTrack",null),__publicField(this,"_mixVideoConfig"),videoMixSeq+=1,this.seq=videoMixSeq,this.log=e.log.createChild({id:`${this.getAlias()}${videoMixSeq}`}),this.log.info("created")}getName(){return e.Name}getAlias(){return"vmix"}getValidateRule(e){switch(e){case"start":return startValidateRule(this.core);case"update":return updateValidateRule(this.core);case"stop":return stopValidateRule(this.core)}}getGroup(){return"vmix"}async start(e){this.localMixVideoTrack||(this.localMixVideoTrack=new this.core.LocalMixVideoTrack),this._mixVideoConfig={canvasInfo:{width:1920,height:1080}},await this.parseMixOptions(e);const{view:t}=e;return this._updatePreview({view:t,track:this.localMixVideoTrack}),await this.localMixVideoTrack.startMix(),this.localMixVideoTrack._outputTrack}async update(e){if(!this.localMixVideoTrack)throw new Error("can't update without mixTrack!");await this.parseMixOptions(e);const{view:t}=e;return await this._updatePreview({view:t,track:this.localMixVideoTrack,prevConfig:this._mixVideoConfig}),this.localMixVideoTrack._outputTrack}async parseMixOptions(e){if(!this.localMixVideoTrack)return;const{canvasInfo:t,camera:i,screen:r,text:s,image:n,video:a}=e;if(t){const{canvasColor:e,width:i,height:r,frameRate:s}=t;e&&this.localMixVideoTrack.setMixBackground(e),s&&this.localMixVideoTrack.setFps(s),this.localMixVideoTrack.resizeMixCanvas(i,r),this._mixVideoConfig.canvasInfo=t}i&&(this._mixVideoConfig.camera=await this.parseCameraOptions(this.localMixVideoTrack,i,this._mixVideoConfig.camera)),r&&(this._mixVideoConfig.screen=await this.parseScreenOptions(this.localMixVideoTrack,r,this._mixVideoConfig.screen)),s&&(this._mixVideoConfig.text=await this.parseTextOptions(this.localMixVideoTrack,s,this._mixVideoConfig.text)),n&&(this._mixVideoConfig.image=await this.parseImageOptions(this.localMixVideoTrack,n,this._mixVideoConfig.image)),a&&(this._mixVideoConfig.video=await this.parseVideoOptions(this.localMixVideoTrack,a,this._mixVideoConfig.video))}async parseCameraOptions(e,t,i=[]){var r,s;const n=new Set(t.map((e=>e.id))),a=i.filter((e=>!n.has(e.id))).map((e=>e.id));for(const t of a)e.removeCameraSource(t);const o=[];for(const n of t){const{id:t,layout:a,profile:d}=n;try{if(i.some((e=>e.id===t))){const i=null==(r=e.inputLocalVideoTracks.get(t))?void 0:r.mediaTrack;await this.updateCameraProfile(n);const o=null==(s=e.inputLocalVideoTracks.get(t))?void 0:s.mediaTrack;let l;d&&(l=isString(d)?videoProfileMap[d]:d),o!==i?e.updateCameraSource(t,a,o,l):e.updateCameraSource(t,a,null,l)}else{const i=await this.captureCamera(n);e.addCameraSource(t,i,a)}o.push(n)}catch(e){this.log.error(`${t} mix failed.`,e)}}return o}async parseScreenOptions(e,t,i=[]){const r=new Set(t.map((e=>e.id))),s=i.filter((e=>!r.has(e.id))).map((e=>e.id));for(const t of s)e.removeScreenSource(t);const n=[];for(const r of t){const{id:t,layout:s}=r;try{if(i.some((e=>e.id===t)))e.updateScreenSource(t,s);else{const i=await this.captureScreen(r);e.addScreenSource(t,i,s)}n.push(r)}catch(e){this.log.error(`${t} mix failed.`,e)}}return n}async parseTextOptions(e,t,i=[]){const r=new Set(t.map((e=>e.id))),s=i.filter((e=>!r.has(e.id))).map((e=>e.id));for(const t of s)e.removeTextSource(t);const n=[];for(const r of t){const{id:t}=r;try{i.some((e=>e.id===t))?e.updateTextSource(r):e.addTextSource(r),n.push(r)}catch(e){this.log.error(`${t} mix failed.`,e)}}return n}async parseImageOptions(e,t,i=[]){const r=new Set(t.map((e=>e.id))),s=i.filter((e=>!r.has(e.id))).map((e=>e.id));for(const t of s)e.removeImageSource(t);const n=[];for(const r of t){const{id:t,url:s,layout:a}=r;try{const o=i.find((e=>e.id===t));if(o){let i;o.url!==s&&(i=await loadImage(s)),e.updateImageSource(t,a,i)}else{const i=await loadImage(s);e.addImageSource(t,i,a)}n.push(r)}catch(e){this.log.error(`${t} mix failed.`,e)}}return n}async parseVideoOptions(e,t,i=[]){const r=new Set(t.map((e=>e.id))),s=i.filter((e=>!r.has(e.id))).map((e=>e.id));for(const t of s)e.removeVideoSource(t);const n=[];for(const r of t){const{id:t,url:s,layout:a}=r;try{const o=i.find((e=>e.id===t));let d;if(o)o.url!==s&&(d=await loadVideo(s)),e.updateVideoSource(t,a,d);else{const i=await loadVideo(s);e.addVideoSource(t,i,a)}n.push(r)}catch(e){this.log.error(`${t} mix failed.`,e)}}return n}async captureCamera(e){const{id:t,cameraId:i,videoTrack:r,profile:s}=e,n=new this.core.LocalVideoTrack;n.log.id+=`-${t}`;const a={};return i?a.deviceId=i:isUndefined(r)||(a.customSource=r),isUndefined(s)||(isString(s)?videoProfileMap[s]&&n.setProfile(videoProfileMap[s]):n.setProfile(s)),await n.capture(a),n}async updateCameraProfile(e){var t;const{id:i,cameraId:r,videoTrack:s,profile:n}=e,a=null==(t=this.localMixVideoTrack)?void 0:t.inputLocalVideoTracks.get(i);a&&(r?await a.switchDevice(r):isUndefined(s)||await a.setInputMediaStreamTrack(s),isUndefined(n)||(isString(n)?videoProfileMap[n]&&a.setProfile(videoProfileMap[n]):a.setProfile(n),r&&a.isNeedToSwitchDevice(r)||await a.applyProfile()))}async captureScreen(e){const{id:t,profile:i,captureElement:r,preferDisplaySurface:s}=e,n=new this.core.LocalScreenTrack;n.log.id+=`-${t}`;const a={};return isUndefined(i)||(isString(i)?screenProfileMap[i]&&n.setProfile(screenProfileMap[i]):n.setProfile(i)),r&&(a.captureElement=r),s&&(a.preferDisplaySurface=s),await n.capture(a),n.mediaTrack.addEventListener(NAME.ENDED,(()=>{var e,i;null==(e=this.localMixVideoTrack)||e.removeScreenSource(t),(null==(i=this._mixVideoConfig)?void 0:i.screen)&&(this._mixVideoConfig.screen=this._mixVideoConfig.screen.filter((e=>e.id!==t)))})),n}async _updatePreview({view:e,track:t,prevConfig:i}){if(isUndefined(e)&&i&&i.view){const e=getViewListFromView(i.view);e.length>0&&await t.play(e)}if(!isUndefined(e)){const i=getViewListFromView(e);i.length>0?await t.play(i):t.stop()}}stop(){var e;null==(e=this.localMixVideoTrack)||e.close(),this.localMixVideoTrack=null,delete this._mixVideoConfig}};__publicField(_VideoMixer,"Name","VideoMixer"),__decorateClass([catchError((function(e){this.log.error("parseMixOptions failed.",e)}))],_VideoMixer.prototype,"parseMixOptions",1),__decorateClass([catchError((function(e){this.log.error("parse camera options failed.",e)}))],_VideoMixer.prototype,"parseCameraOptions",1),__decorateClass([catchError((function(e){this.log.error("parse screen options failed.",e)}))],_VideoMixer.prototype,"parseScreenOptions",1),__decorateClass([catchError((function(e){this.log.error("parse text options failed.",e)}))],_VideoMixer.prototype,"parseTextOptions",1),__decorateClass([catchError((function(e){this.log.error("parse image options failed.",e)}))],_VideoMixer.prototype,"parseImageOptions",1),__decorateClass([catchError((function(e){this.log.error("parse video options failed.",e)}))],_VideoMixer.prototype,"parseVideoOptions",1);var VideoMixer=_VideoMixer,index_default=VideoMixer;export{index_default as default};export{VideoMixer};
|