trtc-sdk-v5 5.0.0-beta

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/trtc.esm.js ADDED
@@ -0,0 +1,100 @@
1
+ var Kl=Object.create;var sr=Object.defineProperty,jl=Object.defineProperties,bc=Object.getOwnPropertyDescriptor,Jl=Object.getOwnPropertyDescriptors,Yl=Object.getOwnPropertyNames,fn=Object.getOwnPropertySymbols,Pc=Object.getPrototypeOf,Ks=Object.prototype.hasOwnProperty,Mc=Object.prototype.propertyIsEnumerable,Xl=Reflect.get;var En=Math.pow,Ws=(i,t,e)=>t in i?sr(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,w=(i,t)=>{for(var e in t||(t={}))Ks.call(t,e)&&Ws(i,e,t[e]);if(fn)for(var e of fn(t))Mc.call(t,e)&&Ws(i,e,t[e]);return i},ie=(i,t)=>jl(i,Jl(t));var Lc=(i,t)=>{var e={};for(var r in i)Ks.call(i,r)&&t.indexOf(r)<0&&(e[r]=i[r]);if(i!=null&&fn)for(var r of fn(i))t.indexOf(r)<0&&Mc.call(i,r)&&(e[r]=i[r]);return e};var me=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),js=(i,t)=>{for(var e in t)sr(i,e,{get:t[e],enumerable:!0})},ql=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Yl(t))!Ks.call(i,n)&&n!==e&&sr(i,n,{get:()=>t[n],enumerable:!(r=bc(t,n))||r.enumerable});return i};var h=(i,t,e)=>(e=i!=null?Kl(Pc(i)):{},ql(t||!i||!i.__esModule?sr(e,"default",{value:i,enumerable:!0}):e,i));var G=(i,t,e,r)=>{for(var n=r>1?void 0:r?bc(t,e):t,s=i.length-1,o;s>=0;s--)(o=i[s])&&(n=(r?o(t,e,n):o(n))||n);return r&&n&&sr(t,e,n),n};var p=(i,t,e)=>(Ws(i,typeof t!="symbol"?t+"":t,e),e);var oi=(i,t,e)=>Xl(Pc(i),e,t);var T=(i,t,e)=>new Promise((r,n)=>{var s=c=>{try{a(e.next(c))}catch(d){n(d)}},o=c=>{try{a(e.throw(c))}catch(d){n(d)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,o);a((e=e.apply(i,t)).next())});var ut=me(Ye=>{"use strict";var P_=h(_());Object.defineProperty(Ye,"__esModule",{value:!0});var Js=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};Ye.extractVersion=or;Ye.wrapPeerConnectionEvent=Ql;Ye.disableLog=Zl;Ye.disableWarnings=ep;Ye.log=tp;Ye.deprecated=ip;Ye.detectBrowser=rp;Ye.compactObject=Vc;Ye.walkStats=Tn;Ye.filterStats=np;function zl(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}var xc=!0,Uc=!0;function or(i,t,e){var r=i.match(t);return r&&r.length>=e&&parseInt(r[e],10)}function Ql(i,t,e){if(!!i.RTCPeerConnection){var r=i.RTCPeerConnection.prototype,n=r.addEventListener;r.addEventListener=function(o,a){if(o!==t)return n.apply(this,arguments);var c=function(u){var l=e(u);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),n.apply(this,[o,c])};var s=r.removeEventListener;r.removeEventListener=function(o,a){if(o!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(a))return s.apply(this,arguments);var c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(r,"on"+t,{get:function(){return this["_on"+t]},set:function(a){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),a&&this.addEventListener(t,this["_on"+t]=a)},enumerable:!0,configurable:!0})}}function Zl(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":Js(i))+". Please use a boolean."):(xc=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function ep(i){return typeof i!="boolean"?new Error("Argument type: "+(typeof i=="undefined"?"undefined":Js(i))+". Please use a boolean."):(Uc=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function tp(){if((typeof window=="undefined"?"undefined":Js(window))==="object"){if(xc)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function ip(i,t){!Uc||console.warn(i+" is deprecated, please use "+t+" instead.")}function rp(i){var t={browser:null,version:null};if(typeof i=="undefined"||!i.navigator)return t.browser="Not a browser.",t;var e=i.navigator;if(e.mozGetUserMedia)t.browser="firefox",t.version=or(e.userAgent,/Firefox\/(\d+)\./,1);else if(e.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection&&!i.RTCIceGatherer)t.browser="chrome",t.version=or(e.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(e.mediaDevices&&e.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=or(e.userAgent,/Edge\/(\d+).(\d+)$/,2);else if(i.RTCPeerConnection&&e.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser="safari",t.version=or(e.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype;else return t.browser="Not a supported browser.",t;return t}function kc(i){return Object.prototype.toString.call(i)==="[object Object]"}function Vc(i){return kc(i)?Object.keys(i).reduce(function(t,e){var r=kc(i[e]),n=r?Vc(i[e]):i[e],s=r&&!Object.keys(n).length;return n===void 0||s?t:Object.assign(t,zl({},e,n))},{}):i}function Tn(i,t,e){!t||e.has(t.id)||(e.set(t.id,t),Object.keys(t).forEach(function(r){r.endsWith("Id")?Tn(i,i.get(t[r]),e):r.endsWith("Ids")&&t[r].forEach(function(n){Tn(i,i.get(n),e)})}))}function np(i,t,e){var r=e?"outbound-rtp":"inbound-rtp",n=new Map;if(t===null)return n;var s=[];return i.forEach(function(o){o.type==="track"&&o.trackIdentifier===t.id&&s.push(o)}),s.forEach(function(o){i.forEach(function(a){a.type===r&&a.trackId===o.id&&Tn(i,a,n)})}),n}});var Bc=me(Ys=>{"use strict";var L_=h(_());Object.defineProperty(Ys,"__esModule",{value:!0});var ar=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};Ys.shimGetUserMedia=cp;var sp=ut(),op=ap(sp);function ap(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}var wc=op.log;function cp(i,t){var e=i&&i.navigator;if(!!e.mediaDevices){var r=function(d){if((typeof d=="undefined"?"undefined":ar(d))!=="object"||d.mandatory||d.optional)return d;var u={};return Object.keys(d).forEach(function(l){if(!(l==="require"||l==="advanced"||l==="mediaSource")){var m=ar(d[l])==="object"?d[l]:{ideal:d[l]};m.exact!==void 0&&typeof m.exact=="number"&&(m.min=m.max=m.exact);var S=function(B,x){return B?B+x.charAt(0).toUpperCase()+x.slice(1):x==="deviceId"?"sourceId":x};if(m.ideal!==void 0){u.optional=u.optional||[];var E={};typeof m.ideal=="number"?(E[S("min",l)]=m.ideal,u.optional.push(E),E={},E[S("max",l)]=m.ideal,u.optional.push(E)):(E[S("",l)]=m.ideal,u.optional.push(E))}m.exact!==void 0&&typeof m.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[S("",l)]=m.exact):["min","max"].forEach(function(y){m[y]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[S(y,l)]=m[y])})}}),d.advanced&&(u.optional=(u.optional||[]).concat(d.advanced)),u},n=function(d,u){if(t.version>=61)return u(d);if(d=JSON.parse(JSON.stringify(d)),d&&ar(d.audio)==="object"){var l=function(B,x,F){x in B&&!(F in B)&&(B[F]=B[x],delete B[x])};d=JSON.parse(JSON.stringify(d)),l(d.audio,"autoGainControl","googAutoGainControl"),l(d.audio,"noiseSuppression","googNoiseSuppression"),d.audio=r(d.audio)}if(d&&ar(d.video)==="object"){var m=d.video.facingMode;m=m&&((typeof m=="undefined"?"undefined":ar(m))==="object"?m:{ideal:m});var S=t.version<66;if(m&&(m.exact==="user"||m.exact==="environment"||m.ideal==="user"||m.ideal==="environment")&&!(e.mediaDevices.getSupportedConstraints&&e.mediaDevices.getSupportedConstraints().facingMode&&!S)){delete d.video.facingMode;var E=void 0;if(m.exact==="environment"||m.ideal==="environment"?E=["back","rear"]:(m.exact==="user"||m.ideal==="user")&&(E=["front"]),E)return e.mediaDevices.enumerateDevices().then(function(y){y=y.filter(function(x){return x.kind==="videoinput"});var B=y.find(function(x){return E.some(function(F){return x.label.toLowerCase().includes(F)})});return!B&&y.length&&E.includes("back")&&(B=y[y.length-1]),B&&(d.video.deviceId=m.exact?{exact:B.deviceId}:{ideal:B.deviceId}),d.video=r(d.video),wc("chrome: "+JSON.stringify(d)),u(d)})}d.video=r(d.video)}return wc("chrome: "+JSON.stringify(d)),u(d)},s=function(d){return t.version>=64?d:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[d.name]||d.name,message:d.message,constraint:d.constraint||d.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}},o=function(d,u,l){n(d,function(m){e.webkitGetUserMedia(m,u,function(S){l&&l(s(S))})})};if(e.getUserMedia=o.bind(e),e.mediaDevices.getUserMedia){var a=e.mediaDevices.getUserMedia.bind(e.mediaDevices);e.mediaDevices.getUserMedia=function(c){return n(c,function(d){return a(d).then(function(u){if(d.audio&&!u.getAudioTracks().length||d.video&&!u.getVideoTracks().length)throw u.getTracks().forEach(function(l){l.stop()}),new DOMException("","NotFoundError");return u},function(u){return Promise.reject(s(u))})})}}}}});var $c=me(Xs=>{"use strict";var x_=h(_());Object.defineProperty(Xs,"__esModule",{value:!0});Xs.shimGetDisplayMedia=dp;function dp(i,t){if(!(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices)&&!!i.navigator.mediaDevices){if(typeof t!="function"){console.error("shimGetDisplayMedia: getSourceId argument is not a function");return}i.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then(function(n){var s=r.video&&r.video.width,o=r.video&&r.video.height,a=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:a||3}},s&&(r.video.mandatory.maxWidth=s),o&&(r.video.mandatory.maxHeight=o),i.navigator.mediaDevices.getUserMedia(r)})}}}});var Gc=me(Pe=>{"use strict";var V_=h(_());Object.defineProperty(Pe,"__esModule",{value:!0});Pe.shimGetDisplayMedia=Pe.shimGetUserMedia=void 0;var Sn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},up=Bc();Object.defineProperty(Pe,"shimGetUserMedia",{enumerable:!0,get:function(){return up.shimGetUserMedia}});var lp=$c();Object.defineProperty(Pe,"shimGetDisplayMedia",{enumerable:!0,get:function(){return lp.shimGetDisplayMedia}});Pe.shimMediaStream=hp;Pe.shimOnTrack=_p;Pe.shimGetSendersWithDtmf=fp;Pe.shimGetStats=Ep;Pe.shimSenderReceiverGetStats=Tp;Pe.shimAddTrackRemoveTrackWithNative=Fc;Pe.shimAddTrackRemoveTrack=Sp;Pe.shimPeerConnection=Ip;Pe.fixNegotiationNeeded=gp;var pp=ut(),cr=mp(pp);function mp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Hc(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function hp(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function _p(i){if((typeof i=="undefined"?"undefined":Sn(i))==="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(r){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=r)},enumerable:!0,configurable:!0});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._ontrackpoly||(this._ontrackpoly=function(n){n.stream.addEventListener("addtrack",function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.track.id}):o={track:s.track};var a=new Event("track");a.track=s.track,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)}),n.stream.getTracks().forEach(function(s){var o=void 0;i.RTCPeerConnection.prototype.getReceivers?o=r.getReceivers().find(function(c){return c.track&&c.track.id===s.id}):o={track:s};var a=new Event("track");a.track=s,a.receiver=o,a.transceiver={receiver:o},a.streams=[n.stream],r.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else cr.wrapPeerConnectionEvent(i,"track",function(e){return e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e})}function fp(i){if((typeof i=="undefined"?"undefined":Sn(i))==="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){var t=function(c,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=c.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:c}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(c,d){var u=e.apply(this,arguments);return u||(u=t(this,c),this._senders.push(u)),u};var r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(c){r.apply(this,arguments);var d=this._senders.indexOf(c);d!==-1&&this._senders.splice(d,1)}}var n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(c){var d=this;this._senders=this._senders||[],n.apply(this,[c]),c.getTracks().forEach(function(u){d._senders.push(t(d,u))})};var s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(c){var d=this;this._senders=this._senders||[],s.apply(this,[c]),c.getTracks().forEach(function(u){var l=d._senders.find(function(m){return m.track===u});l&&d._senders.splice(d._senders.indexOf(l),1)})}}else if((typeof i=="undefined"?"undefined":Sn(i))==="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){var o=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){var c=this,d=o.apply(this,[]);return d.forEach(function(u){return u._pc=c}),d},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ep(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var r=this,n=Array.prototype.slice.call(arguments),s=n[0],o=n[1],a=n[2];if(arguments.length>0&&typeof s=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof s!="function"))return t.apply(this,[]);var c=function(m){var S={},E=m.result();return E.forEach(function(y){var B={id:y.id,timestamp:y.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[y.type]||y.type};y.names().forEach(function(x){B[x]=y.stat(x)}),S[B.id]=B}),S},d=function(m){return new Map(Object.keys(m).map(function(S){return[S,m[S]]}))};if(arguments.length>=2){var u=function(m){o(d(c(m)))};return t.apply(this,[u,s])}return new Promise(function(l,m){t.apply(r,[function(S){l(d(c(S)))},m])}).then(o,a)}}}function Tp(i){if(!!((typeof i=="undefined"?"undefined":Sn(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver)){if(!("getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var o=this,a=t.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var o=e.apply(this,arguments);return o._pc=this,o}),i.RTCRtpSender.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return cr.filterStats(a,o.track,!0)})}}if(!("getStats"in i.RTCRtpReceiver.prototype)){var r=i.RTCPeerConnection.prototype.getReceivers;r&&(i.RTCPeerConnection.prototype.getReceivers=function(){var o=this,a=r.apply(this,[]);return a.forEach(function(c){return c._pc=o}),a}),cr.wrapPeerConnectionEvent(i,"track",function(s){return s.receiver._pc=s.srcElement,s}),i.RTCRtpReceiver.prototype.getStats=function(){var o=this;return this._pc.getStats().then(function(a){return cr.filterStats(a,o.track,!1)})}}if("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype){var n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){var o=arguments[0],a=void 0,c=void 0,d=void 0;return this.getSenders().forEach(function(u){u.track===o&&(a?d=!0:a=u)}),this.getReceivers().forEach(function(u){return u.track===o&&(c?d=!0:c=u),u.track===o}),d||a&&c?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():c?c.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return n.apply(this,arguments)}}}}function Fc(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){var o=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(a){return o._shimmedLocalStreams[a][0]})};var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var c=t.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};var e=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(o){var a=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(function(u){var l=a.getSenders().find(function(m){return m.track===u});if(l)throw new DOMException("Track already exists.","InvalidAccessError")});var c=this.getSenders();e.apply(this,arguments);var d=this.getSenders().filter(function(u){return c.indexOf(u)===-1});this._shimmedLocalStreams[o.id]=[o].concat(d)};var r=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],r.apply(this,arguments)};var n=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){var a=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(function(c){var d=a._shimmedLocalStreams[c].indexOf(o);d!==-1&&a._shimmedLocalStreams[c].splice(d,1),a._shimmedLocalStreams[c].length===1&&delete a._shimmedLocalStreams[c]}),n.apply(this,arguments)}}function Sp(i,t){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Fc(i);var e=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){var u=this,l=e.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(function(m){return u._reverseStreams[m.id]})};var r=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(u){var l=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},u.getTracks().forEach(function(S){var E=l.getSenders().find(function(y){return y.track===S});if(E)throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[u.id]){var m=new i.MediaStream(u.getTracks());this._streams[u.id]=m,this._reverseStreams[m.id]=u,u=m}r.apply(this,[u])};var n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(u){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[u.id]||u]),delete this._reverseStreams[this._streams[u.id]?this._streams[u.id].id:u.id],delete this._streams[u.id]},i.RTCPeerConnection.prototype.addTrack=function(u,l){var m=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var S=[].slice.call(arguments,1);if(S.length!==1||!S[0].getTracks().find(function(x){return x===u}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");var E=this.getSenders().find(function(x){return x.track===u});if(E)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var y=this._streams[l.id];if(y)y.addTrack(u),Promise.resolve().then(function(){m.dispatchEvent(new Event("negotiationneeded"))});else{var B=new i.MediaStream([u]);this._streams[l.id]=B,this._reverseStreams[B.id]=l,this.addStream(B)}return this.getSenders().find(function(x){return x.track===u})};function s(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(m){var S=d._reverseStreams[m],E=d._streams[S.id];l=l.replace(new RegExp(E.id,"g"),S.id)}),new RTCSessionDescription({type:u.type,sdp:l})}function o(d,u){var l=u.sdp;return Object.keys(d._reverseStreams||[]).forEach(function(m){var S=d._reverseStreams[m],E=d._streams[S.id];l=l.replace(new RegExp(S.id,"g"),E.id)}),new RTCSessionDescription({type:u.type,sdp:l})}["createOffer","createAnswer"].forEach(function(d){var u=i.RTCPeerConnection.prototype[d],l=Hc({},d,function(){var m=this,S=arguments,E=arguments.length&&typeof arguments[0]=="function";return E?u.apply(this,[function(y){var B=s(m,y);S[0].apply(null,[B])},function(y){S[1]&&S[1].apply(null,y)},arguments[2]]):u.apply(this,arguments).then(function(y){return s(m,y)})});i.RTCPeerConnection.prototype[d]=l[d]});var a=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};var c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get:function(){var u=c.get.apply(this);return u.type===""?u:s(this,u)}}),i.RTCPeerConnection.prototype.removeTrack=function(u){var l=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!u._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");var m=u._pc===this;if(!m)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};var S=void 0;Object.keys(this._streams).forEach(function(E){var y=l._streams[E].getTracks().find(function(B){return u.track===B});y&&(S=l._streams[E])}),S&&(S.getTracks().length===1?this.removeStream(this._reverseStreams[S.id]):S.removeTrack(u.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Ip(i,t){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),!!i.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var r=i.RTCPeerConnection.prototype[e],n=Hc({},e,function(){return arguments[0]=new(e==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)});i.RTCPeerConnection.prototype[e]=n[e]})}function gp(i,t){cr.wrapPeerConnectionEvent(i,"negotiationneeded",function(e){var r=e.target;if(!((t.version<72||r.getConfiguration&&r.getConfiguration().sdpSemantics==="plan-b")&&r.signalingState!=="stable"))return e})}});var Wc=me(qs=>{"use strict";var B_=h(_());Object.defineProperty(qs,"__esModule",{value:!0});qs.shimGetUserMedia=Rp;function Rp(i){var t=i&&i.navigator,e=function(s){return{name:{PermissionDeniedError:"NotAllowedError"}[s.name]||s.name,message:s.message,constraint:s.constraint,toString:function(){return this.name}}},r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(n){return r(n).catch(function(s){return Promise.reject(e(s))})}}});var Kc=me(zs=>{"use strict";var H_=h(_());Object.defineProperty(zs,"__esModule",{value:!0});zs.shimGetDisplayMedia=Ap;function Ap(i){"getDisplayMedia"in i.navigator&&(!i.navigator.mediaDevices||i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}});var jc=me(Qs=>{"use strict";var G_=h(_());Object.defineProperty(Qs,"__esModule",{value:!0});Qs.filterIceServers=Np;var Cp=ut(),vp=yp(Cp);function yp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Np(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&vp.deprecated("RTCIceServer.url","RTCIceServer.urls");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){if(o.indexOf("stun:")===0)return!1;var a=o.startsWith("turn")&&!o.startsWith("turn:[")&&o.includes("transport=udp");return a&&!e?(e=!0,!0):a&&!e}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}});var eo=me((W_,Zs)=>{"use strict";var K_=h(_()),O={};O.generateIdentifier=function(){return Math.random().toString(36).substr(2,10)};O.localCName=O.generateIdentifier();O.splitLines=function(i){return i.trim().split(`
2
+ `).map(function(t){return t.trim()})};O.splitSections=function(i){var t=i.split(`
3
+ m=`);return t.map(function(e,r){return(r>0?"m="+e:e).trim()+`\r
4
+ `})};O.getDescription=function(i){var t=O.splitSections(i);return t&&t[0]};O.getMediaSections=function(i){var t=O.splitSections(i);return t.shift(),t};O.matchPrefix=function(i,t){return O.splitLines(i).filter(function(e){return e.indexOf(t)===0})};O.parseCandidate=function(i){var t;i.indexOf("a=candidate:")===0?t=i.substring(12).split(" "):t=i.substring(10).split(" ");for(var e={foundation:t[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},r=8;r<t.length;r+=2)switch(t[r]){case"raddr":e.relatedAddress=t[r+1];break;case"rport":e.relatedPort=parseInt(t[r+1],10);break;case"tcptype":e.tcpType=t[r+1];break;case"ufrag":e.ufrag=t[r+1],e.usernameFragment=t[r+1];break;default:e[t[r]]=t[r+1];break}return e};O.writeCandidate=function(i){var t=[];t.push(i.foundation),t.push(i.component),t.push(i.protocol.toUpperCase()),t.push(i.priority),t.push(i.address||i.ip),t.push(i.port);var e=i.type;return t.push("typ"),t.push(e),e!=="host"&&i.relatedAddress&&i.relatedPort&&(t.push("raddr"),t.push(i.relatedAddress),t.push("rport"),t.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(t.push("ufrag"),t.push(i.usernameFragment||i.ufrag)),"candidate:"+t.join(" ")};O.parseIceOptions=function(i){return i.substr(14).split(" ")};O.parseRtpMap=function(i){var t=i.substr(9).split(" "),e={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),e.name=t[0],e.clockRate=parseInt(t[1],10),e.channels=t.length===3?parseInt(t[2],10):1,e.numChannels=e.channels,e};O.writeRtpMap=function(i){var t=i.payloadType;i.preferredPayloadType!==void 0&&(t=i.preferredPayloadType);var e=i.channels||i.numChannels||1;return"a=rtpmap:"+t+" "+i.name+"/"+i.clockRate+(e!==1?"/"+e:"")+`\r
5
+ `};O.parseExtmap=function(i){var t=i.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}};O.writeExtmap=function(i){return"a=extmap:"+(i.id||i.preferredId)+(i.direction&&i.direction!=="sendrecv"?"/"+i.direction:"")+" "+i.uri+`\r
6
+ `};O.parseFmtp=function(i){for(var t={},e,r=i.substr(i.indexOf(" ")+1).split(";"),n=0;n<r.length;n++)e=r[n].trim().split("="),t[e[0].trim()]=e[1];return t};O.writeFmtp=function(i){var t="",e=i.payloadType;if(i.preferredPayloadType!==void 0&&(e=i.preferredPayloadType),i.parameters&&Object.keys(i.parameters).length){var r=[];Object.keys(i.parameters).forEach(function(n){i.parameters[n]?r.push(n+"="+i.parameters[n]):r.push(n)}),t+="a=fmtp:"+e+" "+r.join(";")+`\r
7
+ `}return t};O.parseRtcpFb=function(i){var t=i.substr(i.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}};O.writeRtcpFb=function(i){var t="",e=i.payloadType;return i.preferredPayloadType!==void 0&&(e=i.preferredPayloadType),i.rtcpFeedback&&i.rtcpFeedback.length&&i.rtcpFeedback.forEach(function(r){t+="a=rtcp-fb:"+e+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r
8
+ `}),t};O.parseSsrcMedia=function(i){var t=i.indexOf(" "),e={ssrc:parseInt(i.substr(7,t-7),10)},r=i.indexOf(":",t);return r>-1?(e.attribute=i.substr(t+1,r-t-1),e.value=i.substr(r+1)):e.attribute=i.substr(t+1),e};O.parseSsrcGroup=function(i){var t=i.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(function(e){return parseInt(e,10)})}};O.getMid=function(i){var t=O.matchPrefix(i,"a=mid:")[0];if(t)return t.substr(6)};O.parseFingerprint=function(i){var t=i.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}};O.getDtlsParameters=function(i,t){var e=O.matchPrefix(i+t,"a=fingerprint:");return{role:"auto",fingerprints:e.map(O.parseFingerprint)}};O.writeDtlsParameters=function(i,t){var e="a=setup:"+t+`\r
9
+ `;return i.fingerprints.forEach(function(r){e+="a=fingerprint:"+r.algorithm+" "+r.value+`\r
10
+ `}),e};O.parseCryptoLine=function(i){var t=i.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}};O.writeCryptoLine=function(i){return"a=crypto:"+i.tag+" "+i.cryptoSuite+" "+(typeof i.keyParams=="object"?O.writeCryptoKeyParams(i.keyParams):i.keyParams)+(i.sessionParams?" "+i.sessionParams.join(" "):"")+`\r
11
+ `};O.parseCryptoKeyParams=function(i){if(i.indexOf("inline:")!==0)return null;var t=i.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}};O.writeCryptoKeyParams=function(i){return i.keyMethod+":"+i.keySalt+(i.lifeTime?"|"+i.lifeTime:"")+(i.mkiValue&&i.mkiLength?"|"+i.mkiValue+":"+i.mkiLength:"")};O.getCryptoParameters=function(i,t){var e=O.matchPrefix(i+t,"a=crypto:");return e.map(O.parseCryptoLine)};O.getIceParameters=function(i,t){var e=O.matchPrefix(i+t,"a=ice-ufrag:")[0],r=O.matchPrefix(i+t,"a=ice-pwd:")[0];return e&&r?{usernameFragment:e.substr(12),password:r.substr(10)}:null};O.writeIceParameters=function(i){return"a=ice-ufrag:"+i.usernameFragment+`\r
12
+ a=ice-pwd:`+i.password+`\r
13
+ `};O.parseRtpParameters=function(i){for(var t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},e=O.splitLines(i),r=e[0].split(" "),n=3;n<r.length;n++){var s=r[n],o=O.matchPrefix(i,"a=rtpmap:"+s+" ")[0];if(o){var a=O.parseRtpMap(o),c=O.matchPrefix(i,"a=fmtp:"+s+" ");switch(a.parameters=c.length?O.parseFmtp(c[0]):{},a.rtcpFeedback=O.matchPrefix(i,"a=rtcp-fb:"+s+" ").map(O.parseRtcpFb),t.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(a.name.toUpperCase());break;default:break}}}return O.matchPrefix(i,"a=extmap:").forEach(function(d){t.headerExtensions.push(O.parseExtmap(d))}),t};O.writeRtpDescription=function(i,t){var e="";e+="m="+i+" ",e+=t.codecs.length>0?"9":"0",e+=" UDP/TLS/RTP/SAVPF ",e+=t.codecs.map(function(n){return n.preferredPayloadType!==void 0?n.preferredPayloadType:n.payloadType}).join(" ")+`\r
14
+ `,e+=`c=IN IP4 0.0.0.0\r
15
+ `,e+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
+ `,t.codecs.forEach(function(n){e+=O.writeRtpMap(n),e+=O.writeFmtp(n),e+=O.writeRtcpFb(n)});var r=0;return t.codecs.forEach(function(n){n.maxptime>r&&(r=n.maxptime)}),r>0&&(e+="a=maxptime:"+r+`\r
17
+ `),e+=`a=rtcp-mux\r
18
+ `,t.headerExtensions&&t.headerExtensions.forEach(function(n){e+=O.writeExtmap(n)}),e};O.parseRtpEncodingParameters=function(i){var t=[],e=O.parseRtpParameters(i),r=e.fecMechanisms.indexOf("RED")!==-1,n=e.fecMechanisms.indexOf("ULPFEC")!==-1,s=O.matchPrefix(i,"a=ssrc:").map(function(u){return O.parseSsrcMedia(u)}).filter(function(u){return u.attribute==="cname"}),o=s.length>0&&s[0].ssrc,a,c=O.matchPrefix(i,"a=ssrc-group:FID").map(function(u){var l=u.substr(17).split(" ");return l.map(function(m){return parseInt(m,10)})});c.length>0&&c[0].length>1&&c[0][0]===o&&(a=c[0][1]),e.codecs.forEach(function(u){if(u.name.toUpperCase()==="RTX"&&u.parameters.apt){var l={ssrc:o,codecPayloadType:parseInt(u.parameters.apt,10)};o&&a&&(l.rtx={ssrc:a}),t.push(l),r&&(l=JSON.parse(JSON.stringify(l)),l.fec={ssrc:o,mechanism:n?"red+ulpfec":"red"},t.push(l))}}),t.length===0&&o&&t.push({ssrc:o});var d=O.matchPrefix(i,"b=");return d.length&&(d[0].indexOf("b=TIAS:")===0?d=parseInt(d[0].substr(7),10):d[0].indexOf("b=AS:")===0?d=parseInt(d[0].substr(5),10)*1e3*.95-50*40*8:d=void 0,t.forEach(function(u){u.maxBitrate=d})),t};O.parseRtcpParameters=function(i){var t={},e=O.matchPrefix(i,"a=ssrc:").map(function(s){return O.parseSsrcMedia(s)}).filter(function(s){return s.attribute==="cname"})[0];e&&(t.cname=e.value,t.ssrc=e.ssrc);var r=O.matchPrefix(i,"a=rtcp-rsize");t.reducedSize=r.length>0,t.compound=r.length===0;var n=O.matchPrefix(i,"a=rtcp-mux");return t.mux=n.length>0,t};O.parseMsid=function(i){var t,e=O.matchPrefix(i,"a=msid:");if(e.length===1)return t=e[0].substr(7).split(" "),{stream:t[0],track:t[1]};var r=O.matchPrefix(i,"a=ssrc:").map(function(n){return O.parseSsrcMedia(n)}).filter(function(n){return n.attribute==="msid"});if(r.length>0)return t=r[0].value.split(" "),{stream:t[0],track:t[1]}};O.parseSctpDescription=function(i){var t=O.parseMLine(i),e=O.matchPrefix(i,"a=max-message-size:"),r;e.length>0&&(r=parseInt(e[0].substr(19),10)),isNaN(r)&&(r=65536);var n=O.matchPrefix(i,"a=sctp-port:");if(n.length>0)return{port:parseInt(n[0].substr(12),10),protocol:t.fmt,maxMessageSize:r};var s=O.matchPrefix(i,"a=sctpmap:");if(s.length>0){var o=O.matchPrefix(i,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:r}}};O.writeSctpDescription=function(i,t){var e=[];return i.protocol!=="DTLS/SCTP"?e=["m="+i.kind+" 9 "+i.protocol+" "+t.protocol+`\r
19
+ `,`c=IN IP4 0.0.0.0\r
20
+ `,"a=sctp-port:"+t.port+`\r
21
+ `]:e=["m="+i.kind+" 9 "+i.protocol+" "+t.port+`\r
22
+ `,`c=IN IP4 0.0.0.0\r
23
+ `,"a=sctpmap:"+t.port+" "+t.protocol+` 65535\r
24
+ `],t.maxMessageSize!==void 0&&e.push("a=max-message-size:"+t.maxMessageSize+`\r
25
+ `),e.join("")};O.generateSessionId=function(){return Math.random().toString().substr(2,21)};O.writeSessionBoilerplate=function(i,t,e){var r,n=t!==void 0?t:2;i?r=i:r=O.generateSessionId();var s=e||"thisisadapterortc";return`v=0\r
26
+ o=`+s+" "+r+" "+n+` IN IP4 127.0.0.1\r
27
+ s=-\r
28
+ t=0 0\r
29
+ `};O.writeMediaSection=function(i,t,e,r){var n=O.writeRtpDescription(i.kind,t);if(n+=O.writeIceParameters(i.iceGatherer.getLocalParameters()),n+=O.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),e==="offer"?"actpass":"active"),n+="a=mid:"+i.mid+`\r
30
+ `,i.direction?n+="a="+i.direction+`\r
31
+ `:i.rtpSender&&i.rtpReceiver?n+=`a=sendrecv\r
32
+ `:i.rtpSender?n+=`a=sendonly\r
33
+ `:i.rtpReceiver?n+=`a=recvonly\r
34
+ `:n+=`a=inactive\r
35
+ `,i.rtpSender){var s="msid:"+r.id+" "+i.rtpSender.track.id+`\r
36
+ `;n+="a="+s,n+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+s,i.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+s,n+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
37
+ `)}return n+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+O.localCName+`\r
38
+ `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(n+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+O.localCName+`\r
39
+ `),n};O.getDirection=function(i,t){for(var e=O.splitLines(i),r=0;r<e.length;r++)switch(e[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return e[r].substr(2);default:}return t?O.getDirection(t):"sendrecv"};O.getKind=function(i){var t=O.splitLines(i),e=t[0].split(" ");return e[0].substr(2)};O.isRejected=function(i){return i.split(" ",2)[1]==="0"};O.parseMLine=function(i){var t=O.splitLines(i),e=t[0].substr(2).split(" ");return{kind:e[0],port:parseInt(e[1],10),protocol:e[2],fmt:e.slice(3).join(" ")}};O.parseOLine=function(i){var t=O.matchPrefix(i,"o=")[0],e=t.substr(2).split(" ");return{username:e[0],sessionId:e[1],sessionVersion:parseInt(e[2],10),netType:e[3],addressType:e[4],address:e[5]}};O.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;for(var t=O.splitLines(i),e=0;e<t.length;e++)if(t[e].length<2||t[e].charAt(1)!=="=")return!1;return!0};typeof Zs=="object"&&(Zs.exports=O)});var qc=me((j_,Xc)=>{"use strict";var J_=h(_()),j=eo();function Dp(i){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[i.type]||i.type}function Jc(i,t,e,r,n){var s=j.writeRtpDescription(i.kind,t);if(s+=j.writeIceParameters(i.iceGatherer.getLocalParameters()),s+=j.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),e==="offer"?"actpass":n||"active"),s+="a=mid:"+i.mid+`\r
40
+ `,i.rtpSender&&i.rtpReceiver?s+=`a=sendrecv\r
41
+ `:i.rtpSender?s+=`a=sendonly\r
42
+ `:i.rtpReceiver?s+=`a=recvonly\r
43
+ `:s+=`a=inactive\r
44
+ `,i.rtpSender){var o=i.rtpSender._initialTrackId||i.rtpSender.track.id;i.rtpSender._initialTrackId=o;var a="msid:"+(r?r.id:"-")+" "+o+`\r
45
+ `;s+="a="+a,s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+a,i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
46
+ `)}return s+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+j.localCName+`\r
47
+ `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+j.localCName+`\r
48
+ `),s}function Op(i,t){var e=!1;return i=JSON.parse(JSON.stringify(i)),i.filter(function(r){if(r&&(r.urls||r.url)){var n=r.urls||r.url;r.url&&!r.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var s=typeof n=="string";return s&&(n=[n]),n=n.filter(function(o){var a=o.indexOf("turn:")===0&&o.indexOf("transport=udp")!==-1&&o.indexOf("turn:[")===-1&&!e;return a?(e=!0,!0):o.indexOf("stun:")===0&&t>=14393&&o.indexOf("?transport=udp")===-1}),delete r.url,r.urls=s?n[0]:n,!!n.length}})}function In(i,t){var e={codecs:[],headerExtensions:[],fecMechanisms:[]},r=function(s,o){s=parseInt(s,10);for(var a=0;a<o.length;a++)if(o[a].payloadType===s||o[a].preferredPayloadType===s)return o[a]},n=function(s,o,a,c){var d=r(s.parameters.apt,a),u=r(o.parameters.apt,c);return d&&u&&d.name.toLowerCase()===u.name.toLowerCase()};return i.codecs.forEach(function(s){for(var o=0;o<t.codecs.length;o++){var a=t.codecs[o];if(s.name.toLowerCase()===a.name.toLowerCase()&&s.clockRate===a.clockRate){if(s.name.toLowerCase()==="rtx"&&s.parameters&&a.parameters.apt&&!n(s,a,i.codecs,t.codecs))continue;a=JSON.parse(JSON.stringify(a)),a.numChannels=Math.min(s.numChannels,a.numChannels),e.codecs.push(a),a.rtcpFeedback=a.rtcpFeedback.filter(function(c){for(var d=0;d<s.rtcpFeedback.length;d++)if(s.rtcpFeedback[d].type===c.type&&s.rtcpFeedback[d].parameter===c.parameter)return!0;return!1});break}}}),i.headerExtensions.forEach(function(s){for(var o=0;o<t.headerExtensions.length;o++){var a=t.headerExtensions[o];if(s.uri===a.uri){e.headerExtensions.push(a);break}}}),e}function Yc(i,t,e){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[t][i].indexOf(e)!==-1}function to(i,t){var e=i.getRemoteCandidates().find(function(r){return t.foundation===r.foundation&&t.ip===r.ip&&t.port===r.port&&t.priority===r.priority&&t.protocol===r.protocol&&t.type===r.type});return e||i.addRemoteCandidate(t),!e}function ye(i,t){var e=new Error(t);return e.name=i,e.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[i],e}Xc.exports=function(i,t){function e(c,d){d.addTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("addtrack",{track:c}))}function r(c,d){d.removeTrack(c),d.dispatchEvent(new i.MediaStreamTrackEvent("removetrack",{track:c}))}function n(c,d,u,l){var m=new Event("track");m.track=d,m.receiver=u,m.transceiver={receiver:u},m.streams=l,i.setTimeout(function(){c._dispatchEvent("track",m)})}var s=function(c){var d=this,u=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(m){d[m]=u[m].bind(u)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",c=JSON.parse(JSON.stringify(c||{})),this.usingBundle=c.bundlePolicy==="max-bundle",c.rtcpMuxPolicy==="negotiate")throw ye("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(c.rtcpMuxPolicy||(c.rtcpMuxPolicy="require"),c.iceTransportPolicy){case"all":case"relay":break;default:c.iceTransportPolicy="all";break}switch(c.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:c.bundlePolicy="balanced";break}if(c.iceServers=Op(c.iceServers||[],t),this._iceGatherers=[],c.iceCandidatePoolSize)for(var l=c.iceCandidatePoolSize;l>0;l--)this._iceGatherers.push(new i.RTCIceGatherer({iceServers:c.iceServers,gatherPolicy:c.iceTransportPolicy}));else c.iceCandidatePoolSize=0;this._config=c,this.transceivers=[],this._sdpSessionId=j.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(s.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(s.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),s.prototype.onicecandidate=null,s.prototype.onaddstream=null,s.prototype.ontrack=null,s.prototype.onremovestream=null,s.prototype.onsignalingstatechange=null,s.prototype.oniceconnectionstatechange=null,s.prototype.onconnectionstatechange=null,s.prototype.onicegatheringstatechange=null,s.prototype.onnegotiationneeded=null,s.prototype.ondatachannel=null,s.prototype._dispatchEvent=function(c,d){this._isClosed||(this.dispatchEvent(d),typeof this["on"+c]=="function"&&this["on"+c](d))},s.prototype._emitGatheringStateChange=function(){var c=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",c)},s.prototype.getConfiguration=function(){return this._config},s.prototype.getLocalStreams=function(){return this.localStreams},s.prototype.getRemoteStreams=function(){return this.remoteStreams},s.prototype._createTransceiver=function(c,d){var u=this.transceivers.length>0,l={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:c,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&u)l.iceTransport=this.transceivers[0].iceTransport,l.dtlsTransport=this.transceivers[0].dtlsTransport;else{var m=this._createIceAndDtlsTransports();l.iceTransport=m.iceTransport,l.dtlsTransport=m.dtlsTransport}return d||this.transceivers.push(l),l},s.prototype.addTrack=function(c,d){if(this._isClosed)throw ye("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var u=this.transceivers.find(function(S){return S.track===c});if(u)throw ye("InvalidAccessError","Track already exists.");for(var l,m=0;m<this.transceivers.length;m++)!this.transceivers[m].track&&this.transceivers[m].kind===c.kind&&(l=this.transceivers[m]);return l||(l=this._createTransceiver(c.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(d)===-1&&this.localStreams.push(d),l.track=c,l.stream=d,l.rtpSender=new i.RTCRtpSender(c,l.dtlsTransport),l.rtpSender},s.prototype.addStream=function(c){var d=this;if(t>=15025)c.getTracks().forEach(function(l){d.addTrack(l,c)});else{var u=c.clone();c.getTracks().forEach(function(l,m){var S=u.getTracks()[m];l.addEventListener("enabled",function(E){S.enabled=E.enabled})}),u.getTracks().forEach(function(l){d.addTrack(l,u)})}},s.prototype.removeTrack=function(c){if(this._isClosed)throw ye("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(c instanceof i.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var d=this.transceivers.find(function(m){return m.rtpSender===c});if(!d)throw ye("InvalidAccessError","Sender was not created by this connection.");var u=d.stream;d.rtpSender.stop(),d.rtpSender=null,d.track=null,d.stream=null;var l=this.transceivers.map(function(m){return m.stream});l.indexOf(u)===-1&&this.localStreams.indexOf(u)>-1&&this.localStreams.splice(this.localStreams.indexOf(u),1),this._maybeFireNegotiationNeeded()},s.prototype.removeStream=function(c){var d=this;c.getTracks().forEach(function(u){var l=d.getSenders().find(function(m){return m.track===u});l&&d.removeTrack(l)})},s.prototype.getSenders=function(){return this.transceivers.filter(function(c){return!!c.rtpSender}).map(function(c){return c.rtpSender})},s.prototype.getReceivers=function(){return this.transceivers.filter(function(c){return!!c.rtpReceiver}).map(function(c){return c.rtpReceiver})},s.prototype._createIceGatherer=function(c,d){var u=this;if(d&&c>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var l=new i.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(l,"state",{value:"new",writable:!0}),this.transceivers[c].bufferedCandidateEvents=[],this.transceivers[c].bufferCandidates=function(m){var S=!m.candidate||Object.keys(m.candidate).length===0;l.state=S?"completed":"gathering",u.transceivers[c].bufferedCandidateEvents!==null&&u.transceivers[c].bufferedCandidateEvents.push(m)},l.addEventListener("localcandidate",this.transceivers[c].bufferCandidates),l},s.prototype._gather=function(c,d){var u=this,l=this.transceivers[d].iceGatherer;if(!l.onlocalcandidate){var m=this.transceivers[d].bufferedCandidateEvents;this.transceivers[d].bufferedCandidateEvents=null,l.removeEventListener("localcandidate",this.transceivers[d].bufferCandidates),l.onlocalcandidate=function(S){if(!(u.usingBundle&&d>0)){var E=new Event("icecandidate");E.candidate={sdpMid:c,sdpMLineIndex:d};var y=S.candidate,B=!y||Object.keys(y).length===0;if(B)(l.state==="new"||l.state==="gathering")&&(l.state="completed");else{l.state==="new"&&(l.state="gathering"),y.component=1,y.ufrag=l.getLocalParameters().usernameFragment;var x=j.writeCandidate(y);E.candidate=Object.assign(E.candidate,j.parseCandidate(x)),E.candidate.candidate=x,E.candidate.toJSON=function(){return{candidate:E.candidate.candidate,sdpMid:E.candidate.sdpMid,sdpMLineIndex:E.candidate.sdpMLineIndex,usernameFragment:E.candidate.usernameFragment}}}var F=j.getMediaSections(u._localDescription.sdp);B?F[E.candidate.sdpMLineIndex]+=`a=end-of-candidates\r
49
+ `:F[E.candidate.sdpMLineIndex]+="a="+E.candidate.candidate+`\r
50
+ `,u._localDescription.sdp=j.getDescription(u._localDescription.sdp)+F.join("");var Ee=u.transceivers.every(function(A){return A.iceGatherer&&A.iceGatherer.state==="completed"});u.iceGatheringState!=="gathering"&&(u.iceGatheringState="gathering",u._emitGatheringStateChange()),B||u._dispatchEvent("icecandidate",E),Ee&&(u._dispatchEvent("icecandidate",new Event("icecandidate")),u.iceGatheringState="complete",u._emitGatheringStateChange())}},i.setTimeout(function(){m.forEach(function(S){l.onlocalcandidate(S)})},0)}},s.prototype._createIceAndDtlsTransports=function(){var c=this,d=new i.RTCIceTransport(null);d.onicestatechange=function(){c._updateIceConnectionState(),c._updateConnectionState()};var u=new i.RTCDtlsTransport(d);return u.ondtlsstatechange=function(){c._updateConnectionState()},u.onerror=function(){Object.defineProperty(u,"state",{value:"failed",writable:!0}),c._updateConnectionState()},{iceTransport:d,dtlsTransport:u}},s.prototype._disposeIceAndDtlsTransports=function(c){var d=this.transceivers[c].iceGatherer;d&&(delete d.onlocalcandidate,delete this.transceivers[c].iceGatherer);var u=this.transceivers[c].iceTransport;u&&(delete u.onicestatechange,delete this.transceivers[c].iceTransport);var l=this.transceivers[c].dtlsTransport;l&&(delete l.ondtlsstatechange,delete l.onerror,delete this.transceivers[c].dtlsTransport)},s.prototype._transceive=function(c,d,u){var l=In(c.localCapabilities,c.remoteCapabilities);d&&c.rtpSender&&(l.encodings=c.sendEncodingParameters,l.rtcp={cname:j.localCName,compound:c.rtcpParameters.compound},c.recvEncodingParameters.length&&(l.rtcp.ssrc=c.recvEncodingParameters[0].ssrc),c.rtpSender.send(l)),u&&c.rtpReceiver&&l.codecs.length>0&&(c.kind==="video"&&c.recvEncodingParameters&&t<15019&&c.recvEncodingParameters.forEach(function(m){delete m.rtx}),c.recvEncodingParameters.length?l.encodings=c.recvEncodingParameters:l.encodings=[{}],l.rtcp={compound:c.rtcpParameters.compound},c.rtcpParameters.cname&&(l.rtcp.cname=c.rtcpParameters.cname),c.sendEncodingParameters.length&&(l.rtcp.ssrc=c.sendEncodingParameters[0].ssrc),c.rtpReceiver.receive(l))},s.prototype.setLocalDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(ye("TypeError",'Unsupported type "'+c.type+'"'));if(!Yc("setLocalDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(ye("InvalidStateError","Can not set local "+c.type+" in state "+d.signalingState));var u,l;if(c.type==="offer")u=j.splitSections(c.sdp),l=u.shift(),u.forEach(function(S,E){var y=j.parseRtpParameters(S);d.transceivers[E].localCapabilities=y}),d.transceivers.forEach(function(S,E){d._gather(S.mid,E)});else if(c.type==="answer"){u=j.splitSections(d._remoteDescription.sdp),l=u.shift();var m=j.matchPrefix(l,"a=ice-lite").length>0;u.forEach(function(S,E){var y=d.transceivers[E],B=y.iceGatherer,x=y.iceTransport,F=y.dtlsTransport,Ee=y.localCapabilities,A=y.remoteCapabilities,U=j.isRejected(S)&&j.matchPrefix(S,"a=bundle-only").length===0;if(!U&&!y.rejected){var v=j.getIceParameters(S,l),J=j.getDtlsParameters(S,l);m&&(J.role="server"),(!d.usingBundle||E===0)&&(d._gather(y.mid,E),x.state==="new"&&x.start(B,v,m?"controlling":"controlled"),F.state==="new"&&F.start(J));var Z=In(Ee,A);d._transceive(y,Z.codecs.length>0,!1)}})}return d._localDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-local-offer"):d._updateSignalingState("stable"),Promise.resolve()},s.prototype.setRemoteDescription=function(c){var d=this;if(["offer","answer"].indexOf(c.type)===-1)return Promise.reject(ye("TypeError",'Unsupported type "'+c.type+'"'));if(!Yc("setRemoteDescription",c.type,d.signalingState)||d._isClosed)return Promise.reject(ye("InvalidStateError","Can not set remote "+c.type+" in state "+d.signalingState));var u={};d.remoteStreams.forEach(function(x){u[x.id]=x});var l=[],m=j.splitSections(c.sdp),S=m.shift(),E=j.matchPrefix(S,"a=ice-lite").length>0,y=j.matchPrefix(S,"a=group:BUNDLE ").length>0;d.usingBundle=y;var B=j.matchPrefix(S,"a=ice-options:")[0];return B?d.canTrickleIceCandidates=B.substr(14).split(" ").indexOf("trickle")>=0:d.canTrickleIceCandidates=!1,m.forEach(function(x,F){var Ee=j.splitLines(x),A=j.getKind(x),U=j.isRejected(x)&&j.matchPrefix(x,"a=bundle-only").length===0,v=Ee[0].substr(2).split(" ")[2],J=j.getDirection(x,S),Z=j.parseMsid(x),Te=j.getMid(x)||j.generateIdentifier();if(U||A==="application"&&(v==="DTLS/SCTP"||v==="UDP/DTLS/SCTP")){d.transceivers[F]={mid:Te,kind:A,protocol:v,rejected:!0};return}!U&&d.transceivers[F]&&d.transceivers[F].rejected&&(d.transceivers[F]=d._createTransceiver(A,!0));var W,k,g,R,L,$s,Hs,nr,Ct,vc=j.parseRtpParameters(x),yc,Fs;U||(yc=j.getIceParameters(x,S),Fs=j.getDtlsParameters(x,S),Fs.role="client"),Hs=j.parseRtpEncodingParameters(x);var Nc=j.parseRtcpParameters(x),Dc=j.matchPrefix(x,"a=end-of-candidates",S).length>0,Oi=j.matchPrefix(x,"a=candidate:").map(function(xe){return j.parseCandidate(xe)}).filter(function(xe){return xe.component===1});if((c.type==="offer"||c.type==="answer")&&!U&&y&&F>0&&d.transceivers[F]&&(d._disposeIceAndDtlsTransports(F),d.transceivers[F].iceGatherer=d.transceivers[0].iceGatherer,d.transceivers[F].iceTransport=d.transceivers[0].iceTransport,d.transceivers[F].dtlsTransport=d.transceivers[0].dtlsTransport,d.transceivers[F].rtpSender&&d.transceivers[F].rtpSender.setTransport(d.transceivers[0].dtlsTransport),d.transceivers[F].rtpReceiver&&d.transceivers[F].rtpReceiver.setTransport(d.transceivers[0].dtlsTransport)),c.type==="offer"&&!U){W=d.transceivers[F]||d._createTransceiver(A),W.mid=Te,W.iceGatherer||(W.iceGatherer=d._createIceGatherer(F,y)),Oi.length&&W.iceTransport.state==="new"&&(Dc&&(!y||F===0)?W.iceTransport.setRemoteCandidates(Oi):Oi.forEach(function(xe){to(W.iceTransport,xe)})),nr=i.RTCRtpReceiver.getCapabilities(A),t<15019&&(nr.codecs=nr.codecs.filter(function(xe){return xe.name!=="rtx"})),$s=W.sendEncodingParameters||[{ssrc:(2*F+2)*1001}];var Gs=!1;if(J==="sendrecv"||J==="sendonly"){if(Gs=!W.rtpReceiver,L=W.rtpReceiver||new i.RTCRtpReceiver(W.dtlsTransport,A),Gs){var K;Ct=L.track,Z&&Z.stream==="-"||(Z?(u[Z.stream]||(u[Z.stream]=new i.MediaStream,Object.defineProperty(u[Z.stream],"id",{get:function(){return Z.stream}})),Object.defineProperty(Ct,"id",{get:function(){return Z.track}}),K=u[Z.stream]):(u.default||(u.default=new i.MediaStream),K=u.default)),K&&(e(Ct,K),W.associatedRemoteMediaStreams.push(K)),l.push([Ct,L,K])}}else W.rtpReceiver&&W.rtpReceiver.track&&(W.associatedRemoteMediaStreams.forEach(function(xe){var Oc=xe.getTracks().find(function(Wl){return Wl.id===W.rtpReceiver.track.id});Oc&&r(Oc,xe)}),W.associatedRemoteMediaStreams=[]);W.localCapabilities=nr,W.remoteCapabilities=vc,W.rtpReceiver=L,W.rtcpParameters=Nc,W.sendEncodingParameters=$s,W.recvEncodingParameters=Hs,d._transceive(d.transceivers[F],!1,Gs)}else if(c.type==="answer"&&!U){W=d.transceivers[F],k=W.iceGatherer,g=W.iceTransport,R=W.dtlsTransport,L=W.rtpReceiver,$s=W.sendEncodingParameters,nr=W.localCapabilities,d.transceivers[F].recvEncodingParameters=Hs,d.transceivers[F].remoteCapabilities=vc,d.transceivers[F].rtcpParameters=Nc,Oi.length&&g.state==="new"&&((E||Dc)&&(!y||F===0)?g.setRemoteCandidates(Oi):Oi.forEach(function(xe){to(W.iceTransport,xe)})),(!y||F===0)&&(g.state==="new"&&g.start(k,yc,"controlling"),R.state==="new"&&R.start(Fs));var Fl=In(W.localCapabilities,W.remoteCapabilities),Gl=Fl.codecs.filter(function(xe){return xe.name.toLowerCase()==="rtx"}).length;!Gl&&W.sendEncodingParameters[0].rtx&&delete W.sendEncodingParameters[0].rtx,d._transceive(W,J==="sendrecv"||J==="recvonly",J==="sendrecv"||J==="sendonly"),L&&(J==="sendrecv"||J==="sendonly")?(Ct=L.track,Z?(u[Z.stream]||(u[Z.stream]=new i.MediaStream),e(Ct,u[Z.stream]),l.push([Ct,L,u[Z.stream]])):(u.default||(u.default=new i.MediaStream),e(Ct,u.default),l.push([Ct,L,u.default]))):delete W.rtpReceiver}}),d._dtlsRole===void 0&&(d._dtlsRole=c.type==="offer"?"active":"passive"),d._remoteDescription={type:c.type,sdp:c.sdp},c.type==="offer"?d._updateSignalingState("have-remote-offer"):d._updateSignalingState("stable"),Object.keys(u).forEach(function(x){var F=u[x];if(F.getTracks().length){if(d.remoteStreams.indexOf(F)===-1){d.remoteStreams.push(F);var Ee=new Event("addstream");Ee.stream=F,i.setTimeout(function(){d._dispatchEvent("addstream",Ee)})}l.forEach(function(A){var U=A[0],v=A[1];F.id===A[2].id&&n(d,U,v,[F])})}}),l.forEach(function(x){x[2]||n(d,x[0],x[1],[])}),i.setTimeout(function(){!(d&&d.transceivers)||d.transceivers.forEach(function(x){x.iceTransport&&x.iceTransport.state==="new"&&x.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),x.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},s.prototype.close=function(){this.transceivers.forEach(function(c){c.iceTransport&&c.iceTransport.stop(),c.dtlsTransport&&c.dtlsTransport.stop(),c.rtpSender&&c.rtpSender.stop(),c.rtpReceiver&&c.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},s.prototype._updateSignalingState=function(c){this.signalingState=c;var d=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",d)},s.prototype._maybeFireNegotiationNeeded=function(){var c=this;this.signalingState!=="stable"||this.needNegotiation===!0||(this.needNegotiation=!0,i.setTimeout(function(){if(c.needNegotiation){c.needNegotiation=!1;var d=new Event("negotiationneeded");c._dispatchEvent("negotiationneeded",d)}},0))},s.prototype._updateIceConnectionState=function(){var c,d={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&!l.rejected&&d[l.iceTransport.state]++}),c="new",d.failed>0?c="failed":d.checking>0?c="checking":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0?c="connected":d.completed>0&&(c="completed"),c!==this.iceConnectionState){this.iceConnectionState=c;var u=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",u)}},s.prototype._updateConnectionState=function(){var c,d={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(l){l.iceTransport&&l.dtlsTransport&&!l.rejected&&(d[l.iceTransport.state]++,d[l.dtlsTransport.state]++)}),d.connected+=d.completed,c="new",d.failed>0?c="failed":d.connecting>0?c="connecting":d.disconnected>0?c="disconnected":d.new>0?c="new":d.connected>0&&(c="connected"),c!==this.connectionState){this.connectionState=c;var u=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",u)}},s.prototype.createOffer=function(){var c=this;if(c._isClosed)return Promise.reject(ye("InvalidStateError","Can not call createOffer after close"));var d=c.transceivers.filter(function(E){return E.kind==="audio"}).length,u=c.transceivers.filter(function(E){return E.kind==="video"}).length,l=arguments[0];if(l){if(l.mandatory||l.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");l.offerToReceiveAudio!==void 0&&(l.offerToReceiveAudio===!0?d=1:l.offerToReceiveAudio===!1?d=0:d=l.offerToReceiveAudio),l.offerToReceiveVideo!==void 0&&(l.offerToReceiveVideo===!0?u=1:l.offerToReceiveVideo===!1?u=0:u=l.offerToReceiveVideo)}for(c.transceivers.forEach(function(E){E.kind==="audio"?(d--,d<0&&(E.wantReceive=!1)):E.kind==="video"&&(u--,u<0&&(E.wantReceive=!1))});d>0||u>0;)d>0&&(c._createTransceiver("audio"),d--),u>0&&(c._createTransceiver("video"),u--);var m=j.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.transceivers.forEach(function(E,y){var B=E.track,x=E.kind,F=E.mid||j.generateIdentifier();E.mid=F,E.iceGatherer||(E.iceGatherer=c._createIceGatherer(y,c.usingBundle));var Ee=i.RTCRtpSender.getCapabilities(x);t<15019&&(Ee.codecs=Ee.codecs.filter(function(U){return U.name!=="rtx"})),Ee.codecs.forEach(function(U){U.name==="H264"&&U.parameters["level-asymmetry-allowed"]===void 0&&(U.parameters["level-asymmetry-allowed"]="1"),E.remoteCapabilities&&E.remoteCapabilities.codecs&&E.remoteCapabilities.codecs.forEach(function(v){U.name.toLowerCase()===v.name.toLowerCase()&&U.clockRate===v.clockRate&&(U.preferredPayloadType=v.payloadType)})}),Ee.headerExtensions.forEach(function(U){var v=E.remoteCapabilities&&E.remoteCapabilities.headerExtensions||[];v.forEach(function(J){U.uri===J.uri&&(U.id=J.id)})});var A=E.sendEncodingParameters||[{ssrc:(2*y+1)*1001}];B&&t>=15019&&x==="video"&&!A[0].rtx&&(A[0].rtx={ssrc:A[0].ssrc+1}),E.wantReceive&&(E.rtpReceiver=new i.RTCRtpReceiver(E.dtlsTransport,x)),E.localCapabilities=Ee,E.sendEncodingParameters=A}),c._config.bundlePolicy!=="max-compat"&&(m+="a=group:BUNDLE "+c.transceivers.map(function(E){return E.mid}).join(" ")+`\r
51
+ `),m+=`a=ice-options:trickle\r
52
+ `,c.transceivers.forEach(function(E,y){m+=Jc(E,E.localCapabilities,"offer",E.stream,c._dtlsRole),m+=`a=rtcp-rsize\r
53
+ `,E.iceGatherer&&c.iceGatheringState!=="new"&&(y===0||!c.usingBundle)&&(E.iceGatherer.getLocalCandidates().forEach(function(B){B.component=1,m+="a="+j.writeCandidate(B)+`\r
54
+ `}),E.iceGatherer.state==="completed"&&(m+=`a=end-of-candidates\r
55
+ `))});var S=new i.RTCSessionDescription({type:"offer",sdp:m});return Promise.resolve(S)},s.prototype.createAnswer=function(){var c=this;if(c._isClosed)return Promise.reject(ye("InvalidStateError","Can not call createAnswer after close"));if(!(c.signalingState==="have-remote-offer"||c.signalingState==="have-local-pranswer"))return Promise.reject(ye("InvalidStateError","Can not call createAnswer in signalingState "+c.signalingState));var d=j.writeSessionBoilerplate(c._sdpSessionId,c._sdpSessionVersion++);c.usingBundle&&(d+="a=group:BUNDLE "+c.transceivers.map(function(m){return m.mid}).join(" ")+`\r
56
+ `),d+=`a=ice-options:trickle\r
57
+ `;var u=j.getMediaSections(c._remoteDescription.sdp).length;c.transceivers.forEach(function(m,S){if(!(S+1>u)){if(m.rejected){m.kind==="application"?m.protocol==="DTLS/SCTP"?d+=`m=application 0 DTLS/SCTP 5000\r
58
+ `:d+="m=application 0 "+m.protocol+` webrtc-datachannel\r
59
+ `:m.kind==="audio"?d+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
60
+ a=rtpmap:0 PCMU/8000\r
61
+ `:m.kind==="video"&&(d+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
62
+ a=rtpmap:120 VP8/90000\r
63
+ `),d+=`c=IN IP4 0.0.0.0\r
64
+ a=inactive\r
65
+ a=mid:`+m.mid+`\r
66
+ `;return}if(m.stream){var E;m.kind==="audio"?E=m.stream.getAudioTracks()[0]:m.kind==="video"&&(E=m.stream.getVideoTracks()[0]),E&&t>=15019&&m.kind==="video"&&!m.sendEncodingParameters[0].rtx&&(m.sendEncodingParameters[0].rtx={ssrc:m.sendEncodingParameters[0].ssrc+1})}var y=In(m.localCapabilities,m.remoteCapabilities),B=y.codecs.filter(function(x){return x.name.toLowerCase()==="rtx"}).length;!B&&m.sendEncodingParameters[0].rtx&&delete m.sendEncodingParameters[0].rtx,d+=Jc(m,y,"answer",m.stream,c._dtlsRole),m.rtcpParameters&&m.rtcpParameters.reducedSize&&(d+=`a=rtcp-rsize\r
67
+ `)}});var l=new i.RTCSessionDescription({type:"answer",sdp:d});return Promise.resolve(l)},s.prototype.addIceCandidate=function(c){var d=this,u;return c&&!(c.sdpMLineIndex!==void 0||c.sdpMid)?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(l,m){if(d._remoteDescription)if(!c||c.candidate==="")for(var S=0;S<d.transceivers.length&&!(!d.transceivers[S].rejected&&(d.transceivers[S].iceTransport.addRemoteCandidate({}),u=j.getMediaSections(d._remoteDescription.sdp),u[S]+=`a=end-of-candidates\r
68
+ `,d._remoteDescription.sdp=j.getDescription(d._remoteDescription.sdp)+u.join(""),d.usingBundle));S++);else{var E=c.sdpMLineIndex;if(c.sdpMid){for(var y=0;y<d.transceivers.length;y++)if(d.transceivers[y].mid===c.sdpMid){E=y;break}}var B=d.transceivers[E];if(B){if(B.rejected)return l();var x=Object.keys(c.candidate).length>0?j.parseCandidate(c.candidate):{};if(x.protocol==="tcp"&&(x.port===0||x.port===9)||x.component&&x.component!==1)return l();if((E===0||E>0&&B.iceTransport!==d.transceivers[0].iceTransport)&&!to(B.iceTransport,x))return m(ye("OperationError","Can not add ICE candidate"));var F=c.candidate.trim();F.indexOf("a=")===0&&(F=F.substr(2)),u=j.getMediaSections(d._remoteDescription.sdp),u[E]+="a="+(x.type?F:"end-of-candidates")+`\r
69
+ `,d._remoteDescription.sdp=j.getDescription(d._remoteDescription.sdp)+u.join("")}else return m(ye("OperationError","Can not add ICE candidate"))}else return m(ye("InvalidStateError","Can not add ICE candidate without a remote description"));l()})},s.prototype.getStats=function(c){if(c&&c instanceof i.MediaStreamTrack){var d=null;if(this.transceivers.forEach(function(l){l.rtpSender&&l.rtpSender.track===c?d=l.rtpSender:l.rtpReceiver&&l.rtpReceiver.track===c&&(d=l.rtpReceiver)}),!d)throw ye("InvalidAccessError","Invalid selector.");return d.getStats()}var u=[];return this.transceivers.forEach(function(l){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(m){l[m]&&u.push(l[m].getStats())})}),Promise.all(u).then(function(l){var m=new Map;return l.forEach(function(S){S.forEach(function(E){m.set(E.id,E)})}),m})};var o=["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"];o.forEach(function(c){var d=i[c];if(d&&d.prototype&&d.prototype.getStats){var u=d.prototype.getStats;d.prototype.getStats=function(){return u.apply(this).then(function(l){var m=new Map;return Object.keys(l).forEach(function(S){l[S].type=Dp(l[S]),m.set(S,l[S])}),m})}}});var a=["createOffer","createAnswer"];return a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[0]=="function"||typeof u[1]=="function"?d.apply(this,[arguments[2]]).then(function(l){typeof u[0]=="function"&&u[0].apply(null,[l])},function(l){typeof u[1]=="function"&&u[1].apply(null,[l])}):d.apply(this,arguments)}}),a=["setLocalDescription","setRemoteDescription","addIceCandidate"],a.forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"||typeof u[2]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)},function(l){typeof u[2]=="function"&&u[2].apply(null,[l])}):d.apply(this,arguments)}}),["getStats"].forEach(function(c){var d=s.prototype[c];s.prototype[c]=function(){var u=arguments;return typeof u[1]=="function"?d.apply(this,arguments).then(function(){typeof u[1]=="function"&&u[1].apply(null)}):d.apply(this,arguments)}}),s}});var zc=me(Ht=>{"use strict";var X_=h(_());Object.defineProperty(Ht,"__esModule",{value:!0});Ht.shimGetDisplayMedia=Ht.shimGetUserMedia=void 0;var bp=Wc();Object.defineProperty(Ht,"shimGetUserMedia",{enumerable:!0,get:function(){return bp.shimGetUserMedia}});var Pp=Kc();Object.defineProperty(Ht,"shimGetDisplayMedia",{enumerable:!0,get:function(){return Pp.shimGetDisplayMedia}});Ht.shimPeerConnection=Bp;Ht.shimReplaceTrack=$p;var Mp=ut(),Lp=wp(Mp),kp=jc(),xp=qc(),Up=Vp(xp);function Vp(i){return i&&i.__esModule?i:{default:i}}function wp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Bp(i,t){if(i.RTCIceGatherer&&(i.RTCIceCandidate||(i.RTCIceCandidate=function(s){return s}),i.RTCSessionDescription||(i.RTCSessionDescription=function(s){return s}),t.version<15025)){var e=Object.getOwnPropertyDescriptor(i.MediaStreamTrack.prototype,"enabled");Object.defineProperty(i.MediaStreamTrack.prototype,"enabled",{set:function(s){e.set.call(this,s);var o=new Event("enabled");o.enabled=s,this.dispatchEvent(o)}})}i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)&&Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new i.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),i.RTCDtmfSender&&!i.RTCDTMFSender&&(i.RTCDTMFSender=i.RTCDtmfSender);var r=(0,Up.default)(i,t.version);i.RTCPeerConnection=function(s){return s&&s.iceServers&&(s.iceServers=(0,kp.filterIceServers)(s.iceServers,t.version),Lp.log("ICE servers after filtering:",s.iceServers)),new r(s)},i.RTCPeerConnection.prototype=r.prototype}function $p(i){i.RTCRtpSender&&!("replaceTrack"in i.RTCRtpSender.prototype)&&(i.RTCRtpSender.prototype.replaceTrack=i.RTCRtpSender.prototype.setTrack)}});var Qc=me(ro=>{"use strict";var z_=h(_());Object.defineProperty(ro,"__esModule",{value:!0});var io=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};ro.shimGetUserMedia=Wp;var Hp=ut(),Fp=Gp(Hp);function Gp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function Wp(i,t){var e=i&&i.navigator,r=i&&i.MediaStreamTrack;if(e.getUserMedia=function(c,d,u){Fp.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),e.mediaDevices.getUserMedia(c).then(d,u)},!(t.version>55&&"autoGainControl"in e.mediaDevices.getSupportedConstraints())){var n=function(d,u,l){u in d&&!(l in d)&&(d[l]=d[u],delete d[u])},s=e.mediaDevices.getUserMedia.bind(e.mediaDevices);if(e.mediaDevices.getUserMedia=function(c){return(typeof c=="undefined"?"undefined":io(c))==="object"&&io(c.audio)==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c.audio,"autoGainControl","mozAutoGainControl"),n(c.audio,"noiseSuppression","mozNoiseSuppression")),s(c)},r&&r.prototype.getSettings){var o=r.prototype.getSettings;r.prototype.getSettings=function(){var c=o.apply(this,arguments);return n(c,"mozAutoGainControl","autoGainControl"),n(c,"mozNoiseSuppression","noiseSuppression"),c}}if(r&&r.prototype.applyConstraints){var a=r.prototype.applyConstraints;r.prototype.applyConstraints=function(c){return this.kind==="audio"&&(typeof c=="undefined"?"undefined":io(c))==="object"&&(c=JSON.parse(JSON.stringify(c)),n(c,"autoGainControl","mozAutoGainControl"),n(c,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[c])}}}}});var Zc=me(no=>{"use strict";var Z_=h(_());Object.defineProperty(no,"__esModule",{value:!0});no.shimGetDisplayMedia=Kp;function Kp(i,t){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||!i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(r){if(!(r&&r.video)){var n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return r.video===!0?r.video={mediaSource:t}:r.video.mediaSource=t,i.navigator.mediaDevices.getUserMedia(r)})}});var td=me(Ne=>{"use strict";var tf=h(_());Object.defineProperty(Ne,"__esModule",{value:!0});Ne.shimGetDisplayMedia=Ne.shimGetUserMedia=void 0;var Ft=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},jp=Qc();Object.defineProperty(Ne,"shimGetUserMedia",{enumerable:!0,get:function(){return jp.shimGetUserMedia}});var Jp=Zc();Object.defineProperty(Ne,"shimGetDisplayMedia",{enumerable:!0,get:function(){return Jp.shimGetDisplayMedia}});Ne.shimOnTrack=zp;Ne.shimPeerConnection=Qp;Ne.shimSenderGetStats=Zp;Ne.shimReceiverGetStats=em;Ne.shimRemoveStream=tm;Ne.shimRTCDataChannel=im;Ne.shimAddTransceiver=rm;Ne.shimGetParameters=nm;Ne.shimCreateOffer=sm;Ne.shimCreateAnswer=om;var Yp=ut(),ed=Xp(Yp);function Xp(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function qp(i,t,e){return t in i?Object.defineProperty(i,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):i[t]=e,i}function zp(i){(typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function Qp(i,t){if(!((typeof i=="undefined"?"undefined":Ft(i))!=="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))){!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){var s=i.RTCPeerConnection.prototype[n],o=qp({},n,function(){return arguments[0]=new(n==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)});i.RTCPeerConnection.prototype[n]=o[n]});var e={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},r=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){var s=Array.prototype.slice.call(arguments),o=s[0],a=s[1],c=s[2];return r.apply(this,[o||null]).then(function(d){if(t.version<53&&!a)try{d.forEach(function(u){u.type=e[u.type]||u.type})}catch(u){if(u.name!=="TypeError")throw u;d.forEach(function(l,m){d.set(m,Object.assign({},l,{type:e[l.type]||l.type}))})}return d}).then(a,c)}}}function Zp(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)){var t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){var n=this,s=t.apply(this,[]);return s.forEach(function(o){return o._pc=n}),s});var e=i.RTCPeerConnection.prototype.addTrack;e&&(i.RTCPeerConnection.prototype.addTrack=function(){var n=e.apply(this,arguments);return n._pc=this,n}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function em(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCPeerConnection&&i.RTCRtpSender)&&!(i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)){var t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){var r=this,n=t.apply(this,[]);return n.forEach(function(s){return s._pc=r}),n}),ed.wrapPeerConnectionEvent(i,"track",function(e){return e.receiver._pc=e.srcElement,e}),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function tm(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(e){var r=this;ed.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(n){n.track&&e.getTracks().includes(n.track)&&r.removeTrack(n)})})}function im(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function rm(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var r=arguments[1],n=r&&"sendEncodings"in r;n&&r.sendEncodings.forEach(function(c){if("rid"in c){var d=/^[a-z0-9]{0,16}$/i;if(!d.test(c.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in c&&!(parseFloat(c.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in c&&!(parseFloat(c.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var s=t.apply(this,arguments);if(n){var o=s.sender,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=r.sendEncodings,o.sendEncodings=r.sendEncodings,this.setParametersPromises.push(o.setParameters(a).then(function(){delete o.sendEncodings}).catch(function(){delete o.sendEncodings})))}return s})}}function nm(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCRtpSender)){var t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){var r=t.apply(this,arguments);return"encodings"in r||(r.encodings=[].concat(this.sendEncodings||[{}])),r})}}function sm(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}function om(i){if(!!((typeof i=="undefined"?"undefined":Ft(i))==="object"&&i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){var r=this,n=arguments;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return t.apply(r,n)}).finally(function(){r.setParametersPromises=[]}):t.apply(this,arguments)}}}});var nd=me(tt=>{"use strict";var nf=h(_());Object.defineProperty(tt,"__esModule",{value:!0});var dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};tt.shimLocalStreamsAPI=dm;tt.shimRemoteStreamsAPI=um;tt.shimCallbacksAPI=lm;tt.shimGetUserMedia=pm;tt.shimConstraints=rd;tt.shimRTCIceServerUrls=mm;tt.shimTrackEventTransceiver=hm;tt.shimCreateOfferLegacy=_m;tt.shimAudioContext=fm;var am=ut(),id=cm(am);function cm(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function dm(i){if(!((typeof i=="undefined"?"undefined":dr(i))!=="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(r){var n=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(r)||this._localStreams.push(r),r.getAudioTracks().forEach(function(s){return t.call(n,s,r)}),r.getVideoTracks().forEach(function(s){return t.call(n,s,r)})},i.RTCPeerConnection.prototype.addTrack=function(r){for(var n=this,s=arguments.length,o=Array(s>1?s-1:0),a=1;a<s;a++)o[a-1]=arguments[a];return o&&o.forEach(function(c){n._localStreams?n._localStreams.includes(c)||n._localStreams.push(c):n._localStreams=[c]}),t.apply(this,arguments)}}"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(r){var n=this;this._localStreams||(this._localStreams=[]);var s=this._localStreams.indexOf(r);if(s!==-1){this._localStreams.splice(s,1);var o=r.getTracks();this.getSenders().forEach(function(a){o.includes(a.track)&&n.removeTrack(a)})}})}}function um(i){if(!((typeof i=="undefined"?"undefined":dr(i))!=="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(r){var n=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=r),this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(function(o){if(n._remoteStreams||(n._remoteStreams=[]),!n._remoteStreams.includes(o)){n._remoteStreams.push(o);var a=new Event("addstream");a.stream=o,n.dispatchEvent(a)}})})}});var t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){var r=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(function(s){if(r._remoteStreams||(r._remoteStreams=[]),!(r._remoteStreams.indexOf(s)>=0)){r._remoteStreams.push(s);var o=new Event("addstream");o.stream=s,r.dispatchEvent(o)}})}),t.apply(r,arguments)}}}function lm(i){if(!((typeof i=="undefined"?"undefined":dr(i))!=="object"||!i.RTCPeerConnection)){var t=i.RTCPeerConnection.prototype,e=t.createOffer,r=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],m=e.apply(this,[l]);return u?(m.then(d,u),Promise.resolve()):m},t.createAnswer=function(d,u){var l=arguments.length>=2?arguments[2]:arguments[0],m=r.apply(this,[l]);return u?(m.then(d,u),Promise.resolve()):m};var a=function(d,u,l){var m=n.apply(this,[d]);return l?(m.then(u,l),Promise.resolve()):m};t.setLocalDescription=a,a=function(d,u,l){var m=s.apply(this,[d]);return l?(m.then(u,l),Promise.resolve()):m},t.setRemoteDescription=a,a=function(d,u,l){var m=o.apply(this,[d]);return l?(m.then(u,l),Promise.resolve()):m},t.addIceCandidate=a}}function pm(i){var t=i&&i.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){var e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=function(n){return r(rd(n))}}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(s,o,a){t.mediaDevices.getUserMedia(s).then(o,a)}.bind(t))}function rd(i){return i&&i.video!==void 0?Object.assign({},i,{video:id.compactObject(i.video)}):i}function mm(i){if(!!i.RTCPeerConnection){var t=i.RTCPeerConnection;i.RTCPeerConnection=function(r,n){if(r&&r.iceServers){for(var s=[],o=0;o<r.iceServers.length;o++){var a=r.iceServers[o];!a.hasOwnProperty("urls")&&a.hasOwnProperty("url")?(id.deprecated("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(r.iceServers[o])}r.iceServers=s}return new t(r,n)},i.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get:function(){return t.generateCertificate}})}}function hm(i){(typeof i=="undefined"?"undefined":dr(i))==="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function _m(i){var t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(r){if(r){typeof r.offerToReceiveAudio!="undefined"&&(r.offerToReceiveAudio=!!r.offerToReceiveAudio);var n=this.getTransceivers().find(function(o){return o.receiver.track.kind==="audio"});r.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):r.offerToReceiveAudio===!0&&!n&&this.addTransceiver("audio"),typeof r.offerToReceiveVideo!="undefined"&&(r.offerToReceiveVideo=!!r.offerToReceiveVideo);var s=this.getTransceivers().find(function(o){return o.receiver.track.kind==="video"});r.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):r.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video")}return t.apply(this,arguments)}}function fm(i){(typeof i=="undefined"?"undefined":dr(i))!=="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}});var od=me(Gt=>{"use strict";var of=h(_());Object.defineProperty(Gt,"__esModule",{value:!0});var Em=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i};Gt.shimRTCIceCandidate=Rm;Gt.shimMaxMessageSize=Am;Gt.shimSendThrowTypeError=Cm;Gt.shimConnectionState=vm;Gt.removeExtmapAllowMixed=ym;Gt.shimAddIceCandidateNullOrEmpty=Nm;var Tm=eo(),gn=gm(Tm),Sm=ut(),sd=Im(Sm);function Im(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function gm(i){return i&&i.__esModule?i:{default:i}}function Rm(i){if(!(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)){var t=i.RTCIceCandidate;i.RTCIceCandidate=function(r){if((typeof r=="undefined"?"undefined":Em(r))==="object"&&r.candidate&&r.candidate.indexOf("a=")===0&&(r=JSON.parse(JSON.stringify(r)),r.candidate=r.candidate.substr(2)),r.candidate&&r.candidate.length){var n=new t(r),s=gn.default.parseCandidate(r.candidate),o=Object.assign(n,s);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(r)},i.RTCIceCandidate.prototype=t.prototype,sd.wrapPeerConnectionEvent(i,"icecandidate",function(e){return e.candidate&&Object.defineProperty(e,"candidate",{value:new i.RTCIceCandidate(e.candidate),writable:"false"}),e})}}function Am(i,t){if(!!i.RTCPeerConnection){"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp}});var e=function(c){if(!c||!c.sdp)return!1;var d=gn.default.splitSections(c.sdp);return d.shift(),d.some(function(u){var l=gn.default.parseMLine(u);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},r=function(c){var d=c.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;var u=parseInt(d[1],10);return u!==u?-1:u},n=function(c){var d=65536;return t.browser==="firefox"&&(t.version<57?c===-1?d=16384:d=2147483637:t.version<60?d=t.version===57?65535:65536:d=2147483637),d},s=function(c,d){var u=65536;t.browser==="firefox"&&t.version===57&&(u=65535);var l=gn.default.matchPrefix(c.sdp,"a=max-message-size:");return l.length>0?u=parseInt(l[0].substr(19),10):t.browser==="firefox"&&d!==-1&&(u=2147483637),u},o=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){var c=this.getConfiguration(),d=c.sdpSemantics;d==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return typeof this._sctp=="undefined"?null:this._sctp},enumerable:!0,configurable:!0})}if(e(arguments[0])){var u=r(arguments[0]),l=n(u),m=s(arguments[0],u),S=void 0;l===0&&m===0?S=Number.POSITIVE_INFINITY:l===0||m===0?S=Math.max(l,m):S=Math.min(l,m);var E={};Object.defineProperty(E,"maxMessageSize",{get:function(){return S}}),this._sctp=E}return o.apply(this,arguments)}}}function Cm(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function t(r,n){var s=r.send;r.send=function(){var a=arguments[0],c=a.length||a.size||a.byteLength;if(r.readyState==="open"&&n.sctp&&c>n.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+n.sctp.maxMessageSize+" bytes)");return s.apply(r,arguments)}}var e=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){var n=e.apply(this,arguments);return t(n,this),n},sd.wrapPeerConnectionEvent(i,"datachannel",function(r){return t(r.channel,r.target),r})}function vm(i){if(!(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)){var t=i.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(r){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),r&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=r)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(e){var r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(n){var s=n.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;var o=new Event("connectionstatechange",n);s.dispatchEvent(o)}return n},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}})}}function ym(i,t){if(!!i.RTCPeerConnection&&!(t.browser==="chrome"&&t.version>=71)&&!(t.browser==="safari"&&t.version>=605)){var e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
70
+ a=extmap-allow-mixed`)!==-1){var s=n.sdp.split(`
71
+ `).filter(function(o){return o.trim()!=="a=extmap-allow-mixed"}).join(`
72
+ `);i.RTCSessionDescription&&n instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:n.type,sdp:s}):n.sdp=s}return e.apply(this,arguments)}}}function Nm(i,t){if(!!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype)){var e=i.RTCPeerConnection.prototype.addIceCandidate;!e||e.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():e.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}});var ad=me(so=>{"use strict";var cf=h(_());Object.defineProperty(so,"__esModule",{value:!0});so.adapterFactory=km;var Dm=ut(),ur=bi(Dm),Om=Gc(),Xe=bi(Om),bm=zc(),ai=bi(bm),Pm=td(),Ue=bi(Pm),Mm=nd(),lt=bi(Mm),Lm=od(),Se=bi(Lm);function bi(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e]);return t.default=i,t}function km(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=i.window,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},r=ur.log,n=ur.detectBrowser(t),s={browserDetails:n,commonShim:Se,extractVersion:ur.extractVersion,disableLog:ur.disableLog,disableWarnings:ur.disableWarnings};switch(n.browser){case"chrome":if(!Xe||!Xe.shimPeerConnection||!e.shimChrome)return r("Chrome shim is not included in this adapter release."),s;if(n.version===null)return r("Chrome shim can not determine version, not shimming."),s;r("adapter.js shimming chrome."),s.browserShim=Xe,Se.shimAddIceCandidateNullOrEmpty(t,n),Xe.shimGetUserMedia(t,n),Xe.shimMediaStream(t,n),Xe.shimPeerConnection(t,n),Xe.shimOnTrack(t,n),Xe.shimAddTrackRemoveTrack(t,n),Xe.shimGetSendersWithDtmf(t,n),Xe.shimGetStats(t,n),Xe.shimSenderReceiverGetStats(t,n),Xe.fixNegotiationNeeded(t,n),Se.shimRTCIceCandidate(t,n),Se.shimConnectionState(t,n),Se.shimMaxMessageSize(t,n),Se.shimSendThrowTypeError(t,n),Se.removeExtmapAllowMixed(t,n);break;case"firefox":if(!Ue||!Ue.shimPeerConnection||!e.shimFirefox)return r("Firefox shim is not included in this adapter release."),s;r("adapter.js shimming firefox."),s.browserShim=Ue,Se.shimAddIceCandidateNullOrEmpty(t,n),Ue.shimGetUserMedia(t,n),Ue.shimPeerConnection(t,n),Ue.shimOnTrack(t,n),Ue.shimRemoveStream(t,n),Ue.shimSenderGetStats(t,n),Ue.shimReceiverGetStats(t,n),Ue.shimRTCDataChannel(t,n),Ue.shimAddTransceiver(t,n),Ue.shimGetParameters(t,n),Ue.shimCreateOffer(t,n),Ue.shimCreateAnswer(t,n),Se.shimRTCIceCandidate(t,n),Se.shimConnectionState(t,n),Se.shimMaxMessageSize(t,n),Se.shimSendThrowTypeError(t,n);break;case"edge":if(!ai||!ai.shimPeerConnection||!e.shimEdge)return r("MS edge shim is not included in this adapter release."),s;r("adapter.js shimming edge."),s.browserShim=ai,ai.shimGetUserMedia(t,n),ai.shimGetDisplayMedia(t,n),ai.shimPeerConnection(t,n),ai.shimReplaceTrack(t,n),Se.shimMaxMessageSize(t,n),Se.shimSendThrowTypeError(t,n);break;case"safari":if(!lt||!e.shimSafari)return r("Safari shim is not included in this adapter release."),s;r("adapter.js shimming safari."),s.browserShim=lt,Se.shimAddIceCandidateNullOrEmpty(t,n),lt.shimRTCIceServerUrls(t,n),lt.shimCreateOfferLegacy(t,n),lt.shimCallbacksAPI(t,n),lt.shimLocalStreamsAPI(t,n),lt.shimRemoteStreamsAPI(t,n),lt.shimTrackEventTransceiver(t,n),lt.shimGetUserMedia(t,n),lt.shimAudioContext(t,n),Se.shimRTCIceCandidate(t,n),Se.shimMaxMessageSize(t,n),Se.shimSendThrowTypeError(t,n),Se.removeExtmapAllowMixed(t,n);break;default:r("Unsupported browser!");break}return s}});var _=me(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});var xm=ad(),Um=(0,xm.adapterFactory)({window:typeof window=="undefined"?void 0:window});oo.default=Um});var rt=me((pE,Bo)=>{"use strict";var mE=h(_()),ch=Object.prototype.hasOwnProperty,Me="~";function wr(){}Object.create&&(wr.prototype=Object.create(null),new wr().__proto__||(Me=!1));function dh(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function Kd(i,t,e,r,n){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new dh(e,r||i,n),o=Me?Me+t:t;return i._events[o]?i._events[o].fn?i._events[o]=[i._events[o],s]:i._events[o].push(s):(i._events[o]=s,i._eventsCount++),i}function zn(i,t){--i._eventsCount===0?i._events=new wr:delete i._events[t]}function Oe(){this._events=new wr,this._eventsCount=0}Oe.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)ch.call(e,r)&&t.push(Me?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};Oe.prototype.listeners=function(t){var e=Me?Me+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,o=new Array(s);n<s;n++)o[n]=r[n].fn;return o};Oe.prototype.listenerCount=function(t){var e=Me?Me+t:t,r=this._events[e];return r?r.fn?1:r.length:0};Oe.prototype.emit=function(t,e,r,n,s,o){var a=Me?Me+t:t;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,l;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,n),!0;case 5:return c.fn.call(c.context,e,r,n,s),!0;case 6:return c.fn.call(c.context,e,r,n,s,o),!0}for(l=1,u=new Array(d-1);l<d;l++)u[l-1]=arguments[l];c.fn.apply(c.context,u)}else{var m=c.length,S;for(l=0;l<m;l++)switch(c[l].once&&this.removeListener(t,c[l].fn,void 0,!0),d){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,e);break;case 3:c[l].fn.call(c[l].context,e,r);break;case 4:c[l].fn.call(c[l].context,e,r,n);break;default:if(!u)for(S=1,u=new Array(d-1);S<d;S++)u[S-1]=arguments[S];c[l].fn.apply(c[l].context,u)}}return!0};Oe.prototype.on=function(t,e,r){return Kd(this,t,e,r,!1)};Oe.prototype.once=function(t,e,r){return Kd(this,t,e,r,!0)};Oe.prototype.removeListener=function(t,e,r,n){var s=Me?Me+t:t;if(!this._events[s])return this;if(!e)return zn(this,s),this;var o=this._events[s];if(o.fn)o.fn===e&&(!n||o.once)&&(!r||o.context===r)&&zn(this,s);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||n&&!o[a].once||r&&o[a].context!==r)&&c.push(o[a]);c.length?this._events[s]=c.length===1?c[0]:c:zn(this,s)}return this};Oe.prototype.removeAllListeners=function(t){var e;return t?(e=Me?Me+t:t,this._events[e]&&zn(this,e)):(this._events=new wr,this._eventsCount=0),this};Oe.prototype.off=Oe.prototype.removeListener;Oe.prototype.addListener=Oe.prototype.on;Oe.prefixed=Me;Oe.EventEmitter=Oe;typeof Bo!="undefined"&&(Bo.exports=Oe)});var cc=me((ID,ul)=>{var gD=h(_()),dl=ul.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(i){return i.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(i){return i.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(i){return i.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(i){return i.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(i){return"imageattr:%s %s %s"+(i.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(i){return"simulcast:%s %s"+(i.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(dl).forEach(function(i){var t=dl[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var ml=me(wt=>{var AD=h(_()),ir=function(i){return String(Number(i))===i?Number(i):i},a_=function(i,t,e,r){if(r&&!e)t[r]=ir(i[1]);else for(var n=0;n<e.length;n+=1)i[n+1]!=null&&(t[e[n]]=ir(i[n+1]))},c_=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var n=i.push?{}:r?t[i.name]:t;a_(e.match(i.reg),n,i.names,i.name),i.push&&t[i.push].push(n)},ll=cc(),d_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);wt.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(d_).forEach(function(n){var s=n[0],o=n.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var a=0;a<(ll[s]||[]).length;a+=1){var c=ll[s][a];if(c.reg.test(o))return c_(c,r,o)}}),t.media=e,t};var pl=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=ir(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};wt.parseParams=function(i){return i.split(/;\s?/).reduce(pl,{})};wt.parseFmtpConfig=wt.parseParams;wt.parsePayloads=function(i){return i.toString().split(" ").map(Number)};wt.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(ir),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};wt.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(pl,{})})};wt.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,n=!1;return e[0]!=="~"?r=ir(e):(r=ir(e.substring(1,e.length)),n=!0),{scid:r,paused:n}})})}});var _l=me((CD,hl)=>{var vD=h(_()),dc=cc(),u_=/%[sdv%]/g,l_=function(i){var t=1,e=arguments,r=e.length;return i.replace(u_,function(n){if(t>=r)return n;var s=e[t];switch(t+=1,n){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},nn=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,n=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?n.push(e[t.name][o]):n.push(e[t.names[s]])}else n.push(e[t.name]);return l_.apply(null,n)},p_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],m_=["i","c","b","a"];hl.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||p_,r=t.innerOrder||m_,n=[];return e.forEach(function(s){dc[s].forEach(function(o){o.name in i&&i[o.name]!=null?n.push(nn(s,o,i)):o.push in i&&i[o.push]!=null&&i[o.push].forEach(function(a){n.push(nn(s,o,a))})})}),i.media.forEach(function(s){n.push(nn("m",dc.m[0],s)),r.forEach(function(o){dc[o].forEach(function(a){a.name in s&&s[a.name]!=null?n.push(nn(o,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){n.push(nn(o,a,c))})})})}),n.join(`\r
73
+ `)+`\r
74
+ `}});var fl=me(Bt=>{var ND=h(_()),Ci=ml(),h_=_l();Bt.write=h_;Bt.parse=Ci.parse;Bt.parseParams=Ci.parseParams;Bt.parseFmtpConfig=Ci.parseFmtpConfig;Bt.parsePayloads=Ci.parsePayloads;Bt.parseRemoteCandidates=Ci.parseRemoteCandidates;Bt.parseImageAttributes=Ci.parseImageAttributes;Bt.parseSimulcastStreamList=Ci.parseSimulcastStreamList});var gc=me((Pl,xs)=>{var dP=h(_());(function(i){"use strict";function t(A,U){var v=(A&65535)+(U&65535),J=(A>>16)+(U>>16)+(v>>16);return J<<16|v&65535}function e(A,U){return A<<U|A>>>32-U}function r(A,U,v,J,Z,Te){return t(e(t(t(U,A),t(J,Te)),Z),v)}function n(A,U,v,J,Z,Te,W){return r(U&v|~U&J,A,U,Z,Te,W)}function s(A,U,v,J,Z,Te,W){return r(U&J|v&~J,A,U,Z,Te,W)}function o(A,U,v,J,Z,Te,W){return r(U^v^J,A,U,Z,Te,W)}function a(A,U,v,J,Z,Te,W){return r(v^(U|~J),A,U,Z,Te,W)}function c(A,U){A[U>>5]|=128<<U%32,A[(U+64>>>9<<4)+14]=U;var v,J,Z,Te,W,k=1732584193,g=-271733879,R=-1732584194,L=271733878;for(v=0;v<A.length;v+=16)J=k,Z=g,Te=R,W=L,k=n(k,g,R,L,A[v],7,-680876936),L=n(L,k,g,R,A[v+1],12,-389564586),R=n(R,L,k,g,A[v+2],17,606105819),g=n(g,R,L,k,A[v+3],22,-1044525330),k=n(k,g,R,L,A[v+4],7,-176418897),L=n(L,k,g,R,A[v+5],12,1200080426),R=n(R,L,k,g,A[v+6],17,-1473231341),g=n(g,R,L,k,A[v+7],22,-45705983),k=n(k,g,R,L,A[v+8],7,1770035416),L=n(L,k,g,R,A[v+9],12,-1958414417),R=n(R,L,k,g,A[v+10],17,-42063),g=n(g,R,L,k,A[v+11],22,-1990404162),k=n(k,g,R,L,A[v+12],7,1804603682),L=n(L,k,g,R,A[v+13],12,-40341101),R=n(R,L,k,g,A[v+14],17,-1502002290),g=n(g,R,L,k,A[v+15],22,1236535329),k=s(k,g,R,L,A[v+1],5,-165796510),L=s(L,k,g,R,A[v+6],9,-1069501632),R=s(R,L,k,g,A[v+11],14,643717713),g=s(g,R,L,k,A[v],20,-373897302),k=s(k,g,R,L,A[v+5],5,-701558691),L=s(L,k,g,R,A[v+10],9,38016083),R=s(R,L,k,g,A[v+15],14,-660478335),g=s(g,R,L,k,A[v+4],20,-405537848),k=s(k,g,R,L,A[v+9],5,568446438),L=s(L,k,g,R,A[v+14],9,-1019803690),R=s(R,L,k,g,A[v+3],14,-187363961),g=s(g,R,L,k,A[v+8],20,1163531501),k=s(k,g,R,L,A[v+13],5,-1444681467),L=s(L,k,g,R,A[v+2],9,-51403784),R=s(R,L,k,g,A[v+7],14,1735328473),g=s(g,R,L,k,A[v+12],20,-1926607734),k=o(k,g,R,L,A[v+5],4,-378558),L=o(L,k,g,R,A[v+8],11,-2022574463),R=o(R,L,k,g,A[v+11],16,1839030562),g=o(g,R,L,k,A[v+14],23,-35309556),k=o(k,g,R,L,A[v+1],4,-1530992060),L=o(L,k,g,R,A[v+4],11,1272893353),R=o(R,L,k,g,A[v+7],16,-155497632),g=o(g,R,L,k,A[v+10],23,-1094730640),k=o(k,g,R,L,A[v+13],4,681279174),L=o(L,k,g,R,A[v],11,-358537222),R=o(R,L,k,g,A[v+3],16,-722521979),g=o(g,R,L,k,A[v+6],23,76029189),k=o(k,g,R,L,A[v+9],4,-640364487),L=o(L,k,g,R,A[v+12],11,-421815835),R=o(R,L,k,g,A[v+15],16,530742520),g=o(g,R,L,k,A[v+2],23,-995338651),k=a(k,g,R,L,A[v],6,-198630844),L=a(L,k,g,R,A[v+7],10,1126891415),R=a(R,L,k,g,A[v+14],15,-1416354905),g=a(g,R,L,k,A[v+5],21,-57434055),k=a(k,g,R,L,A[v+12],6,1700485571),L=a(L,k,g,R,A[v+3],10,-1894986606),R=a(R,L,k,g,A[v+10],15,-1051523),g=a(g,R,L,k,A[v+1],21,-2054922799),k=a(k,g,R,L,A[v+8],6,1873313359),L=a(L,k,g,R,A[v+15],10,-30611744),R=a(R,L,k,g,A[v+6],15,-1560198380),g=a(g,R,L,k,A[v+13],21,1309151649),k=a(k,g,R,L,A[v+4],6,-145523070),L=a(L,k,g,R,A[v+11],10,-1120210379),R=a(R,L,k,g,A[v+2],15,718787259),g=a(g,R,L,k,A[v+9],21,-343485551),k=t(k,J),g=t(g,Z),R=t(R,Te),L=t(L,W);return[k,g,R,L]}function d(A){var U,v="",J=A.length*32;for(U=0;U<J;U+=8)v+=String.fromCharCode(A[U>>5]>>>U%32&255);return v}function u(A){var U,v=[];for(v[(A.length>>2)-1]=void 0,U=0;U<v.length;U+=1)v[U]=0;var J=A.length*8;for(U=0;U<J;U+=8)v[U>>5]|=(A.charCodeAt(U/8)&255)<<U%32;return v}function l(A){return d(c(u(A),A.length*8))}function m(A,U){var v,J=u(A),Z=[],Te=[],W;for(Z[15]=Te[15]=void 0,J.length>16&&(J=c(J,A.length*8)),v=0;v<16;v+=1)Z[v]=J[v]^909522486,Te[v]=J[v]^1549556828;return W=c(Z.concat(u(U)),512+U.length*8),d(c(Te.concat(W),512+128))}function S(A){var U="0123456789abcdef",v="",J,Z;for(Z=0;Z<A.length;Z+=1)J=A.charCodeAt(Z),v+=U.charAt(J>>>4&15)+U.charAt(J&15);return v}function E(A){return unescape(encodeURIComponent(A))}function y(A){return l(E(A))}function B(A){return S(y(A))}function x(A,U){return m(E(A),E(U))}function F(A,U){return S(x(A,U))}function Ee(A,U,v){return U?v?x(U,A):F(U,A):v?y(A):B(A)}typeof define=="function"&&define.amd?define(function(){return Ee}):typeof xs=="object"&&xs.exports?xs.exports=Ee:i.md5=Ee})(Pl)});var bL=h(_());var uN=h(_());var kE=h(_(),1);var hf=h(_(),1),Pi="4.15.00.1600",Ve="5.0.0";function cd(i){Ve=i;let[t,e,r]=i.split(".").map(n=>parseInt(n,10));Pi=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var Rn=typeof importScripts!="undefined",An=typeof registerProcessor!="undefined";var Cn="",dd=i=>Cn=i,ao="web.sdk.qcloud.com",ud="web.sdk.tencent.cn",ld="web.sdk.cloud.tencent.cn",vn="https://console.cloud.tencent.com/trtc",Mi=`https://${ao}/trtc/webrtc/doc`,Li=`${Mi}/zh-cn/`,pd="https://yun.tim.qq.com",md="https://videoapi-sgp.im.qcloud.com",hd="trtc_error_assistance",ki={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport"},Wt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},pt=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(pt||{});var ci={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5},co=7*24*3600*1e3;var uo={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:192},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},xi={"120p":{width:160,height:120,frameRate:15,bitrate:200},"180p":{width:320,height:180,frameRate:15,bitrate:350},"240p":{width:320,height:240,frameRate:15,bitrate:400},"360p":{width:640,height:360,frameRate:15,bitrate:800},"480p":{width:640,height:480,frameRate:15,bitrate:900},"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}},lo={"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}},f={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",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"},he={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},po={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"};var lr=1,_d=2,yn=4,pr=8,mo=64,ho=16,Nn="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",fd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Ed=f.MAIN,Dn=f.AUXILIARY;var mr="unknown",De={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Td=1/0;function Sd(i){Td=i}function hr(){return Td}var On=30,di={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"};var Id=1e4,gd=1e4,ui="unified-plan",_r="plan-b",li={MODE:{MANUAL:"manual",PRESET_LAYOUT:"preset-layout"},PLACE_HOLDER:{REMOTE:"$PLACE_HOLDER_REMOTE$"},STREAM_TYPE:{IT_AUDIO_VIDEO:0,IT_PICTURE:2,IT_CANVAS:3,IT_PURE_AUDIO:4,IT_PURE_VIDEO:5}},b={String:"string",Number:"number",Boolean:"boolean",Array:"array",Object:"object"},bn=1028;var _o=500;var uf=f.BIG,lf=f.SMALL,Rd=10*1e3,fr={MAIN:"schedule.rtc.qq.com",BACKUP:"schedule.rtc.qcloud.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA:"schedule-ecdn.rtc.tencentcloud.com"};var Ad=5,Ui="default",Pn=Ui;var pf=Object.keys(pt),Cd=["normal leave","timeout leave","kick","role change"],Er=10,Tr=2e3,vt="ric",Kt="raf",vd="interval",Sr="timeout";var OE=h(_(),1);var Ef=h(_(),1);var yd=new Date().getTime(),fo=0,Nd=function(i){yd=i,fo=yd-new Date().getTime();let t=new Date;t.setTime(i),P.info(`baseTime from server: ${t} offset: ${fo}`)},Ir=function(){return new Date().getTime()+fo},Mn=function(){let i=new Date;return i.setTime(Ir()),i.toLocaleString()};var Fe={};js(Fe,{bytes2ms:()=>Xm,catchEmitterError:()=>wo,copyProperties:()=>Ym,deepMerge:()=>Et,fibonacci:()=>wi,formatedTime:()=>nh,getAudioContext:()=>Pt,getConstructorName:()=>Xn,getContainerFromElement:()=>qn,getEnv:()=>jm,getGainAudioContext:()=>Qm,getInternalVersion:()=>Zm,getLoggerUrl:()=>hi,getMuteStateFromFlag:()=>Bi,getNetworkQuality:()=>th,getNetworkType:()=>Jn,getOSType:()=>$d,getReconnectionTimeout:()=>ft,getSysInfo:()=>Jm,getTerminalType:()=>Bd,getTurnServer:()=>ih,getValueType:()=>_e,glog:()=>Gd,ipv4ToUint32:()=>Vr,isArray:()=>Xt,isArrayOrObject:()=>kr,isAudioWorkletSupported:()=>Uo,isBoolean:()=>bt,isConstructor:()=>xr,isEmpty:()=>Ur,isFunction:()=>oe,isLangChinese:()=>_t,isMediaStreamTrack:()=>zm,isNumber:()=>ce,isObject:()=>_i,isOverseaSdkAppId:()=>jn,isPlainObject:()=>Yt,isPromise:()=>Yn,isRemoteTrack:()=>qt,isString:()=>re,isUndefined:()=>N,ms2bytes:()=>qm,ms2samples:()=>Fd,performanceNow:()=>ee,promiseAny:()=>Vo,samples2ms:()=>Hd,tryCatchFunction:()=>xo});var zf=h(_(),1);var Of=h(_(),1);var mt=typeof navigator!="undefined"?navigator==null?void 0:navigator.userAgent:"",Q=i=>new RegExp(i,"i").test(mt),Ie=i=>{if(Q(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=mt.match(t);if(e&&e[1])return e[1]}return""},Eo=i=>{if(Q(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=mt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},Dd=/AppleWebKit\/([\d.]+)/i.exec(mt),Vm=Dd?parseFloat(Dd[1]):NaN,Rr=Q("iPad"),Od=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Q("Macintosh"),pi=Q("iPhone")&&!Rr,wm=Q("iPod"),qe=pi||Rr||wm||Od,it=Q("Android"),bd=function(){if(it){let i=mt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),If=it&&Q("webkit")&&bd<2.3,gf=it&&bd<5&&Vm<537,we=Q("Firefox"),To=Ie("Firefox"),Pd=Eo("Firefox"),Ar=Q("Edge"),So=Ie("Edge"),Cr=Q("Edg"),Io=Ie("Edg"),Md=Eo("Edg"),Ln=Q("SogouMobileBrowser"),go=Ie("SogouMobileBrowser"),kn=Q("MetaSr\\s"),Ro=Ie("MetaSr\\s"),yt=Q("TBS"),Ao=Ie("TBS"),xn=Q("XWEB"),Co=Ie("XWEB"),Rf=Q("MSIE\\s8\\.0"),Bm=Q("MSIE\\/\\d+"),Af=function(){if(Bm){let i=/MSIE\s(\d+)\.\d/.exec(mt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(mt)&&/rv:11.0/.test(mt)&&(t=11),t}return NaN}(),vr=Q("(micromessenger|webbrowser)"),vo=Ie("MicroMessenger"),yr=!yt&&Q("MQQBrowser")&&Q("COVC"),Nr=!yt&&Q("MQQBrowser")&&!Q("COVC"),gr=Nr||yr?Ie("MQQBrowser"):"",Un=!yt&&Q(" QQBrowser"),yo=Ie(" QQBrowser"),Vn=!yt&&Q("QQBrowserLite"),No=Ie("QQBrowserLite"),wn=!yt&&Q("MQBHD"),Do=Ie("MQBHD"),Dr=Q("Windows"),Nt=!qe&&Q("MAC OS X"),Or=!it&&Q("Linux"),Cf=Q("MicroMessenger"),Ld=Q("UCBrowser"),vf=Q("Electron"),Bn=Q("MiuiBrowser"),Oo=Ie("MiuiBrowser"),$n=Q("HuaweiBrowser"),yf=Q("Huawei"),bo=Ie("HuaweiBrowser"),Hn=Q("SamsungBrowser"),Po=Ie("SamsungBrowser"),Fn=Q("HeyTapBrowser"),Mo=Ie("HeyTapBrowser"),Gn=Q("VivoBrowser"),Lo=Ie("VivoBrowser"),br=()=>Eo("Chrome"),kd=Q("Chrome"),Pr=!Ar&&!kn&&!Ln&&!yt&&!xn&&!Cr&&!Un&&!Bn&&!$n&&!Hn&&!Fn&&!Gn&&kd,Mr=br(),ko=Ie("Chrome"),ht=!kd&&!Nr&&!yr&&!Vn&&!wn&&Q("Safari");var Lr=Ie("Safari"),Nf=/Android.*(wv|.0.0.0)/.test(mt),jt=(()=>{if(Od)return Lr;if(qe){let i=mt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})(),xd=Lr==="15.1",Wn=jt==="15.1",Df=(()=>{let i=Number(jt.split(".")[0]);return i===14||i===13})(),Vi=typeof location!="undefined"?location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1":!1,Jt=(()=>{let i;return()=>{if(N(i))try{i=!!window.localStorage}catch(t){P.warn(t),i=!1}return i}})(),Dt=$m();function $m(){let i=new Map([[we,["Firefox",To]],[Cr,["Edg",Io]],[Pr,["Chrome",ko]],[ht,["Safari",Lr]],[yt,["TBS",Ao]],[xn,["XWEB",Co]],[vr&&pi,["WeChat",vo]],[Un,["QQ(Win)",yo]],[Nr,["QQ(Mobile)",gr]],[yr,["QQ(Mobile X5)",gr]],[Vn,["QQ(Mac)",No]],[wn,["QQ(iPad)",Do]],[Bn,["MI",Oo]],[$n,["HW",bo]],[Hn,["Samsung",Po]],[Fn,["OPPO",Mo]],[Gn,["VIVO",Lo]],[Ar,["EDGE",So]],[Ln,["SogouMobile",go]],[kn,["Sogou",Ro]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Wf=h(_(),1);var xf=h(_(),1);var Pf=h(_(),1);var mi=1e8;var $={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",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_EMPTY:"SEI_EMPTY",SEI_OVERSIZE:"SEI_OVERSIZE",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"},Be={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${_e(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${_e(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(i){return`exchange sdp failed ${i.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:`no permission to publish() under live/${"audience"}, please call switchRole("${"anchor"}") firstly before publish().`,INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:`role could only be set to a value as ${"anchor"} or ${"audience"}.`,INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed\uFF0Cbrowser exception: ${i.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(i){return`${i}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone and the configuration on TRTC.createStream.",CAMERA_NOT_FOUND:"no camera detected, please check your camera and the configuration on TRTC.createStream.",SIGNAL_RESPONSE_FAILED(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught on ${i}.on('${t}', handler), please check your code on 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>`[${i}] is calling client.join api or has already joined room, please avoid repeated join.`,CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled, to enable SEI: TRTC.createClient({ enableSEI: true })",SEI_EMPTY:"buffer cannot be empty",SEI_OVERSIZE:i=>`buffer size(${i}) is over 1000 Bytes`,SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.message}`,t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var Uf=h(_());function Ud(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Hm={AVOID_REPEATED_CALL(i){return`\u524D\u4E00\u4E2A ${i.name}() \u8C03\u7528\u6B63\u5728\u8FDB\u884C\u4E2D, \u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${i||t.name}' \u662F\u5FC5\u987B\u7684\u53C2\u6570, \u6536\u5230\u7684\u503C\u4E3A: ${r}\u3002`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`\u8C03\u7528 ${e}() \u65B9\u6CD5\u7684\u65F6\u5019 '${n}' \u5FC5\u987B\u662F ${s} \u7C7B\u578B, \u6536\u5230\u7684\u7C7B\u578B\u662F: ${Ud(r)}\u3002`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u4E0D\u80FD\u662F '${r}'\u3002`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${n}' \u539F\u578B\u5FC5\u987B\u662F ${s} , \u6536\u5230\u7684\u662F: ${Ud(r)}\u3002`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`\u8C03\u7528 ${e}() \u7684\u65F6\u5019 '${i||t.name}' \u5FC5\u987B\u662F ${t.values.join("|")} \u7684\u5176\u4E2D\u4E00\u79CD, \u6536\u5230\u7684\u662F: ${r}\u3002`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} \u8D85\u65F6\u3002`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"\u4FE1\u4EE4\u901A\u9053\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4F60\u7684\u7F51\u7EDC\u3002",SIGNAL_CHANNEL_SETUP_FAILED(i){return`\u4FE1\u4EE4\u901A\u9053\u5EFA\u7ACB\u5931\u8D25: (\u9519\u8BEF\u7801: ${i.errorCode}, \u9519\u8BEF\u4FE1\u606F: ${i.errorMsg} })\u3002`},ERROR_MESSAGE(i){let t=`${i.type} \u5931\u8D25\u3002`;return i.message&&(t=`${t}: ${i.message}\u3002`),t},SUBSCRIPTION_TIMEOUT:"\u8FDC\u7A0B\u670D\u52A1\u5668\u4E0D\u54CD\u5E94\u8BA2\u9605\u884C\u4E3A\u3002",EXCHANGE_SDP_TIMEOUT:"\u4EA4\u6362 sdp \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",DOWNLINK_RECONNECTION_FAILED:"\u4E0B\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u52A0\u5165\u623F\u95F4\u3002",EXCHANGE_SDP_FAILED(i){return`\u4EA4\u6362 SDP \u5931\u8D25\uFF0C\u539F\u56E0 ${i.errMsg}\u3002`},REPLACE_TRACK_INVALID:"LocalStream \u53D1\u5E03\u4E4B\u540E\u624D\u53EF\u4EE5\u8C03\u7528 replaceTrack\u3002",UPDATE_OFFER_TIMEOUT:"\u66F4\u65B0 offer \u8D85\u65F6\uFF0C\u8BF7\u5237\u65B0\u7F51\u7EDC\u91CD\u8BD5\u3002",UPLINK_RECONNECTION_FAILED:"\u4E0A\u884C\u91CD\u8FDE\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u7F51\u7EDC\u5E76\u91CD\u65B0\u63A8\u6D41\u3002",INVALID_RECORDID:"recordId \u5FC5\u987B\u662F\u6570\u5B57\u3002",INVALID_PURE_AUDIO:"pureAudioPushMode \u5FC5\u987B\u662F\u6570\u5B571\u62162\u3002",INVALID_STREAMID:"streamId \u5FC5\u987B\u662F 64 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId \u5FC5\u987B\u662F\u5305\u542B (a-zA-Z)\u3001(0-9)\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\u7684\u5B57\u7B26\u4E32\u5B57\u9762\u91CF\uFF0C64 \u4E2A\u5B57\u8282\u4EE5\u5185\uFF0C\u4E14\u4E0D\u4E3A\u7A7A\u3002",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs \u5FC5\u987B\u662F 256 \u5B57\u8282\u4EE5\u5185\u7684\u5B57\u7B26\u4E32\u6587\u5B57\uFF0C\u5E76\u4E14\u4E0D\u80FD\u4E3A\u7A7A\u3002",INVALID_PROXY:"\u4EE3\u7406\u670D\u52A1\u5668 url \u5FC5\u987B\u4EE5\u201Cwss://\u201D\u5F00\u5934\u3002",INVALID_JOIN:"join() \u65B9\u6CD5\u4E0D\u80FD\u88AB\u91CD\u590D\u8C03\u7528\u3002",INVALID_ROOMID_STRING(i){return`\u5F53 useStringRoomId \u4E3A true \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u5B57\u7B26\u4E32\u3002`},INVALID_ROOMID_INTEGER(i){return`\u5F53 useStringRoomId \u4E3A false \u65F6\uFF0C'${i}' \u5FC5\u987B\u662F\u5408\u6CD5\u6574\u6570\u5728\u533A\u95F4[1, 4294967294]\u3002`},INVALID_SIGNAL_CHANNEL:"SignalChannel \u8FD8\u672A\u521D\u59CB\u5316\u597D\u3002",JOIN_ROOM_TIMEOUT:"\u8FDB\u623F\u8D85\u65F6\u3002",JOIN_ROOM_FAILED(i){return`\u8FDB\u623F\u5931\u8D25\uFF0C\u539F\u56E0\uFF1A${i.error}\u3002`},REJOIN_ROOM_FAILED(i){return`\u91CD\u8FDB\u623F: ${i.roomId} \u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u72B6\u51B5\u3002`},INVALID_LEAVE:"\u8BF7\u5728\u8C03\u7528 destroy() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 leave()\u3002",INVALID_PUBLISH:"\u8BF7\u5728\u8C03\u7528 publish() \u65B9\u6CD5\u4E4B\u524D\u8C03\u7528 join()\u3002",INVALID_UNPUBLISH:"\u8FD8\u6CA1\u6709\u88AB publish\u3002",INVALID_AUDIENCE:"\u5728\u89C2\u4F17\u6A21\u5F0F\u4E0B\u4E0D\u5141\u8BB8\u8C03\u7528 publish()\uFF0C\u8BF7\u5148\u5207\u6362\u6210\u4E3B\u64AD\u6A21\u5F0F\u3002",INVALID_INITIALIZE:"\u65E0\u6CD5\u53D1\u5E03 stream\uFF0C\u539F\u56E0\uFF1AlocalStream \u672A\u521D\u59CB\u5316\u3001\u6B63\u5728\u5207\u6362\u8BBE\u5907\u3001\u5DF2\u7ECF\u8C03\u7528 localStream.close() \u5173\u95ED\u91C7\u96C6",INVALID_DUPLICATE_PUBLISHING:"\u91CD\u590D\u53D1\u5E03\uFF0C\u8BF7\u5148 unpublish \u4E4B\u540E\uFF0C\u518D\u91CD\u65B0 publish\u3002",INVALID_SUBSCRIBE_UNDEFINED:"stream \u53C2\u6570\u662F undefined \u6216\u8005 null\u3002",INVALID_SUBSCRIBE_LOCAL:"stream \u53C2\u6570\u4E0D\u80FD\u4E3A\u672C\u5730\u6D41\u3002",INVALID_REMOTE_STREAM:"remoteStream \u4E0D\u5B58\u5728\uFF0C\u5DF2\u88AB\u8FDC\u7AEF client \u53D6\u6D88\u53D1\u5E03\u3002",SUBSCRIBE_FAILED(i){let t="\u8BA2\u9605\u6D41\u5931\u8D25\uFF0C\u539F\u56E0: ";return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t+="\u8FDC\u7AEF\u7528\u6237\u5DF2\u53D6\u6D88\u63A8\u6D41\uFF0C\u65E0\u6CD5\u8BA2\u9605\u8BE5\u8FDC\u7AEF\u6D41\u3002":t+=`${i.message}\u3002`,t},INVALID_ROLE:"\u53EA\u6709\u76F4\u64AD\u6A21\u5F0F\u624D\u53EF\u4EE5\u8FDB\u884C\u89D2\u8272\u5207\u6362\u3002",INVALID_PARAMETER_SWITCH_ROLE:"role \u53EA\u80FD\u8BBE\u7F6E\u4E3A anchor \u6216\u8005 audience\u3002",INVALID_OPERATION_SWITCH_ROLE:"\u8BF7\u5728\u4F7F\u7528 switchRole() \u65B9\u6CD5\u524D\u5148\u8FDB\u623F\u3002",SWITCH_ROLE_TIMEOUT:"\u5207\u6362\u89D2\u8272\u8D85\u65F6\u3002",SWITCH_ROLE_FAILED(i){return`\u5207\u6362\u89D2\u8272\u5931\u8D25\u3002\u9519\u8BEF\u7801: ${i.code} \u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},CLIENT_BANNED(i){return`\u60A8\u88AB\u52A8\u9000\u623F\u4E86\uFF0C\u539F\u56E0\u4E3A\uFF1A${i.reason}\u3002`},INVALID_OPERATION_START_PUBLISH_CDN:"\u8BF7\u5728\u8FDB\u623F\u524D\u6216\u8005\u8FDB\u623F\u5E76\u6210\u529F\u53D1\u5E03\u672C\u5730\u6D41\u540E\u8C03\u7528 startPublishCDNStream() \u65B9\u6CD5\u3002",INVALID_OPERATION_STOP_PUBLISH_CDN:"\u5728\u8C03\u7528 stopPublishCDNStream() \u65B9\u6CD5\u524D\u9700\u8981\u5148 startPublishCDNStream()\u3002",INVALID_STREAM_ID(i){return`'${i}' \u53EA\u80FD\u7531\u5927\u5C0F\u5199\u5B57\u6BCD\uFF08a-zA-z\uFF09, \u6570\u5B57\uFF080-9\uFF09, \u8FDE\u5B57\u7B26\u548C\u4E0B\u5212\u7EBF\u7EC4\u6210`},START_PUBLISH_CDN_FAILED(i){return`startPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},START_MIX_TRANSCODE:"\u8C03\u7528 startMixTranscode() \u65B9\u6CD5\u524D\u9700\u8981\u5148\u8C03\u7528 join()\u3002",STOP_MIX_TRANSCODE:"\u8C03\u7528 stopMixTranscode \u4E4B\u524D\u9700\u8981\u8C03\u7528 startMixTranscode\u3002",INVALID_AUDIO_VOLUME:"interval \u5FC5\u987B\u662F\u6570\u5B57\u3002",ENABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5F00\u542F\u5C0F\u6D41\u3002",DISABLE_SMALL_STREAM_PUBLISHED:"\u53D1\u5E03 localStream \u4E4B\u540E\u4E0D\u5141\u8BB8\u5173\u95ED\u5C0F\u6D41\u3002",NOT_SUPPORTED_SMALL_STREAM:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5F00\u542F\u5C0F\u6D41\u3002",INVALID_SMALL_STREAM_PROFILE:"\u5C0F\u6D41\u53C2\u6570\u4E0D\u5408\u6CD5\u3002",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream \u4E0D\u5408\u6CD5\u3002",REMOTE_NOT_PUBLISH_SMALL_STREAM:"\u8FDC\u7AEF\u7528\u6237\u6CA1\u6709\u53D1\u5E03\u5C0F\u6D41\u3002",INVALID_SWITCH_DEVICE:"\u5F53\u524D\u7684\u6D41\u4E0D\u53EF\u4EE5\u8C03\u7528 switchDevice\u3002",INVALID_SWITCH_DEVICE_PUBLISHING:"\u53D1\u5E03\u672C\u5730\u6D41\u65F6\u4E0D\u80FD\u5207\u6362\u8BBE\u5907\u3002",INVALID_REPLACE_TRACK:"client.publish \u63A5\u53E3\u5C1A\u672A\u8C03\u7528\u5B8C\u6210\uFF0C\u8BF7\u7B49\u5176\u8C03\u7528\u5B8C\u6210\u540E\u518D\u8C03\u7528 replaceTrack \u63A5\u53E3\u3002",INVALID_INITIALIZE_LOCAL_STREAM:"\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_REPETITIVE:"\u524D\u4E00\u4E2A addTrack \u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u8C03\u7528\u3002",INVALID_ADD_TRACK_REMOVING:"track \u5728\u79FB\u52A8\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_ADD_TRACK_PUBLISHING:"\u5728\u53D1\u5E03\u672C\u5730\u6D41\u7684\u65F6\u5019\u4E0D\u80FD\u6DFB\u52A0\u65B0\u7684 track\u3002",INVALID_STREAM_INITIALIZED:"\u60A8\u7684\u672C\u5730\u6D41\u8FD8\u6CA1\u6709\u521D\u59CB\u5316\u3002",INVALID_ADD_TRACK_NUMBER:"\u4E00\u6761\u6D41\u6700\u591A\u6709\u4E00\u4E2A\u97F3\u9891\u8F68\u9053\u548C\u4E00\u4E2A\u89C6\u9891\u8F68\u9053\u3002",INVALID_REMOVE_AUDIO_TRACK:"remove audio track \u662F\u4E0D\u5141\u8BB8\u7684\u3002",INVALID_REMOVE_AUDIO_ADDING:"\u5F53\u4E00\u4E2A track \u88AB addTrack \u7684\u65F6\u5019\u4E0D\u80FD\u5BF9\u6D41\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_AUDIO_ON:"\u524D\u4E00\u6B21\u8C03\u7528\u7684 removeTrack \u6B63\u5728\u8FDB\u884C\u4E2D\uFF0C\u8BF7\u907F\u514D\u91CD\u590D\u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_PUBLISHING:"\u53D1\u5E03\u6D41\u7684\u8FC7\u7A0B\u4E2D\u4E0D\u80FD\u8FDB\u884C removeTrack \u64CD\u4F5C\u3002",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"\u88AB remove \u7684 track \u6CA1\u6709\u88AB\u53D1\u5E03\u3002",INVALID_REMOVE_TRACK_NUMBER:"\u4E0D\u652F\u6301\u79FB\u9664\u552F\u4E00\u7684\u89C6\u9891\u8F68\u9053\uFF0C\u8BF7\u4F7F\u7528 replaceTrack \u6216\u8005 muteVideo \u65B9\u6CD5\u3002",INVALID_REPLACE_TRACK_NO_TRACK(i){return`LocalStream \u6CA1\u6709 ${i.kind} track\uFF0C\u65E0\u6CD5\u8FDB\u884C\u66FF\u6362\u3002`},START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode \u8C03\u7528\u5931\u8D25\uFF0C\u9519\u8BEF\u4FE1\u606F: ${i.message}\u3002`},MIX_TRANSCODE_NOT_STARTED:"\u8FD8\u6CA1\u6709\u5F00\u59CB mixTranscode\u3002",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'\u5F53\u8C03\u7528 ${e}() \u51FD\u6570\u65F6\uFF0C\u8981\u6C42\u53C2\u6570 ${i||t.name}' \u5FC5\u987B\u5927\u4E8E\u7B49\u4E8E0`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' \u5E94\u8BE5\u662F (0, 30] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' \u5E94\u8BE5\u662F [1, 8] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' \u5E94\u8BE5\u662F [32, 192] \u533A\u95F4\u5185\u7684\u6574\u6570\u3002",MIX_PARAMS_USER_Z_ORDER(i){return`'${i}' \u662F\u5FC5\u4F20\u7684\uFF0C\u4E14\u8981\u6C42\u4E3A [1 ,15] \u4E4B\u95F4\u7684\u6574\u6570\u3002`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' \u5FC5\u987B\u5305\u542B\u53D1\u8D77\u6DF7\u6D41\u7684\u7528\u6237\u4FE1\u606F\u3002",MIX_PARAMS_USER_STREAM:"\u8F93\u51FA\u6D41\u7684 'config.videoWidth' \u548C 'config.videoHeight' \u5E94\u8BE5\u5BB9\u7EB3\u6240\u6709\u6DF7\u5165\u6D41\u3002",INVALID_PLAY:"play() \u88AB\u91CD\u590D\u8C03\u7528\uFF0C\u8BF7\u5148 stop()\uFF0C\u7136\u540E\u518D\u91CD\u65B0\u8C03\u7528 play\u3002",INVALID_ELEMENT_ID:({key:i,fnName:t})=>`\u5728\u8C03\u7528 ${t}() \u65F6\uFF0Cdocument \u5BF9\u8C61\u4E2D\u627E\u4E0D\u5230 ${i} \u5BF9\u5E94\u7684\u5143\u7D20\uFF0C\u8BF7\u68C0\u67E5\u3002`,INVALID_ELEMENT_ID_TYPE:({key:i,type:t,fnName:e})=>`\u5728\u8C03\u7528 ${e}() \u65B9\u6CD5\u65F6\uFF0C${i} \u53C2\u6570\u5BF9\u5E94\u7684 HTML \u6807\u7B7E\u5143\u7D20\u5FC5\u987B\u662F HTMLElement \u5B9E\u4F8B\uFF0C\u60A8\u4F20\u5165\u7684\u662F\uFF1A${t}\u3002`,PLAY_FAILED:i=>`${i.media} \u64AD\u653E\u88AB\u4E2D\u65AD\uFF0C\u6D4F\u89C8\u5668\u5F02\u5E38\u539F\u56E0\uFF1A${i.error.toString()}`,INVALID_USERID:"userId \u4E0D\u80FD\u4E3A\u7A7A\u683C\u3002",INVALID_CREATE_STREAM_SOURCE:"createStream() \u751F\u6210 LocalStream \u53EF\u4EE5\u4F7F\u7528 audio & video \u6216 audioSource & videoSource \u521B\u5EFA\uFF0C\u4F46\u4E0D\u80FD\u6DF7\u5408\u4F7F\u7528\u3002",INVALID_CREATE_STREAM_SCREEN:"screen \u548C video \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_AUDIO:"audio \u548C screenAudio \u4E0D\u80FD\u540C\u65F6\u4E3A true\u3002",INVALID_CREATE_STREAM_SCREEN_AUDIO:"screen \u4E3A true \u65F6\uFF0C\u4E0D\u80FD\u8BBE\u7F6E screenAudio\u3002",NOT_SUPPORTED_HTTP:"\u7531\u4E8E\u6D4F\u89C8\u5668\u5B89\u5168\u7B56\u7565\u9650\u5236\uFF0C\u4E0D\u652F\u6301\u5728 http \u534F\u8BAE\u4E0B\u4F7F\u7528\u91C7\u96C6\u3001\u63A8\u6D41\u7B49\u80FD\u529B\uFF0C\u8BF7\u4F7F\u7528 https \u534F\u8BAE\u3002",NOT_SUPPORTED_WEBRTC:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u5B8C\u5168\u652F\u6301 WebRTC \u80FD\u529B\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_PROFILE:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 setVideoProfile \u65B9\u6CD5\u3002\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_MEDIA:"\u5F53\u524D\u6D4F\u89C8\u5668\u6216\u73AF\u5883\u4E0D\u652F\u6301 navigator.mediaDevices\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_H264ENCODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u7F16\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u63A8\u6D41\u3002",NOT_SUPPORTED_H264DECODE:"\u5F53\u524D\u7684\u8BBE\u5907\u6216\u73AF\u5883\u4E0D\u652F\u6301 H264 \u89E3\u7801\uFF0C\u4E0D\u652F\u6301 H264 \u683C\u5F0F\u8FDB\u884C\u62C9\u6D41\u3002",NOT_SUPPORTED_TRACK(i){return`\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 ${i}Track \u65B9\u6CD5\u3002`},NOT_SUPPORTED_REPLACE_TRACK:"\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301 replaceTrack \u65B9\u6CD5\uFF0C\u8BF7\u4F7F\u7528 switchDevice \u6216\u8005 addTrack\u3002",NOT_SUPPORTED_CAPTURE:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5C4F\u5E55\u5206\u4EAB\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u548C\u9875\u9762\u8BBF\u95EE\u534F\u8BAE\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\u3002",NOT_SUPPORTED_AUX:"\u60A8\u5F53\u524D\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u63A8\u8F85\u6D41\uFF0C\u8BF7\u68C0\u67E5\u6D4F\u89C8\u5668\u7248\u672C\u662F\u5426\u6EE1\u8DB3\u6761\u4EF6\uFF08Chrome 69+, Safari 11+, Firefox 59+\uFF09\u3002",MICROPHONE_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u9EA6\u514B\u98CE\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u9EA6\u514B\u98CE\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CAMERA_NOT_FOUND:"\u672A\u68C0\u6D4B\u5230\u6444\u50CF\u5934\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684\u6444\u50CF\u5934\u548C TRTC.createStream \u4E0A\u7684\u914D\u7F6E\u3002",CATCH_HANDLER_ERROR:({name:i,event:t})=>` \u5728 ${i}.on('${t}', handler) \u4E8B\u4EF6\u4E2D\u6355\u83B7\u5230\u4E1A\u52A1\u4FA7\u9519\u8BEF\uFF0C\u8BF7\u6839\u636E\u4E0B\u8FF0\u9519\u8BEF\u4FE1\u606F\uFF0C\u68C0\u67E5\u60A8\u5728 handler \u4E2D\u7684\u4E1A\u52A1\u4EE3\u7801\u3002`,REPEAT_JOIN:i=>`\u7528\u6237 [${i}] \u6B63\u5728\u8C03\u7528\u8FDB\u623F\u63A5\u53E3\u6216\u8005\u5DF2\u7ECF\u5728\u623F\u95F4\u5185\uFF0C\u8BF7\u52FF\u91CD\u590D\u521B\u5EFA\u76F8\u540C userId \u7684 client \u8FDB\u5165\u540C\u4E00\u4E2A\u623F\u95F4\u3002`,CLIENT_DESTROYED:({funName:i})=>`client \u5DF2\u7ECF\u88AB\u9500\u6BC1\uFF0C\u8C03\u7528 ${i}() \u65B9\u6CD5\u5931\u8D25\u3002`,API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`\u4E2D\u65AD\u8BA2\u9605\u7528\u6237 ${i.userId} \u7684 ${i.streamType} stream, \u539F\u56E0: \u5728\u60A8\u8BA2\u9605\u8FC7\u7A0B\u4E2D\uFF0C\u8FDC\u7AEF\u7528\u6237 ${i.userId} \u53D6\u6D88\u4E86\u63A8\u6D41\uFF0C\u60A8\u53EF\u4EE5\u5728\u4E0B\u6B21\u8FDC\u7AEF\u63A8\u6D41\u65F6\u518D\u8FDB\u884C\u8BA2\u9605\u3002`:t=`\u4E2D\u65AD\u63A5\u53E3\u8C03\u7528, \u539F\u56E0: ${i.message}\u3002`,t},SEI_BEFORE_PUBLISH:"\u5F53\u524D client \u6CA1\u6709\u63A8 localStream(\u4E3B\u6D41\uFF0C\u975E\u5C4F\u5E55\u5206\u4EAB\u6D41)\uFF0C\u65E0\u6CD5\u8C03\u7528 client.sendSEIMessage() \u63A5\u53E3\u3002"},Fm={INVALID_USER_DEFINE_RECORDID:"TRTC.html#createClient",INVALID_PROXY:"Client.html#setProxyServer",INVALID_JOIN:"Client.html#join",INVALID_ROOMID_STRING:"Client.html#join",INVALID_ROOMID_INTEGER:"Client.html#join",INVALID_PUBLISH:"Client.html#publish",INVALID_UNPUBLISH:"Client.html#unpublish",INVALID_AUDIENCE:"Client.html#switchRole",INVALID_INITIALIZE:"Client.html#publish",INVALID_DUPLICATE_PUBLISHING:"Client.html#publish",INVALID_SUBSCRIBE_UNDEFINED:"Client.html#subscribe",INVALID_SUBSCRIBE_LOCAL:"Client.html#subscribe",INVALID_REMOTE_STREAM:"Client.html#subscribe",INVALID_ROLE:"Client.html#switchRole",INVALID_PARAMETER_SWITCH_ROLE:"Client.html#switchRole",INVALID_OPERATION_SWITCH_ROLE:"Client.html#switchRole",CLIENT_BANNED:"module-ClientEvent.html#.CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"Client.html#startPublishCDNStream",INVALID_OPERATION_STOP_PUBLISH_CDN:"Client.html#stopPublishCDNStream",START_MIX_TRANSCODE:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE:"Client.html#stopMixTranscode",INVALID_AUDIO_VOLUME:"Client.html#enableAudioVolumeEvaluation",ENABLE_SMALL_STREAM_PUBLISHED:"Client.html#enableSmallStream",DISABLE_SMALL_STREAM_PUBLISHED:"Client.html#disableSmallStream",NOT_SUPPORTED_SMALL_STREAM:"tutorial-27-advanced-small-stream.html#h2-4",INVALID_SMALL_STREAM_PROFILE:"Client.html#setSmallStreamProfile",REMOTE_NOT_PUBLISH_SMALL_STREAM:"Client.html#setRemoteVideoStreamType",INVALID_SWITCH_DEVICE:"LocalStream.html#switchDevice",INVALID_SWITCH_DEVICE_PUBLISHING:"LocalStream.html#switchDevice",INVALID_REPLACE_TRACK:"LocalStream.html#replaceTrack",INVALID_INITIALIZE_LOCAL_STREAM:"LocalStream.html#replaceTrack",INVALID_ADD_TRACK_REPETITIVE:"LocalStream.html#addTrack",INVALID_ADD_TRACK_REMOVING:"LocalStream.html#addTrack",INVALID_ADD_TRACK_PUBLISHING:"LocalStream.html#addTrack",INVALID_STREAM_INITIALIZED:"LocalStream.html#addTrack",INVALID_ADD_TRACK_NUMBER:"LocalStream.html#addTrack",INVALID_REMOVE_AUDIO_TRACK:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ADDING:"LocalStream.html#removeTrack",INVALID_REMOVE_AUDIO_ON:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHING:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NUMBER:"LocalStream.html#removeTrack",INVALID_REMOVE_TRACK_NOT_PUBLISHED:"LocalStream.html#removeTrack",START_MIX_TRANSCODE_TIMEOUT:"Client.html#startMixTranscode",START_MIX_TRANSCODE_FAILED:"Client.html#startMixTranscode",STOP_MIX_TRANSCODE_FAILED:"Client.html#stopMixTranscode",MIX_TRANSCODE_NOT_STARTED:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_FRAMERATE:"Client.html#startMixTranscode",MIX_PARAMS_VIDEO_GOP:"Client.html#startMixTranscode",MIX_PARAMS_AUDIO_BITRATE:"Client.html#startMixTranscode",MIX_PARAMS_USER_Z_ORDER:"Client.html#startMixTranscode",MIX_PARAMS_NOT_SELF:"Client.html#startMixTranscode",MIX_PARAMS_USER_STREAM:"Client.html#startMixTranscode",INVALID_PLAY:"Stream.html#play",PLAY_FAILED:"Stream.html#play",INVALID_USERID:"TRTC.html#createClient",INVALID_CREATE_STREAM_SOURCE:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN:"TRTC.html#createStream",INVALID_CREATE_STREAM_AUDIO:"TRTC.html#createStream",INVALID_CREATE_STREAM_SCREEN_AUDIO:"TRTC.html#createStream",NOT_SUPPORTED_HTTP:"tutorial-05-info-browser.html#h2-2",NOT_SUPPORTED_WEBRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_TRTC:"tutorial-05-info-browser.html",NOT_SUPPORTED_PROFILE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_MEDIA:"tutorial-05-info-browser.html",NOT_SUPPORTED_H264ENCODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_H264DECODE:"tutorial-23-advanced-support-detection.html",NOT_SUPPORTED_TRACK:"LocalStream.html#addTrack",NOT_SUPPORTED_REPLACE_TRACK:"LocalStream.html#replaceTrack",NOT_SUPPORTED_CAPTURE:"tutorial-05-info-browser.html",MICROPHONE_NOT_FOUND:"TRTC.html#createStream",CAMERA_NOT_FOUND:"TRTC.html#createStream",SUBSCRIBE_FAILED:"Client.html#subscribe",API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t="Client.html#subscribe":t="module-ErrorCode.html#.API_CALL_ABORTED",t}};typeof window!="undefined"&&(window.TRTC_ERROR_INFO=Hm,window.TRTC_ERROR_LINK=Fm);var Vd=(i,t)=>t?`${Mi}/${i}/${t}`:`${Mi}/${i}/index.html`;var Gm=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let i=localStorage.getItem(hd);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function H(i){let{key:t,data:e,link:r,addDocLink:n=!0}=i,s="",o="",a="";oe(Be[t])?s=Be[t](e):re(Be[t])&&(s=Be[t]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Gm();r?a=`${r.className}.html#${r.fnName}`:d&&d[t]&&(oe(d[t])?a=d[t](e):re(d[t])&&(a=d[t]));let u=s;return _t()&&(c&&c[t]&&(oe(c[t])?o=c[t](e):re(c[t])&&(o=c[t])),o&&(n?u=`${o}
75
+ \u8BF7\u67E5\u770B\u6587\u6863: ${Vd("zh-cn",a)}
76
+
77
+ `:u=`${o}
78
+
79
+ `,u+=s)),n&&(u+=`
80
+ Refer to: ${Vd("en",a)}
81
+ `),u}var Km="trtc_env",jm=function(){return new URLSearchParams(location.search).get(Km)||""},jn=i=>Number(i)<14e8,hi=function(i,t){let e;Cn?e=Cn:e=jn(i)?md:pd;let r=Math.floor(Math.random()*En(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`};function Bd(){return it?4:pi?2:Rr?3:Nt?12:Dr?5:Or?13:1}function $d(){return it?"Android":pi?"iPhone":Rr?"iPad":Nt?"Mac":Dr?"Windows":Or?"Linux":"unknown"}function Jn(){let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),n=t&&t.effectiveType&&t.effectiveType.toLowerCase();n==="slow-2"&&(n="2g");let s=e||"unknown";if(r)switch(r){case"cellular":case"wimax":s=n||"unknown";break;case"wifi":s="wifi";break;case"ethernet":s="wired";break;case"none":case"other":case"unknown":default:s="unknown";break}return s}var Jm=function(i){return{AbilityOption:{AVLimit:i,GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:String(navigator.platform),uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:Bd(),uint32_device_type:0,str_os_verion:$d(),uint32_link_type:1,str_client_version:Pi,uint32_net_type:ci[Jn()],ua:navigator.userAgent,version:""}}}};function xo({fn:i,context:t}){return function(...e){try{let r=i.apply(t||this,e);return Yn(r)?r.catch(n=>P.error(`${i.name}() error observed ${n}`)):r}catch(r){P.error(`${i.name}() error observed ${r}`)}}}function Ym(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Xm(i,t=48e3){return Hd(i/4,t)}function Hd(i,t=48e3){return i*1e3/t}function qm(i,t=48e3){return Fd(i,t)*4}function Fd(i,t=48e3){return i*t/1e3}var Gd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},_t=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},Yt=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function wi(i,t=1,e=1){return i<=1?e:wi(i-1,e,t+e)}function ft(i){return i>8?30*1e3:wi(i)*1e3}function _e(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var oe=i=>typeof i=="function",N=i=>typeof i=="undefined",re=i=>typeof i=="string",ce=i=>typeof i=="number",bt=i=>typeof i=="boolean",_i=i=>_e(i)==="object",Xt=i=>_e(i)==="array",zm=i=>_e(i)==="MediaStreamTrack".toLowerCase(),qt=i=>i.isRemote,Yn=i=>_e(i)==="promise",xr=i=>oe(i)&&i.prototype.constructor===i,Xn=i=>xr(i)?i.prototype.constructor.name:"";typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Uo=typeof AudioWorkletNode!="undefined",Pt=()=>new window.AudioContext,Qm=(()=>{let i;return()=>{if(i)return i;i=new window.AudioContext;let t=()=>{i.state==="suspended"?(i.resume(),document.addEventListener("click",i.resume)):i.state==="interrupted"?i.resume():document.removeEventListener("click",i.resume)};return i.onstatechange=()=>{P.info(`gain context state: ${i.state}`),t()},i}})();function Vo(i){return new Promise((t,e)=>{let r=[];i.forEach(n=>{n.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function ee(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var wo=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(n){let s=H({key:$.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return P.warn(`${s}
82
+
83
+ ${n.stack}`),!1}},i},wd=i=>+i<10?`0${i}`:i,Zm=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=wd(e[1])+wd(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},eh=Object.prototype.hasOwnProperty,{toString:qf}=Object.prototype;function Ur(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Yt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(eh.call(i,t))return!1;return!0}}return!1}function Bi(i,t){return{userId:t,hasAudio:!!(i&pr),hasVideo:!!(i&lr),hasAuxiliary:!!(i&yn),hasSmall:!!(i&_d),audioMuted:!!(i&mo),videoMuted:!!(i&ho),audioAvailable:!!(i&pr)&&!(i&mo),videoAvailable:!!(i&lr)&&!(i&ho)}}function th(i,t){return i>50||t>500?5:i>30||t>350?4:i>20||t>200?3:i>10||t>100?2:i>=0||t>=0?1:0}function ih(i){let t={urls:`turn:${i.url}`};return!N(i.username)&&!N(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",N(i.credentialType)||(t.credentialType=i.credentialType)),t}function Vr(i,t=!0){if(!re(i))return 0;let e=i.split(".");return t?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var kr=function(i){return Xt(i)||_i(i)},Et=function(i,t,e,r){if(!(kr(i)&&kr(t)))return 0;let n=0,s=Object.keys(t),o;for(let a=0,c=s.length;a<c;a++)if(o=s[a],!(N(t[o])||e&&e.includes(o)))if(kr(i[o])&&kr(t[o]))n+=Et(i[o],t[o],e,r);else{if(r&&r.includes(t[o]))continue;i[o]!==t[o]&&(i[o]=t[o],n+=1)}return n},qn=i=>re(i)?document.getElementById(i):i,rh=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),nh=()=>rh.format(new Date);var eE=h(_(),1);function zt({url:i,body:t,method:e,timeout:r}){let n=new XMLHttpRequest;return new Promise((s,o)=>{n.onreadystatechange=()=>{if(n.readyState===4)if(n.status>=200&&n.status<300)try{let a=JSON.parse(n.response);s({data:a})}catch(a){s({data:n.response})}else o({status:n.status,statusText:n.statusText||"request failed!"})},n.timeout=r||5e3,n.open(e||"POST",i,!0),n.send(t)})}var nE=h(_(),1);var sh=0,oh=1,Wd=2;function ah({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:n,context:s}){return function(...o){let{retries:a=5,timeout:c=1e3}=t,d=0,u=-1,l=sh,m=(S,E)=>T(this,null,function*(){let y=s||this;try{let B=yield i.apply(y,o);d=0,S(B)}catch(B){let x=()=>{clearTimeout(u),d=0,l=Wd,E(B)},F=()=>{l!==Wd&&d<(oe(a)?a():a)?(d++,l=oh,oe(r)&&r.call(this,d,x),u=window.setTimeout(()=>{u=-1,m(S,E)},oe(c)?c(d):c)):(x(),oe(n)&&n.call(this,B))};oe(e)?e.call(y,B,F,E):F()}});return new Promise(m)}}var Tt=ah;var uE=h(_(),1);var $i=class{constructor(t){p(this,"userId");p(this,"id");p(this,"sdkAppId");p(this,"type");p(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.isLocal=bt(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}|${this.userId}]`),P.log(t,e,N(this.userId)||Ur(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var _E=h(_(),1),jd=h(rt(),1),uh=new jd.default,C=uh;var EE=h(_(),1),Jd=(K=>(K.ROOM_DESTROY="1",K.JOIN_START="21",K.JOIN_SCHEDULE_SUCCESS="22",K.JOIN_SIGNAL_CONNECTION_START="23",K.JOIN_SIGNAL_CONNECTION_END="24",K.JOIN_SEND_CMD="25",K.JOIN_RECEIVED_CMD_RES="26",K.JOIN_SUCCESS="27",K.JOIN_FAILED="28",K.LEAVE_START="51",K.LEAVE_SEND_CMD="52",K.LEAVE_SUCCESS="53",K.PUBLISH_START="61",K.SEND_FIRST_VIDEO_FRAME="62",K.SUBSCRIBE_START="81",K.SUBSCRIBE_SUCCESS="82",K.UNSUBSCRIBE_SUCCESS="83",K.LOCAL_TRACK_CAPTURE_START="101",K.LOCAL_TRACK_CAPTURE_SUCCESS="102",K.LOCAL_TRACK_CAPTURE_FAILED="103",K.LOCAL_TRACK_PUBLISHED="104",K.LOCAL_TRACK_UNPUBLISHED="105",K.LOCAL_TRACK_REPLACED="106",K.SWITCH_DEVICE_SUCCESS="107",K.TRACK_MUTED="108",K.TRACK_UNMUTED="109",K.REMOTE_TRACK_SUBSCRIBED="110",K.REMOTE_TRACK_UNSUBSCRIBED="111",K.PLAY_TRACK_START="151",K.PLAYER_STATE_CHANGED="152",K.VIDEO_LOADED_DATA="153",K.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",K.WORKLET_LOADED_SUCCESS="155",K.WORKLET_LOADED_FAILED="156",K.SIGNAL_CONNECTION_STATE_CHANGED="201",K.PEER_CONNECTION_STATE_CHANGED="202",K.HEARTBEAT_REPORT="251",K.RECEIVED_PUBLISHED_USER_LIST="252",K.REMOTE_PUBLISH_STATE_CHANGED="253",K.AUDIO_LEVEL_INTERVAL="260",K.NETWORK_QUALITY="261",K.API_SUCCESS_RATE="262",K))(Jd||{}),I=Jd;var lh="%cTRTC%c%s",ph="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",mh="display: inline",hh=!(qe||it),$o=class{constructor(){p(this,"_isEnableUploadLog",!0);p(this,"_localJoinedUser",new Map);p(this,"_queue",[]);p(this,"_timeoutId",-1);p(this,"_logLevel",1);p(this,"_logLevelToUpload",2);!Rn&&!An&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){C.on(I.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;((e=t==null?void 0:t.config)==null?void 0:e.logLevelToUpload)&&pt[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),C.on(I.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),C.once(I.JOIN_FAILED,()=>{this.startUpload()}),C.on(I.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:n,sdkAppId:s})=>{t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})});else if(re(r.userId)&&ce(r.sdkAppId)){let{userId:n,sdkAppId:s}=r;t.map.has(n)?t.map.get(n).logs.push(r):t.map.set(n,{userId:n,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return T(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let n=[...t.values()];for(let s=0;s<n.length;s++){let{userId:o,sdkAppId:a,logs:c}=n[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Mn(),sdkAppId:String(a),userId:o,version:Ve,log:c.map(d=>d.log).join(`
84
+ `)}),a),c.forEach(d=>d.uploaded=!0)}}catch(n){}let r=e.filter(n=>!n.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Tt({retryFunction:()=>zt({url:hi(e,ki.LOG),body:t,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:(r,n)=>{n()}})()}getPrefix(t){let e=new Date;e.setTime(Ir());let r=String(e.getMilliseconds());return"padStart"in String.prototype&&(r=r.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${r}] <${pt[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){N(pt[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(re(t))return t;try{return JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,n,s){var a;if(e.unshift(this.getPrefix(t)),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push({log:e.reduce((c,d)=>`${c} ${this.logChunkToString(d)}`.trim(),""),level:t,userId:n,sdkAppId:s,forAllJoinedClients:r}),t<this._logLevel)return;let o=((a=pt[t])==null?void 0:a.toLowerCase())||"info";hh?console[o](lh,ph,mh,...e):console[o](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new $i(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;pt[r]&&(this._logLevelToUpload=r)}},P=new $o;var Yd=!0,Xd=function(){var i;Yd&&(Yd=!1,P.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Li}index.html`),console.info("* Changelog: https://cloud.tencent.com/document/product/647/38958"),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),P.info("TRTC Web SDK Version:",Ve),P.info("UA:",navigator.userAgent),P.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`))};var il=h(rt());var UE=h(_()),X={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed"};var Mt={};js(Mt,{HTTPS_API:()=>Sh,IS_GET_CAPABILITIES_SUPPORTED:()=>Ah,IS_GET_SETTINGS_SUPPORTED:()=>fi,IS_SEI_SUPPORTED:()=>rs,basis:()=>Ch,checkSystemRequirementsInternal:()=>Ko,decodeSupportStatus:()=>Zn,encodeSupportStatus:()=>eu,getBrowserInfo:()=>Eh,getDisplayResolution:()=>tu,getOSName:()=>es,isAddTransceiverSupported:()=>$r,isBrowserSupported:()=>Fo,isGetReceiversSupported:()=>Br,isGetSendersSupported:()=>is,isGetTransceiversSupported:()=>Qt,isGetUserMediaSupported:()=>iu,isMediaDevicesSupported:()=>Qn,isMediaSessionSupported:()=>ou,isMediaStreamTrackProcessorSupported:()=>Wo,isReplaceTrackSupported:()=>Rh,isScreenCaptureApiAvailable:()=>jo,isSelectedCandidatePair:()=>Hi,isSetParametersSupported:()=>Jo,isSmallStreamAPISupported:()=>nu,isSmallStreamSupported:()=>ts,isStopTransceiverSupported:()=>gh,isTRTCSupported:()=>Th,isUnifiedPlanDefault:()=>Ih,isUsedInHttpProtocol:()=>Go,isWebAudioSupported:()=>ru,isWebCodecSupported:()=>su,isWebCodecsSupported:()=>Zd,isWebRTCSupported:()=>Yo,isWebTransportSupported:()=>au});var qE=h(_(),1);var HE=h(_(),1);var wE=h(_(),1),qd=(R=>(R[R.INVALID_PARAMETER=4096]="INVALID_PARAMETER",R[R.INVALID_OPERATION=4097]="INVALID_OPERATION",R[R.NOT_SUPPORTED=4098]="NOT_SUPPORTED",R[R.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",R[R.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",R[R.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",R[R.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",R[R.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",R[R.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",R[R.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",R[R.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",R[R.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",R[R.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",R[R.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",R[R.CLIENT_BANNED=16448]="CLIENT_BANNED",R[R.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",R[R.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",R[R.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",R[R.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",R[R.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",R[R.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",R[R.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",R[R.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",R[R.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",R[R.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",R[R.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",R[R.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",R[R.API_CALL_ABORTED=16461]="API_CALL_ABORTED",R[R.UNKNOWN=65535]="UNKNOWN",R))(qd||{}),M=qd;var _h=function(i){for(let t in M)if(M[t]===i)return t;return"UNKNOWN"},Ho=class extends Error{constructor({name:e="RtcError",message:r,code:n=M.UNKNOWN,extraCode:s=0,constraint:o}){let a=`<${_h(n)} 0x${n.toString(16)}>`,c=`${r}${o?` constraint: ${o}`:""}${r!=null&&r.includes(a)?"":` ${a}`}`;super(c);this.code=n,this.extraCode=s,this.name=e,this.message=c,this.constraint=o,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},V=Ho;var ae={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},fh=new Map([[we,["Firefox",To]],[Cr,["Edg",Io]],[Pr,["Chrome",ko]],[ht,["Safari",Lr]],[yt,["TBS",Ao]],[xn,["XWEB",Co]],[vr&&pi,["WeChat",vo]],[Un,["QQ(Win)",yo]],[Nr,["QQ(Mobile)",gr]],[yr,["QQ(Mobile X5)",gr]],[Vn,["QQ(Mac)",No]],[wn,["QQ(iPad)",Do]],[Bn,["MI",Oo]],[$n,["HW",bo]],[Hn,["Samsung",Po]],[Fn,["OPPO",Mo]],[Gn,["VIVO",Lo]],[Ar,["EDGE",So]],[Ln,["SogouMobile",go]],[kn,["Sogou",Ro]]]);function Eh(){let i=fh.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Fo=function(){return!(Ld||Ar||Cr&&Md<80||we&&Pd<56)},Zd=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Qn=function(){if(!navigator.mediaDevices)return P.error(Be.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},zd=!1;function Go(){return location.protocol==="http:"&&!Vi&&!zd?(zd=!0,P.warn(H({key:$.NOT_SUPPORTED_HTTP})),!0):!1}var Wo=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},eu=function(){return T(this,null,function*(){if(ae.detail.isH264EncodeSupported||ae.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ae.detail.isH264EncodeSupported,isVp8EncodeSupported:ae.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,n=document.createElement(f.CANVAS);n.getContext("2d");let s=n.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),ae.detail.isH264EncodeSupported=t,ae.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ae.detail.isH264EncodeSupported,isVp8EncodeSupported:ae.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Zn=function(){return T(this,null,function*(){if(ae.detail.isH264DecodeSupported&&ae.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ae.detail.isH264DecodeSupported,isVp8DecodeSupported:ae.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Ko=function(){return T(this,null,function*(){if(ae.result)return ae;let i=Fo(),t=Yo(),e=Zd(),r=Qn(),{isH264EncodeSupported:n,isVp8EncodeSupported:s}=yield eu(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield Zn();return ae.result=i&&t&&r&&(n||s)&&(o||a),ae.detail.isBrowserSupported=i,ae.detail.isWebRTCSupported=t,ae.detail.isWebCodecsSupported=e,ae.detail.isMediaDevicesSupported=r,ae.detail.isScreenShareSupported=jo(),ae.detail.isSmallStreamSupported=ts(),ae.detail.isH264EncodeSupported=n,ae.detail.isVp8EncodeSupported=s,ae.detail.isH264DecodeSupported=o,ae.detail.isVp8DecodeSupported=a,ae.result||P.error(`${navigator.userAgent} isBrowserSupported: ${i}isWebCodecsSupported: ${e} isMediaSupported: ${r} isH264EncodeSupported: ${n} isVp8EncodeSupported: ${s} isH264DecodeSupported: ${o} isVp8DecodeSupported: ${a} `),ae})},Th=function(){return ae.result},jo=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Sh=(i,t,e)=>{location.protocol==="http:"&&!Vi&&(i[t]=()=>{throw new V({code:M.INVALID_OPERATION,message:Be.NOT_SUPPORTED_HTTP})})},Hi=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(bt(i.selected)&&!i.selected):!1},Qd=new Map([[it,"Android"],[qe,"iOS"],[Dr,"Windows"],[Nt,"MacOS"],[Or,"Linux"]]),es=function(){return Qd.get(!0)?Qd.get(!0):"unknown"};function tu(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function iu(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ru(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function nu(){return"captureStream"in HTMLCanvasElement.prototype}function ts(){return vr||qe||Mr&&Mr<63?!1:!!(Fo()&&nu())}var Ih=function(){if(N(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:ui}),i.addTransceiver(f.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function Br(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function is(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Qt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function $r(){return"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}function gh(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Rh(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Jo(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&is()}var fi=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Ah=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,rs="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&br()>=86,Yo=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function su(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return N(window.AudioDecoder)||(i.AudioDecoder=!0),N(window.AudioEncoder)||(i.AudioEncoder=!0),N(window.VideoDecoder)||(i.VideoDecoder=!0),N(window.VideoEncoder)||(i.VideoEncoder=!0),N(window.ImageDecoder)||(i.ImageDecoder=!0),i}function ou(){return"mediaSession"in navigator&&!N(navigator.mediaSession.setActionHandler)}function au(){return!N(window.WebTransport)}function Ch(){let i={browser:`${Dt.name}/${Dt.version}`,os:es(),displayResolution:tu(),isScreenShareSupported:jo(),isWebRTCSupported:Yo(),isGetUserMediaSupported:iu(),isWebAudioSupported:ru(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:su(),isMediaSessionSupported:ou(),isWebTransportSupported:au()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var DC=h(_(),1);var ZE=h(_(),1),vh=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},Xo=vh;var nT=h(_(),1);var qo=class{constructor(){p(this,"_prefix","TRTC");p(this,"_queue",new Map);this.checkStorage()}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!Jt())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix)){let n=JSON.parse(localStorage.getItem(r));if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(!!Jt())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){P.warn(t)}}getItem(t){if(!Jt())return null;try{let e=JSON.parse(localStorage.getItem(this.getRealKey(t)));return e&&e.expiresIn>=Date.now()?e.value:null}catch(e){P.warn(e)}}setItem(t,e){if(!!Jt())try{let r={expiresIn:Date.now()+co,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){P.warn(r)}}deleteItem(t){if(!Jt())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return P.warn(e),!1}}clear(){if(!!Jt())try{localStorage.clear()}catch(t){P.warn(t)}}},Fi=new qo;var ZI=h(_(),1);var aT=h(_(),1),du=h(rt(),1);var cu=Symbol("instance"),Hr=Symbol("abortCtrl"),Ei=Symbol("cacheResult"),zo=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},Fr=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},Gr=new Map,yh=Object.getPrototypeOf((()=>T(void 0,null,function*(){}))()).constructor;function $e(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=Gr.get(r)||[];Gr.has(r)||Gr.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return T(this,null,function*(){var S;let d=this;if(e.context&&(d=ue.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[Ei];let u=null;if(Array.isArray(i)?i.length==0?d[Hr]&&(d[Hr].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new Fr(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new Fr(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;ns.call(d,new zo(l,t,o));let m={aborted:!1};d[Hr]=m;try{let E=a.apply(this,c);return E instanceof yh?d[Ei]=yield E:d[Ei]=E,m.aborted||(d[Hr]=void 0,ns.call(d,t),(S=e.success)==null||S.call(this,d[Ei])),d[Ei]}catch(E){let y=E instanceof Error?E.message:String(E);if(ns.call(d,l,y),e.fail)e.fail.call(this,new Fr(d._state,`action '${o}' failed :${y}`,E instanceof Error?E:new Error(y)));else{if(e.ignoreError)return E;throw E}}})}}}var Nh=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function ns(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(ue.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var Dh,Oh,Ge=class extends du.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",Ge.INIT);p(this,Dh);p(this,Oh);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[cu];s?this.name=s.name+"-"+s.count++:n[cu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=Gr.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);Gr.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:m})=>{typeof u=="string"?s.push({from:u,to:l,action:m}):u.length?u.forEach(S=>{s.push({from:S,to:l,action:m})}):o.push({to:l,action:m})}),s.forEach(({from:u,to:l,action:m})=>{a.add(u),a.add(l),a.add(m+"ing"),n.add(`${u} --> ${m}ing : ${m}`),n.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),n.add(`${m}ing --> ${u} : ${m} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(m=>{m!==u&&n.add(`${m} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperties(e,{stateDiagram:{value:d},allStates:{value:a}}),d}static get(e){let r;return typeof e=="string"?(r=Ge.instances.get(e),r||Ge.instances.set(e,r=new Ge(e,void 0,Object.create(Ge.prototype)))):(r=Ge.instances2.get(e),r||Ge.instances2.set(e,r=new Ge(e.constructor.name,void 0,Object.create(Ge.prototype)))),r}static getState(e){var r;return(r=Ge.get(e))==null?void 0:r.state}updateDevTools(e={}){Nh(Ge.UPDATEAFSM,w({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){ns.call(this,e)}},ue=Ge;Dh=Ei,Oh=Hr,p(ue,"STATECHANGED","stateChanged"),p(ue,"UPDATEAFSM","updateAFSM"),p(ue,"INIT","[*]"),p(ue,"ON","on"),p(ue,"OFF","off"),p(ue,"instances",new Map),p(ue,"instances2",new WeakMap);var cI=h(_(),1);var xS=h(_(),1);var uS=h(_(),1);var nS=h(_(),1);var pT=h(_(),1);var uu=(window==null?void 0:window.requestIdleCallback)||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},bh=(window==null?void 0:window.cancelIdleCallback)||function(i){clearTimeout(i)},Ph=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Wr=class{static generateTaskID(){return this.currentTaskID++}static run(t=Sr,e,r){t===vd?r=w({delay:2e3,count:0,backgroundTask:!0},r):t===vt?r=w({delay:1e4,count:0},r):t===Kt?r=w({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=w({delay:2e3,count:0,backgroundTask:!0},r),_i(e)&&(r=w(w({},r),e)),oe(t)&&(e=t,t=Sr);let n=w({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r);return this.taskMap.set(n.taskID,n),this[t](n),n.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,this.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!this.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=ee(),r,n=()=>{if(r=ee()-e,r>=t.delay&&(e=ee()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.ricID=uu(n,{timeout:t.delay})};return t.ricID=uu(n,{timeout:t.delay})}static raf(t){t.delay=(1e3/t.fps).toFixed(2);let e=ee(),r,n=()=>{if(document.hidden&&t.backgroundTask)return r=ee()-e,e=ee(),t.callback(),t.loopCount+=1,this.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(n,t.delay-Math.floor(r%t.delay));if(r=ee()-e,r>=t.delay&&(e=ee()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!this.isBreakLoop(t))return t.rafID=requestAnimationFrame(n)};if(t.rafID=requestAnimationFrame(n),t.backgroundTask){let s=()=>{if(document.hidden){let o=ee()-e;o>=t.delay?n():t.timeoutID=setTimeout(n,t.delay-o)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:n,ricID:s,onVisibilitychange:o}=this.taskMap.get(t);return e&&clearInterval(e),r&&clearTimeout(r),n&&Ph(n),s&&bh(s),o&&document.removeEventListener("visibilitychange",o),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.taskMap.has(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};Wr.taskMap=new Map,Wr.currentTaskID=1;var le=Wr;var ET=h(_(),1);var lu={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_PUBLISHED:"stream-published",STREAM_SUBSCRIBED:"stream-subscribed",STREAM_UNSUBSCRIBED:"stream-unsubscribed",STATE_CHANGED:"state-changed",ERROR:"error",CONNECTION_STATE_CHANGED:"connection-state-changed",SEI_MESSAGE:f.SEI_MESSAGE},_T={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:f.SEI_MESSAGE,ERROR:"error"};var Zt={LOADED_DATA:f.LOADEDDATA,PLAYER_STATE_CHANGED:"player-state-changed"};var VT=h(_(),1);var DT=h(_(),1);var Qo=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Ve,env:Wt.QCLOUD,browserVersion:Dt.name+Dt.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:n}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(n))}logSuccessEvent(t){Vi||!P.isAbleToUpload||this._configs.env===Wt.QCLOUD&&this.uploadEventToKibana(ie(w({},t),{result:"success"}))}logFailedEvent(t){if(Vi||!P.isAbleToUpload)return;let{eventType:e,code:r,error:n,userId:s}=t,o={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||n.extraCode||n.code||M.UNKNOWN};this._configs.env===Wt.QCLOUD&&this.uploadEventToKibana(ie(w({},o),{error:n}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let n={timestamp:Mn(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Ve,log:t};r&&(n.errorInfo=r.message),this.sendRequest(hi(this._configs.sdkAppId,ki.LOG),n)}sendRequest(t,e){if(!P.isAbleToUpload){setTimeout(()=>{this.sendRequest(t,e)},1e3);return}zt({url:t,body:JSON.stringify(e)}).catch(()=>{})}},Ae=new Qo;var Lt="trtc_autoplay",Zo=`${Lt}_mask`,Gi=`${Lt}_wrapper`,pu=`${Lt}_header`,ea=`${Lt}_content`,ss=`${Lt}_action_wrapper`,ta=`${Lt}_question`,ia=`${Lt}_collapse`,os=`${Lt}_action_confirm`,mu=`${Lt}_detail`,hu="#2473E8",na="dialog",Mh=`${na}-show`,Lh=`${na}-1`,kh=`${na}-2`,_u=!1,sa=()=>!!document.querySelector(`.${Gi}`),Eu=`${Mi}/${_t()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,fu=`<br><a href='${Eu}' target='_blank'>${_t()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,xh=`${_t()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${fu}`:`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. ${fu}`}`,ra=class{constructor(){p(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");p(this,"_dialogNode",null);p(this,"_bodyPosition","");p(this,"_showDetail",!1);p(this,"_isCollapseClicked",!1);p(this,"_isQuestionClicked",!1);if(_t()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!_u){let t=document.createElement("style");t.innerHTML=`.${Zo}{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;}.${Zo} div:not(.${ss}){display:block !important;}.${Gi}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Gi} a{color:${hu};}.${pu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${ea}{margin:8px 0;}.${ss}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${ia}{margin-right:auto;cursor:pointer}.${ta}{height:100%;line-height:16px;cursor:pointer;}.${os}{margin-left:8px;color:#fff;background:${hu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${os}:hover{opacity:0.9;}.${ia},.${os},.${ea},.${ta}{font-size:14px;}@media screen and (max-width:750px){.${Gi}{width:80vw;}}`,document.head.appendChild(t),_u=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${Zo}"><div class='${Gi}'><div class='${pu}'>${location.host}</div><div class='${ea}'>${this.content}</div><div class='${mu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${xh}</div><div class='${ss}'></div></div></div>`.trim();let e=document.createElement("button");e.className=os,e.innerText=_t()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=ta,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
85
+ <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">
86
+ <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"/>
87
+ <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"/>
88
+ <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"/>
89
+ </svg>
90
+ `,r.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=ia,n.innerText=`${_t()?"\u8BE6\u60C5 >":"Detail >"}`,n.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,o=s.querySelector(`.${ss}`);return o.appendChild(n),o.appendChild(r),o.appendChild(e),s}addDiaLog(){sa()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Gi}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",P.info("show autoplay dialog"),Ae.uploadEvent({log:Mh}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){P.warn("confirm clicked, try resume stream"),C.emit(I.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${mu}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Ae.uploadEvent({log:Lh}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Eu,"_blank"),this._isQuestionClicked||Ae.uploadEvent({log:kh}),this._isQuestionClicked=!0}},Tu=ra;var Wi={};js(Wi,{create:()=>ze,remove:()=>Le});var BT=h(_(),1),Kr=new WeakMap;function ze(i,t){Kr.has(i)||Kr.set(i,[]);let e=Kr.get(i),n={add:(s,o)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,o)),t.addEventListener(s,o)):(e.push(t.off.bind(t,s,o)),t.on(s,o)),n)};return n}function Le(i){let t=Kr.get(i);t&&(t.forEach(e=>e()),Kr.delete(i))}var kt=class extends ue{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;p(this,"id");p(this,"element",null);p(this,"container",null);p(this,"mediaStream",new MediaStream);p(this,"track");p(this,"attr");p(this,"muted");p(this,"_log");p(this,"_pausedRetryCount");p(this,"_isElementPlayingFired",!1);p(this,"_interval");this.id=e.id,this._log=e.log,this.track=e.track,this.container=e.container,this.muted=e.muted,this._pausedRetryCount=Ad,this._state="STOPPED",this.bindTrackEvents()}get isPlaying(){return this._state==="PLAYING"}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setTrack(e){if(e!==this.track&&(this.unbindTrackEvents(),this.track=e,e!==null&&(this.bindTrackEvents(),this.element))){let r=new MediaStream;r.addTrack(e),this.element.srcObject=r}}setContainer(e){this.container=e,this.track&&this.element&&this.container&&this.container.appendChild(this.element)}play(){return T(this,null,function*(){if(this.element&&this.element.parentElement!==this.container&&this.container&&this.container.append(this.element),!this.isPlaying)try{this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let r=H({key:$.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(r),r.includes("NotAllowedError"))throw new V({code:M.PLAY_NOT_ALLOWED,message:r})}})}stop(){this.unbindEvents(),this._isElementPlayingFired=!1,this.element&&(this.container&&this.container.removeChild(this.element),this.element.srcObject=null,this.element=null),this.handleStopped(f.ENDED),this._interval>0&&le.clearTask(this._interval)}resume(){return this.isPlaying?Promise.resolve():Wn?this.replay():(this._log.info("resume"),this.play().catch(()=>{}))}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}setRect(e,r){this.element&&(this.element.style.width=`${e}px`,this.element.style.height=`${r}px`)}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);ze(this.element,this.element).add(f.PLAYING,e).add(f.ENDED,e).add(f.PAUSE,e).add(f.ERROR,e).add(f.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);Wi==null||Wi.create(this.track,this.track).add(f.ENDED,e).add(f.MUTE,e).add(f.UNMUTE,e),this.track.readyState===f.ENDED&&this.handleTrackEvent({type:f.ENDED}),this.track.muted&&this.handleTrackEvent({type:f.MUTE})}}bindAutoPlayEvent(){C.on(I.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&Le(this.track)}unbindEvents(){this.element&&Le(this.element),this.unbindTrackEvents(),C.off(I.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){var n;switch(e.type){case f.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(f.PLAYING),this._interval&&(le.clearTask(this._interval),this._interval=-1);break;case f.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(f.ENDED);break;case f.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(f.PAUSE);let s=this.container&&document.getElementById(this.container.id);s||this._log.warn(`${this.kind} player has been remove, element ID: ${(n=this.container)==null?void 0:n.id}`);let o=br();this._pausedRetryCount>0&&(this.kind===f.VIDEO&&!sa()||this.kind===f.AUDIO&&(ce(o)&&o<=70||!s))&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),qe&&(this._interval=le.run(Sr,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case f.ERROR:if(this.element&&this.element.error){let a=`${es()}/${Dt.name}/${Dt.version}`;this._log.error(`${this.kind} player error observed. code: ${this.element.error.code} message: ${this.element.error.message} deviceInfo: ${a}`)}break;case f.LOADEDDATA:this.kind===f.VIDEO&&this.emit(Zt.LOADED_DATA);break}}handleTrackEvent(e){switch(e.type){case f.ENDED:this._log.info(`${this.kind} track is ended`),this.handleStopped(f.ENDED);break;case f.MUTE:this._log.info(`${this.kind} track is unable to provide media output`),this.handlePaused(f.MUTE);break;case f.UNMUTE:this._log.info(`${this.kind} track is able to provide media output`),this._isElementPlayingFired&&this.handlePlaying(f.UNMUTE);break}}handlePlaying(e){this.emit(Zt.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Zt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}handleStopped(e){this.emit(Zt.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};G([$e([],"PLAYING")],kt.prototype,"handlePlaying",1),G([$e("PLAYING","STOPPED",{ignoreError:!0})],kt.prototype,"handlePaused",1),G([$e([],"STOPPED")],kt.prototype,"handleStopped",1);var Ki=class extends kt{constructor(e){super(e,f.VIDEO);p(this,"mirror");p(this,"objectFit");N(e.mirror)||(this.mirror=e.mirror),N(e.objectFit)||(this.objectFit=e.objectFit)}initializeElement(){var n;let e=document.createElement(f.VIDEO);if(this.track){let s=new MediaStream;s.addTrack(this.track),e.srcObject=s}e.muted=!0;let r=`width: 100%; height: 100%; object-fit: ${this.objectFit};background-color: black;`;this.mirror&&(r+="transform: scaleX(-1);"),e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",r),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),(n=this.container)==null||n.appendChild(e),this.element=e,this.bindElementEvents()}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}setMirror(e){this.element&&(this.element.style.transform=e?"scaleX(-1)":""),this.mirror=e}setObjectFit(e){this.element&&(this.element.style.objectFit=`${e}`),this.objectFit=e}play(){return this.element||this.initializeElement(),super.play()}getVideoFrame(){if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}};var MS=h(_(),1);var vS=h(_(),1);var fS=h(_(),1);var Uh="class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.port.onmessage=event=>{const{data}=event;switch(data.name){case'setIntervalTime':this.intervalTime=data.intervalTime;break;case'stop':this.isStop=true;break}}}process(inputs){const input=inputs[0];if(this.isStop){return false}if(input.length>0){const firstChannel=input[0];let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i]}rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume})}}return true}}registerProcessor('volume-meter',VolumeMeter);",Iu=!1,oa=class{constructor(t){p(this,"context_");p(this,"blob_");this.context_=t.context,this.blob_=new Blob([Uh],{type:"application/javascript"}),this.addModuleToContext()}addModuleToContext(){return T(this,null,function*(){try{yield this.context_.audioWorklet.addModule(URL.createObjectURL(this.blob_)),P.info("worklet addModule success"),C.emit(I.WORKLET_LOADED_SUCCESS),Iu=!0}catch(t){P.info(`worklet addModule catch error. ${t.message}`),C.emit(I.WORKLET_LOADED_FAILED)}})}get initWorkletSuccess(){return Iu}},gu=oa;var nt,as,cs=0,aa=class{constructor(t){p(this,"_volume");p(this,"_log");p(this,"_track");p(this,"_stream");p(this,"_audioCtx");p(this,"_destination");p(this,"_streamSource");p(this,"_scriptProcessorNode");p(this,"_audioWorkletNode");p(this,"_interval");let{track:e,log:r}=t;this._volume=0,this._log=r,this._track=e,nt||(nt=Pt()),this._audioCtx=nt,this._destination=this._audioCtx.destination;let n=new MediaStream;n.addTrack(this._track),this._streamSource=this._audioCtx.createMediaStreamSource(n),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._interval=200,C.on(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),Uo?(C.on(I.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.on(I.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),this.preload()):this.initScriptProcessor(),cs+=1}preload(){as?as.initWorkletSuccess&&this.initAudioWorklet():as=new gu({context:nt})}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(this._audioCtx,"volume-meter"),this._audioWorkletNode.port.onmessage=t=>{this._volume=t.data.volume||0},this._streamSource.connect(this._audioWorkletNode).connect(this._destination),this.handleAudioLevelInterval({interval:this._interval})}catch(t){Ae.logFailedEvent({userId:this._log.userId,eventType:di.LOAD_WORKLET}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=this._audioCtx.createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{let e=t.inputBuffer.getChannelData(0),r=0;for(let n=0;n<e.length;++n)r+=e[n]*e[n];this._volume=Math.sqrt(r/e.length)||0},this._streamSource.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._destination)}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}destroy(){this._streamSource&&this._streamSource.disconnect(),this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null,this._scriptProcessorNode.disconnect()),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null,this._audioWorkletNode.disconnect()),this._audioWorkletNode=null,this._scriptProcessorNode=null,this._audioCtx=null,C.off(I.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this),C.off(I.WORKLET_LOADED_SUCCESS,this.initAudioWorklet,this),C.off(I.WORKLET_LOADED_FAILED,this.initScriptProcessor,this),cs>0&&(cs-=1),cs===0&&(nt==null||nt.close(),nt=null,as=null)}resume(){nt==null||nt.resume()}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ru=aa;var Ti=class extends kt{constructor(e){super(e,f.AUDIO);p(this,"_volumeMeter");p(this,"gainedTrack");p(this,"_outputDeviceId");p(this,"_volume",1);e.gainedTrack&&(this.gainedTrack=e.gainedTrack),this._outputDeviceId=e.outputDeviceId,this.track&&this.initVolumeMeter(this.track)}setTrack(e){this.track!==e&&(this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),e!==null&&this.initVolumeMeter(e)),super.setTrack(e)}initVolumeMeter(e){this._volumeMeter=new Ru({track:this.gainedTrack||e,log:this._log})}initializeElement(){if((jt==="15.2"||jt==="15.3"||jt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=document.createElement(f.AUDIO);if(this.gainedTrack||this.track){let n=new MediaStream;n.addTrack(this.gainedTrack||this.track),r.srcObject=n}r.muted=this.muted,r.setAttribute("id",`audio_${this.id}`),r.setAttribute("autoplay","autoplay"),r.setAttribute("playsinline","playsinline"),this.element=r,this.bindElementEvents()}play(){return T(this,null,function*(){this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),!this._volumeMeter&&this.track&&this.initVolumeMeter(this.track),this.setVolume(this._volume),yield oi(Ti.prototype,this,"play").call(this)})}stop(){this._volumeMeter&&(this._volumeMeter.destroy(),this._volumeMeter=null),super.stop()}resume(){return T(this,null,function*(){yield oi(Ti.prototype,this,"resume").call(this),this._volumeMeter&&this._volumeMeter.resume()})}setSinkId(e){return T(this,null,function*(){this._outputDeviceId!==e&&(this.element&&(yield this.element.setSinkId(e)),this._outputDeviceId=e)})}setVolume(e){!this.element||(this.element.volume=e,this._volume=e)}getAudioLevel(){var e;return((e=this._volumeMeter)==null?void 0:e.getCalculatedVolume())||0}getInternalAudioLevel(){var e;return(e=this._volumeMeter)==null?void 0:e.getInternalAudioLevel()}};var Si=class extends ue{constructor({userId:e,sdkAppId:r,mediaType:n}){super();p(this,"id",Xo());p(this,"userId");p(this,"isRemote");p(this,"mediaType");p(this,"room");p(this,"user");p(this,"_log");p(this,"isPlayCalled");p(this,"mediaTrack",null);p(this,"mediaStream");p(this,"container",null);p(this,"playerMuted",!1);p(this,"abortCtrl");p(this,"audioOutputDeviceId");p(this,"audioVolume");p(this,"objectFit","cover");p(this,"mirror",!1);p(this,"gain");p(this,"isScreen",!1);N(e)||(this.userId=e),this.mediaType=n,this._log=P.createLogger({id:`${this.kind[0]}t`,userId:e,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Ze}),this.initPlayer()}get log(){return this._log||P}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get muted(){return!!(this.mediaTrack&&!this.mediaTrack.enabled)}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}uninstallEvents(){}play(e,r){return T(this,null,function*(){if(!!this.mediaTrack){if(this._log.info(`play with options: ${JSON.stringify(r)}`),this.isPlayCalled){r&&!N(r.muted)&&this.setPlayerMute(r.muted),r&&!N(r.objectFit)&&(this.objectFit=r.objectFit),this.isScreen?this.mirror=!1:r&&!N(r.mirror)&&(this.mirror=r.mirror),this.kind===f.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror),this.container!==e&&e&&(this.container=e,this.player.setContainer(e)));return}(!this.isRemote||this.kind===f.VIDEO)&&(this.playerMuted=!0),r&&!N(r.muted)&&(this.playerMuted=r.muted),r&&!N(r.objectFit)&&(this.objectFit=r.objectFit),this.isScreen?this.mirror=!1:(this.isRemote||(this.mirror=!0),r&&!N(r.mirror)&&(this.mirror=r.mirror)),this.player.setMuted(this.playerMuted),this.kind===f.VIDEO&&(this.player.setObjectFit(this.objectFit),this.player.setMirror(this.mirror)),this.isPlayCalled=!0,e&&(this.container=e,this.player.setContainer(e)),C.emit(I.PLAY_TRACK_START,{track:this});try{yield this.player.play()}catch(n){if(this.room&&this.room.enableAutoPlayDialog)new Tu;else{let s=()=>{this.resume().then(()=>{document.removeEventListener("click",s,!0),document.removeEventListener("touchstart",s,!0)})};document.addEventListener("click",s,!0),document.addEventListener("touchstart",s,!0)}throw this.emit("error",n),n}}})}initPlayer(){var e;this.log.info(`create ${this.kind}Player`),this.kind===f.AUDIO?this.player=new Ti({id:this.userId||this.id,track:this.mediaTrack,gainedTrack:(e=this.gain)==null?void 0:e.audioTrack,container:this.container||null,muted:this.playerMuted,outputDeviceId:this.audioOutputDeviceId,log:this.log}):(this.player=new Ki({id:this.userId||this.id,track:this.mediaTrack,container:this.container||null,muted:this.playerMuted,objectFit:this.objectFit,mirror:this.mirror,log:this.log}),this.player.on(Zt.LOADED_DATA,()=>{C.emit(I.VIDEO_LOADED_DATA,{track:this})})),this.player.on(Zt.PLAYER_STATE_CHANGED,r=>{C.emit(I.PLAYER_STATE_CHANGED,w({track:this},r)),this.emit("player-state-changed",r)})}setAudioOutput(e){return T(this,null,function*(){var r;this.audioOutputDeviceId=e,yield(r=this.player)==null?void 0:r.setSinkId(e)})}setAudioVolume(e){var r;this.audioVolume=e,this.log.info(`setAudioVolume to ${e}`),(r=this.player)==null||r.setVolume(e)}getAudioLevel(){var e;return((e=this.player)==null?void 0:e.getAudioLevel())||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(),this.player.setContainer(null)),this.container=null)}resume(){return T(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){var e;this.log.info("close"),this.isPlayCalled&&this.stop(),!this.isRemote&&((e=this.mediaTrack)==null||e.stop(),this.mediaTrack=null,this.uninstallEvents())}setMute(e){return this.mediaTrack?(this.mediaTrack.enabled=!e,this.emit(e?"mute":"unmute",this),C.emit(e?I.TRACK_MUTED:I.TRACK_UNMUTED,{track:this}),!0):!1}setPlayerMute(e){this.playerMuted=e,this.player.setMuted(e)}setMediaStream(e){e!==this.mediaStream&&(this.mediaStream=e)}setMediaStreamTrack(e){this.mediaStream||(this.mediaStream=new MediaStream),this.mediaTrack&&this.mediaStream.removeTrack(this.mediaTrack);let r=this.mediaTrack;this.mediaTrack=e,this.mediaTrack&&(this.mediaTrack.enabled=!this.muted,this.mediaStream.addTrack(this.mediaTrack),this.isRemote||this.player.setTrack(this.mediaTrack)),this.updatePlayingState(!!e),this.emit("media-track-changed",this.mediaTrack,r)}setMediaType(e){this.mediaType=e}updatePlayingState(e){!this.isPlayCalled||e&&!this.player.isStopped||!e&&this.player.isStopped||this.isPlayCalled&&this.player.isStopped===e&&(this.log.info(`playing state updated, ${e?"play":"stop"} ${this.kind}`),e&&this.player.isStopped&&this.player.play(),!e&&!this.player.isStopped&&this.player.stop())}};G([$e([],ue.INIT)],Si.prototype,"close",1);var bI=h(_(),1);var mI=h(_(),1);var Vh=Object.prototype.hasOwnProperty,{toString:lI}=Object.prototype;function wh(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(Yt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(Vh.call(i,t))return!1;return!0}}return!1}var ji=wh;var TI=h(_(),1),vu=h(rt(),1);var Cu=i=>t=>t.deviceId===i;var jr=class{constructor(t,e="Input"){p(this,"kind");p(this,"type");p(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(n=>n.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);e&&(r.forEach(n=>{if(n.deviceId&&!this.devices.find(Cu(n.deviceId))){let s=`${this.kind}${this.type}Added`;P.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}}),this.devices.forEach(n=>{if(n.deviceId&&!r.find(Cu(n.deviceId))){let s=`${this.kind}${this.type}Removed`;P.warn(`${s}: ${JSON.stringify(n)}`),e.emit(s,n)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},ca=class extends vu.EventEmitter{constructor(){super();p(this,"audioInputs",new jr(f.AUDIO));p(this,"videoInputs",new jr(f.VIDEO));p(this,"audioOutputs",new jr(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&navigator.mediaDevices.addEventListener("devicechange",this.update.bind(this))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return T(this,null,function*(){let e=yield ds();return this.audioInputs.update(e,this),this.videoInputs.update(e,this),this.audioOutputs.update(e,this),this})}},fe=An||Rn?null:new ca;function ds(){return T(this,null,function*(){return Go()||!Qn()?[]:(yield navigator.mediaDevices.enumerateDevices()).map((t,e)=>{let r={kind:t.kind,deviceId:t.deviceId,groupId:t.groupId,label:t.label||`${t.kind}_${e}`};return t.deviceId.length>0&&da.add(`${t.deviceId}_${t.kind}`),t.getCapabilities&&(r.getCapabilities=()=>t.getCapabilities()),r})})}function et(){return fe.update().then(i=>i.audioInputs.devices)}function It(){return fe.update().then(i=>i.videoInputs.devices)}function Ji(){return T(this,null,function*(){return fe.update().then(i=>i.audioOutputs.devices)})}var da=new Set;function yu(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!da.has(r)}function Nu(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!da.has(r)}function ua(i,t){return T(this,null,function*(){let r=(yield et()).find(n=>n.deviceId===Ui);return(r==null?void 0:r.groupId)===i&&r.label===t})}function Du(s){return T(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:n}){return i!==t?!1:n===f.AUDIO&&i===Ui?yield ua(e,r):!0})}var Bh=function(i){return T(this,null,function*(){let t=yield Hh(i);P.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e,r;t.audio&&(e=yield et(),P.info(`microphones: ${JSON.stringify(e)}`)),t.video&&(r=yield It(),P.info(`cameras: ${JSON.stringify(r)}`));try{return yield navigator.mediaDevices.getUserMedia(t)}catch(n){if(n.name==="NotFoundError"){if(r&&r.length===0)throw new V({code:M.DEVICE_NOT_FOUND,message:H({key:$.CAMERA_NOT_FOUND})});if(e&&e.length===0)throw new V({code:M.DEVICE_NOT_FOUND,message:H({key:$.MICROPHONE_NOT_FOUND})})}throw new V({code:M.INITIALIZE_FAILED,name:n.name,message:n.message,constraint:n.constraint})}})},$h=Tt({retryFunction:Bh,settings:{retries:3,timeout:500},onError:(i,t,e)=>{i.name==="NotReadableError"?t():e(i)},onRetrying:i=>{P.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)}});function Hh(i){return T(this,null,function*(){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression};if(!i.audio)t=!1;else if(!ji(i.microphoneId))t=w({deviceId:i.useExact?{exact:i.microphoneId}:i.microphoneId,sampleRate:i.sampleRate,channelCount:i.channelCount},t);else{t=w({sampleRate:i.sampleRate,channelCount:i.channelCount},t);let o=(yield et()).filter(({deviceId:a})=>a.length>0);o.length>0&&(t.deviceId={exact:o[0].deviceId})}let e={},r={ideal:i.width,max:i.width},n={ideal:i.height,max:i.height};return we&&Nt&&i.width*i.height<352*288&&(r=i.width,n=i.height),!N(i.facingMode)&&i.video?e={facingMode:i.facingMode,width:r,height:n,frameRate:i.frameRate}:!ji(i.cameraId)&&i.video?e={deviceId:i.useExact?{exact:i.cameraId}:i.cameraId,width:r,height:n,frameRate:i.frameRate}:i.video?N(i.width)?e=!0:e={width:r,height:n,frameRate:i.frameRate}:e=!1,{audio:t,video:e}})}var Ou=$h;var LI=h(_(),1);function us(i){return de((t,e)=>function(...r){return T(this,null,function*(){return yield i.apply(this,r),t.apply(this,r)})})}function Yi(i){return de((t,e)=>function(...r){return T(this,null,function*(){return i.call(this,t.apply(this,r))})})}function de(i){return function(t,e,r){return r.value=i(r.value,e),r}}var Ze=class extends Si{constructor(e){super({mediaType:e});p(this,"isRemote",!1);p(this,"deviceId");p(this,"groupId","");p(this,"label","");p(this,"_isRecapturing",!1);p(this,"_lastRecaptureTime",0);this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this)}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToCapture(){}capture(e){return T(this,null,function*(){try{C.emit(I.LOCAL_TRACK_CAPTURE_START,{track:this});let r;e.customSource?(r=new MediaStream,r.addTrack(e.customSource)):r=yield Ou(e);let n=r.getTracks()[0];return this.setMediaStream(r),this.setMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),C.emit(I.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this}),r}catch(r){throw C.emit(I.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setMediaStreamTrack(e){this.state===ue.INIT&&this.setStateToCapture(),this.mediaTrack&&this.uninstallTrackEvent(this.mediaTrack),super.setMediaStreamTrack(e),e&&this.installTrackEvent(e)}setPublishStarting(){}setPublishStarted(){}setPublishStopped(e,r){}publish(e){this.room=e,this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),C.emit(I.LOCAL_TRACK_PUBLISHED,{track:this}),this.setPublishStarted()}unpublish(){this.room=void 0,this.mediaType===2&&(this.mediaType=4),C.emit(I.LOCAL_TRACK_UNPUBLISHED,{track:this}),this.setPublishStopped("api-call")}get isPublishing(){return this.state==="publish"}updateDeviceIdInUse(){return T(this,null,function*(){if(this.mediaTrack&&fi){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings();(yield Du({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=this.mediaTrack.label,r&&(this.groupId=r),ds().then(s=>{let o=s.find(a=>a.deviceId===e);o&&this.emit("2",o)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===f.AUDIO&&!Nu(this.mediaTrack)||this.kind===f.VIDEO&&!yu(this.mediaTrack)||this._isRecapturing||e&&(Nt&&ht||qe&&Number(jt)>=15.1))}onTrackMuted(){if(!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Tr){setTimeout(()=>this.onTrackMuted(),Tr);return}setTimeout(()=>{var e;((e=this.mediaTrack)==null?void 0:e.muted)&&document.visibilityState==="visible"&&this.recapture(this.deviceId)},5e3)}}onTrackEnded(){if(!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Tr){setTimeout(()=>this.onTrackEnded(),Tr);return}this.recapture(this.deviceId)}}recapture(e){return T(this,null,function*(){var s;if(this._isRecapturing||!this.mediaTrack)return;let r;return this.log.warn("recapture trying"),(s=this.mediaTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now(),(this.kind==="audio"?yield et():yield It()).find(o=>o.deviceId===e)&&(r=e),this.capture({deviceId:r,useExact:!0}).then(()=>{var o;return(o=this.room)==null?void 0:o.replaceTrack(this)}).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o)})})}};G([$e(ue.INIT,"capture")],Ze.prototype,"setStateToCapture",1),G([$e("capture","publish_starting",{success(){this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"})}})],Ze.prototype,"setPublishStarting",1),G([$e("publish_starting","publish",{success(){this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})}})],Ze.prototype,"setPublishStarted",1),G([de(i=>function(t,e){i.call(this,t,e),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:this.state.oldState==="publish_starting"?"starting":"started",reason:t,error:e})}),$e(["publish","publish_starting"],"capture",{ignoreError:!0})],Ze.prototype,"setPublishStopped",1);var ug=h(_(),1);var xt=class extends Ze{constructor(){super(1);p(this,"mediaType",1);p(this,"volume",0);p(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});p(this,"playerMuted",!0)}getAudioLevel(){return this.volume||super.getAudioLevel()}capture({deviceId:e,useExact:r=!1}={}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExact:r})}switchDevice(e){return T(this,null,function*(){if(!(!this.mediaStream||!this.mediaTrack)){if(this.deviceId===e)if(e===Ui){if(yield ua(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(I.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){fe&&!fe.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&fe.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return T(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`);let r=yield et();r[0]?this.recapture(r[0].deviceId):fe.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){return T(this,null,function*(){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){fe.off("audioInputAdded",this.handleMicrophoneAdded,this),fe.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}};var Rg=h(_(),1);var st=class extends Ze{constructor(){super(4);p(this,"mediaType",4);p(this,"profile",{width:640,height:480,frameRate:15,bitrate:900});p(this,"states",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0});p(this,"small");p(this,"facingMode");p(this,"_canvas");p(this,"_canvasInterval");p(this,"canvasTrack")}capture({deviceId:e,facingMode:r,useExact:n=!1,customSource:s}={}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExact:n,customSource:s})}genCanvasTrack(){if(this.canvasTrack||!this.mediaTrack)return;this.log.info("gen canvas track");let{width:e,height:r,frameRate:n}=this.mediaTrack.getSettings();this._canvas=document.createElement("canvas");let s=this._canvas.getContext("2d");e&&r&&(this._canvas.width=e,this._canvas.height=r),this._canvasInterval=le.run(Kt,()=>{if(!this._canvas)return;if(this.mediaTrack){let c=this.mediaTrack.getSettings();(c.width!==this._canvas.width||c.height!==this._canvas.height)&&(this._canvas.width=c.width,this._canvas.height=c.height)}let a=this.player.getElement();a&&(s==null||s.drawImage(a,0,0,this._canvas.width,this._canvas.height))},{fps:Math.max(15,n||0)});let o=this._canvas.captureStream();this.canvasTrack=o.getVideoTracks()[0]}destoryCanvasTrack(){this._canvasInterval&&(le.clearTask(this._canvasInterval),this._canvasInterval=void 0,this._canvas=void 0,this.canvasTrack=void 0)}setProfile(e){var n;if(!e)return;let r=e.bitrate&&e.bitrate!==this.profile.bitrate;return super.setProfile(e),(n=this.mediaTrack)==null?void 0:n.applyConstraints({width:e.width,height:e.height,frameRate:e.frameRate}).then(()=>{if(r&&this.room&&this.room.setBandWidth)return this.room.setBandWidth({bandwidth:e.bitrate,type:f.VIDEO,videoType:f.BIG})})}switchDevice(e){return T(this,null,function*(){try{if(!this.mediaStream||this.deviceId===e||this.facingMode===e)return;(e===f.FACING_MODE_USER||e===f.FACING_MODE_ENVIRONMENT)&&(this.facingMode=e,e=void 0),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExact:!0}),this.room&&(yield this.room.replaceTrack(this)),C.emit(I.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){fe&&!fe.listeners("audioInputRemoved").includes(this.handleCameraRemoved)&&fe.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return T(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`);let r=yield It();r[0]?this.recapture(r[0].deviceId):fe.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return T(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}close(){fe.off("videoInputAdded",this.handleCameraAdded,this),fe.off("videoInputRemoved",this.handleCameraRemoved,this),this.destoryCanvasTrack(),super.close()}};var xg=h(_(),1);var Dg=h(_(),1);var Gh=function(i){return T(this,null,function*(){let t=null;if(Pr&&Mr<74||ht){let n=la(i);P.info(`getDisplayMedia with constraints: ${JSON.stringify(n)}`);let s=yield navigator.mediaDevices.getDisplayMedia(n);if(i.systemAudio)return P.warn("Your browser not support capture system audio"),s;if(i.audio){let o=Pu(i);return P.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),t=yield navigator.mediaDevices.getUserMedia(o),s.addTrack(t.getAudioTracks()[0]),s}return s}if(i.systemAudio){let n=la(i);return P.info(`getDisplayMedia with constraints: ${JSON.stringify(n)}`),yield navigator.mediaDevices.getDisplayMedia(n)}let e=la(i);P.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);if(i.audio){let n=Pu(i);return P.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),t=yield navigator.mediaDevices.getUserMedia(n),r.addTrack(t.getAudioTracks()[0]),r}return r})};function Pu(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return N(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function la(i){let t={systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:ht?{max:i.width}:{ideal:i.width,max:i.width},height:ht?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:"monitor"};if(t.video=e,!N(i.systemAudio)){let{echoCancellation:r=!0,noiseSuppression:n=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:n,autoGainControl:s,sampleRate:48e3}}return t}var Mu=Gh;var gt=class extends st{constructor(){super();p(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});p(this,"objectFit","contain");p(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(){return T(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:n,noiseSuppression:s,audioTrack:o,videoTrack:a}={}){try{let c;return a||o?(c=new MediaStream,a&&c.addTrack(a),o&&c.addTrack(o)):c=yield Mu({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:n,noiseSuppression:s}),this.setMediaStream(c),this.setMediaStreamTrack(c.getVideoTracks()[0]),c}catch(c){throw this.log.error(`getDisplayMedia error observed ${c}`),c instanceof V?c:new V({code:M.INITIALIZE_FAILED,name:c.name,message:c.message})}})}switchDevice(e){return T(this,null,function*(){throw new Error("Method not implemented.")})}};var Bg=h(_(),1);var Ii=class extends xt{constructor(){super(),this._log.id=`s-${this._log.id}`}setScreenAudioTrack(t,e){this.setMediaStream(e),this.setMediaStreamTrack(t)}};var Xg=h(_(),1);var Gg=h(_(),1),ku=h(rt(),1);var Lu=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","interruptbegin","interruptend","loadedmetadata","loadstart","mozaudioavailable","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting"],Jr=class extends ku.default{constructor(e){super();p(this,"audioContext");p(this,"destination");p(this,"source",null);p(this,"audio");p(this,"id");this.audioContext=Pt(),this.initAudioContext(),this.destination=this.audioContext.createMediaStreamDestination(),this.audio=document.createElement("audio"),this.audio.crossOrigin="anonymous",this.audio.src=e.url,typeof e.loop=="boolean"&&(this.audio.loop=e.loop),e.volume&&this.setVolume(e.volume),e.id&&(this.id=e.id),this.source=this.audioContext.createMediaElementSource(this.audio),this.source.connect(this.destination),Lu.forEach(r=>{this.audio.addEventListener(r,this.handleAudio.bind(this))})}initAudioContext(){let e=this.audioContext,r=()=>{e.state==="suspended"?(e.resume(),document.addEventListener("click",r)):e.state==="interrupted"?e.resume():document.removeEventListener("click",r)};document.addEventListener("click",r),e.onstatechange=()=>{P.info(`audioSource context state: ${e.state}`),r()}}destroy(){var e,r;(e=this.source)==null||e.disconnect(),(r=this.destination)==null||r.disconnect(),this.audio&&(Lu.forEach(n=>{this.audio.removeEventListener(n,this.handleAudio.bind(this))}),this.audio.pause(),this.audio.removeAttribute("src"),this.audio.removeAttribute("srcObject"),this.audio.load()),this.audioContext.close().then(()=>{this.source=null,this.destination=null,this.audioContext=null})}handleAudio(e){this.emit(e.type,e)}getStream(){var e;return((e=this.destination)==null?void 0:e.stream)||null}play(){this.audio&&this.audio.play().then(()=>{}).catch(e=>{this.emit("error",e)})}pause(){this.audio&&this.audio.pause()}resume(){this.audio&&(this.audio.pause(),this.audio.currentTime=0)}stop(){this.audio&&(this.audio.pause(),this.audio.currentTime=0)}setPosition(e){if(e<0&&e>this.duration()){P.error("Time beyond song duration.");return}this.audio&&(this.audio.currentTime=e)}getPosition(){if(this.audio)return this.audio.currentTime}setVolume(e){if(e>1&&e<0)throw new Error("\u97F3\u91CF\u8D85\u51FA\u9650\u5236");this.audio&&(this.audio.volume=e)}getVolume(){if(this.audio)return this.audio.volume}setPlayBackRate(e){if(e>8&&e<0)throw new Error("\u901F\u7387\u8D85\u51FA\u9650\u5236");this.audio&&(this.audio.playbackRate=e)}getPlayBackRate(){if(this.audio)return this.audio.playbackRate}duration(){return this.audio&&this.audio.duration||0}loop(e){if(e===void 0)return this.audio&&this.audio.loop;this.audio&&typeof e=="boolean"&&(this.audio.loop=e)}};var ls=class{constructor({log:t}){p(this,"audioContext",null);p(this,"destination",null);p(this,"localAudioTrack",null);p(this,"localScreenAudioTrack",null);p(this,"audioTrackStreamSource",null);p(this,"screenAudioTrackStreamSource",null);p(this,"musicList",[]);p(this,"hasMusic",!1);p(this,"mixedMusicMap",new Map);p(this,"cacheMusicMap",new Map);p(this,"_log");this._log=t,this.initAudioContext()}get hasScreenAudioTrack(){return this.localScreenAudioTrack!==null}get hasAudioTrack(){return this.localAudioTrack!==null}isNeedToUseDestination(){return this.hasMusic&&this.localAudioTrack||this.localAudioTrack&&this.localScreenAudioTrack}get mediaStreamTrack(){var t,e;return this.isNeedToUseDestination()?this.destination.stream.getAudioTracks()[0]:((t=this.localAudioTrack)==null?void 0:t.mediaTrack)||((e=this.localScreenAudioTrack)==null?void 0:e.mediaTrack)}addMusicSource(t){return T(this,null,function*(){this.initAudioContext();let{id:e,url:r,loop:n,volume:s}=t;if(this.mixedMusicMap.has(e))return;let o;this.cacheMusicMap.has(e)?o=this.cacheMusicMap.get(e).audioSource:o=new Jr(t);let{stream:a}=o.destination,c=document.createElement("audio");c.srcObject=a,o.play(),yield c.play(),this._log.info(`start mix audio ${e} success.`);let d=this.audioContext.createMediaStreamSource(a),u=this.audioContext.createGain();d.connect(u),u.connect(this.destination),this.musicList.push(e),this.mixedMusicMap.set(e,{audioSource:o,streamSource:d,gainNode:u,audioPlayer:c}),this.cacheMusicMap.set(e,{audioSource:o}),this.hasMusic=!0})}addAudioTrack(t){this.initAudioContext(),!!(t!=null&&t.mediaStream)&&this.localAudioTrack!==t&&(this.localAudioTrack=t,this.audioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this.audioTrackStreamSource.connect(this.destination))}addScreenAudioTrack(t){this.initAudioContext(),!!(t!=null&&t.mediaStream)&&this.localScreenAudioTrack!==t&&(this.localScreenAudioTrack=t,this.screenAudioTrackStreamSource=this.audioContext.createMediaStreamSource(t.mediaStream),this.screenAudioTrackStreamSource.connect(this.destination))}removeAudioTrackSource(t){var e,r;t==="main"&&((e=this.audioTrackStreamSource)==null||e.disconnect(),this.audioTrackStreamSource=null,this.localAudioTrack=null),t==="screen"&&((r=this.screenAudioTrackStreamSource)==null||r.disconnect(),this.screenAudioTrackStreamSource=null,this.localScreenAudioTrack=null)}removeMusicSource({id:t}){if(this.mixedMusicMap.has(t)){let{audioSource:e,streamSource:r,gainNode:n,audioPlayer:s}=this.mixedMusicMap.get(t);r.disconnect(),n.disconnect(),s.pause(),s.srcObject=null,e.stop(),this.mixedMusicMap.delete(t),this.musicList=this.musicList.filter(o=>o!==t),this.musicList.length===0&&(this.hasMusic=!1)}}destroyAllMusic(){this.musicList.forEach(t=>{this.removeMusicSource({id:t})})}initAudioContext(){if(this.audioContext)return;this.audioContext=Pt(),this.destination=this.audioContext.createMediaStreamDestination();let t=this.audioContext,e=()=>{t.state==="suspended"?(t.resume(),document.addEventListener("click",e)):t.state==="interrupted"?t.resume():document.removeEventListener("click",e)};document.addEventListener("click",e),t.onstatechange=()=>{P.info(`audioManager context state: ${t.state}`),e()}}destroy(){this.removeAudioTrackSource("main"),this.removeAudioTrackSource("aux"),this.audioContext.close()}};var _R=h(_(),1);var aR=h(_(),1);var pa=class extends Si{constructor(e,r,n){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:n});this.room=e;this.user=r;p(this,"userId");p(this,"tinyId");p(this,"isRemote",!0);this.tinyId=r.tinyId,this.userId=r.userId}play(e,r){return this.hasFlag?super.play(e,r):(this.isPlayCalled=!0,this.container=e,e&&this.player.setContainer(e),Promise.resolve())}setMute(e){return this.hasFlag&&super.setMute(e)}setMediaStreamTrack(e){super.setMediaStreamTrack(e),this.mediaTrack&&this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.mediaTrack)}get isSubscribed(){return this.state===pa.STATE_SUBSCRIBE}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}subscribe(e=!0){this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack),this.updatePlayingState(!0),e&&C.emit(I.REMOTE_TRACK_SUBSCRIBED,{track:this})}unsubscribe(e=!0){this.player.setTrack(null),this.updatePlayingState(!1),e&&C.emit(I.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}onFlagChanged(){this.updatePlayingState(this.hasFlag),this.mediaTrack&&this.hasFlag&&this.player.setTrack(this.mediaTrack)}},ot=pa;p(ot,"STATE_SUBSCRIBE","subscribe"),G([$e(ue.INIT,ot.STATE_SUBSCRIBE)],ot.prototype,"subscribe",1),G([$e(ot.STATE_SUBSCRIBE,ue.INIT)],ot.prototype,"unsubscribe",1);var ps=class extends ot{constructor(e,r){super(e,r,1);p(this,"volume",0);p(this,"mediaType",1);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0})}getAudioLevel(){return this.volume||super.getAudioLevel()}get hasFlag(){return this.user.muteState.hasAudio&&!this.user.muteState.audioMuted}isFlagChanged(e){let r=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==r}};var RR=h(_(),1);var Yr=class extends ot{constructor(e,r,n=4){super(e,r,n);p(this,"mediaType",4);p(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0})}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let r=e.hasVideo&&!e.videoMuted;return this.hasFlag!==r}},ms=class extends Yr{constructor(e,r){super(e,r,2);p(this,"mediaType",2);p(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let r=e.hasAuxiliary;return this.hasFlag!==r}};var WA=h(_(),1);var NA=h(_());var vR=h(_());function ge(...i){}var Wh=i=>i();function ha(){this.dispose()}var Kh=()=>typeof __FASTRX_DEVTOOLS__!="undefined",jh=1,Ut=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new ma(t,this,this.streamId++);return at.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Xr=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=ge,this.error=ge,this.next=ge,this.dispose=ge,this.subscribe=ge,this.doDefer()}subscribe(t){return t instanceof Ut?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Wh),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Y=class extends Xr{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}};function xu(i,...t){return t.reduce((e,r)=>r(e),i)}function Vt(i,t,e){if(Kh()){let r=Object.defineProperties(Object.setPrototypeOf(i,Ut.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});at.create(r);for(let n=0;n<e.length;n++){let s=e[n];typeof s=="function"&&s instanceof Ut&&at.addSource(r,s)}return r}return i}function q(i,t){return function(...e){return r=>{if(r instanceof Ut){let n=Vt(s=>{let o=new i(s,...e);o.sourceId=n.id,o.subscribe(r)},t,arguments);return n.source=r,at.pipe(n),n}else return n=>r(new i(n,...e))}}}function ei(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var ma=class extends Y{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{at.defer(this.source,this.id)})}next(t){at.next(this.source,this.id,t),this.sink.next(t)}complete(){at.complete(this.source,this.id),this.sink.complete()}error(t){at.complete(this.source,this.id,t),this.sink.error(t)}},at={addSource(i,t){ei("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){ei("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){ei("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){ei("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){ei("defer",{id:i.id,streamId:t})},pipe(i){ei("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){ei("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=jh++),ei("create",{name:i.toString(),id:i.id})}},hs=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var xR=h(_());var PR=h(_());var _a=class extends Xr{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function _s(){return i=>{let t=new _a(i);if(i instanceof Ut){let e=Vt(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,at.pipe(e),e}return Vt(t.add.bind(t),"share",arguments)}}function Jh(...i){return Vt(t=>{let e=i.length,r=e,n=e,s=new Array(e),o=()=>{--n===0&&t.complete()},a=(c,d)=>{let u=new Y(t);u.next=l=>{--r===0?(u.next=m=>{s[d]=m,t.next(s)},u.next(l)):s[d]=l},u.complete=o,u.subscribe(c)};i.forEach(a)},"combineLatest",arguments)}var fa=class extends Y{constructor(t,...e){super(t);let r=new Y(this.sink);r.next=n=>this.buffer=n,r.complete=ge,r.subscribe(Jh(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},NR=q(fa,"withLatestFrom"),Ea=class extends Y{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(t=>this.sink.next(t)),super.complete()}},DR=q(Ea,"bufferCount"),Ta=class extends Y{constructor(t,e){super(t),this.buffer=[];let r=new Y(t);r.next=n=>{t.next(this.buffer),this.buffer=[]},r.complete=ge,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},OR=q(Ta,"buffer");function Sa(i){let t=arguments,e=_s()(Vt(r=>{e.next=n=>r.next(n),e.complete=()=>r.complete(),e.error=n=>r.error(n),i&&r.subscribe(i)},"subject",t));return e.next=ge,e.complete=ge,e.error=ge,e}function Uu(i){return Vt(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}var tA=h(_());var wR=h(_());var Ia=class extends Y{constructor(t,e,r){super(t),this.f=e;let n=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=n,this.resetNext()}:(this.acc=r,this.complete=n)}next(t){this.acc=this.f(this.acc,t)}},Yh=q(Ia,"reduce");var ga=class extends Y{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Xh=q(ga,"filter"),Ra=class extends Y{next(t){}},GR=q(Ra,"ignoreElements"),Aa=class extends Y{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},qh=q(Aa,"take"),Ca=class extends Y{constructor(t,e){super(t);let r=new Y(t);r.next=()=>t.complete(),r.complete=ha,r.subscribe(e)}},WR=q(Ca,"takeUntil"),va=class extends Y{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},zh=q(va,"takeWhile");var ya=class extends Y{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},KR=q(ya,"skip"),Na=class extends Y{constructor(t,e){super(t),t.next=ge;let r=new Y(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=ha,r.subscribe(e)}},jR=q(Na,"skipUntil"),Da=class extends Y{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},Qh=q(Da,"skipWhile"),Zh={leading:!0,trailing:!1},Oa=class extends Y{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},ba=class extends Y{constructor(t,e,r=Zh){super(t),this.durationSelector=e,this.config=r,this._throttle=new Oa(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=ge,this._throttle.complete(),super.complete()}},JR=q(ba,"throttle");var Pa=class extends Y{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ma=class extends Y{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Pa(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},YR=q(Ma,"debounce");var La=class extends Y{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},XR=q(La,"elementAt");var ka=class extends Y{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},qR=q(ka,"findIndex"),xa=class extends Y{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},zR=q(xa,"first"),Ua=class extends Y{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},QR=q(Ua,"last"),Va=class extends Y{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},ZR=q(Va,"every");var SA=h(_());var wa=class extends Y{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=n=>{this.acc=n,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},nA=q(wa,"scan"),Ba=class extends Y{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},sA=q(Ba,"pairwise"),$a=class extends Y{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Vu=q($a,"map");var Xi=class extends Y{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},qi=class extends Y{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},fs=class extends Xi{},Es=class extends qi{next(t){this.subInner(t,fs),this.next=e=>{this.currentSink.dispose(),this.subInner(e,fs)}}},e_=q(Es,"switchMap");function gs(i){return(t,e)=>i(()=>t,e)}var oA=gs(q(Es,"switchMapTo")),Ha=class extends Xi{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Ts=class extends qi{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Ha),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},aA=q(Ts,"concatMap"),cA=gs(q(Ts,"concatMapTo")),Fa=class extends Xi{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Ss=class extends qi{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,Fa),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},dA=q(Ss,"mergeMap"),uA=gs(q(Ss,"mergeMapTo")),Ga=class extends Xi{dispose(){this.context.resetNext(),super.dispose()}},Is=class extends qi{next(t){this.next=ge,this.subInner(t,Ga)}},lA=q(Is,"exhaustMap"),pA=gs(q(Is,"exhaustMapTo")),Wa=class extends Y{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=Sa(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},mA=q(Wa,"groupBy"),Ka=class extends Y{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},hA=q(Ka,"timeInterval"),ja=class extends Y{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},_A=q(ja,"bufferTime"),Ja=class extends Y{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:n}=e;super.next(n),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},fA=q(Ja,"delay"),Ya=class extends Y{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},EA=q(Ya,"catchError");var vA=h(_());var Xa=class extends Y{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},RA=q(Xa,"tap"),qa=class extends Y{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new hs(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},AA=q(qa,"timeout");var FA=xu(Uu(250),Vu(()=>performance.now()),_s());var ZA=h(_(),1);var zi=new Map;C.on(I.JOIN_SUCCESS,({room:i})=>{Ce(i.userId,{eventId:32788,eventDesc:"join room"})});C.on(I.LEAVE_START,({room:i})=>{Ce(i.userId,{eventId:32789,eventDesc:"leave room"})});C.on(I.LOCAL_TRACK_PUBLISHED,({track:i})=>{i.room&&Ce(i.room.userId,{eventId:i.kind===f.AUDIO?32769:32768,eventDesc:`publish ${i.kind}`})});C.on(I.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{i.room&&Ce(i.room.userId,{eventId:i.kind===f.AUDIO?32771:32770,eventDesc:`unpublish ${i.kind}`})});C.on(I.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===f.AUDIO?Ce(i.room.userId,{eventId:i.isRemote?32785:32772,eventDesc:"mute audio",remoteUserId:i.isRemote?i.userId:void 0}):Ce(i.room.userId,{eventId:i.isRemote?32784:32773,eventDesc:"mute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(I.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===f.AUDIO?Ce(i.room.userId,{eventId:i.isRemote?32787:32774,eventDesc:"unmute audio",remoteUserId:i.isRemote?i.userId:void 0}):Ce(i.room.userId,{eventId:i.isRemote?32786:32775,eventDesc:"unmute video",remoteUserId:i.isRemote?i.userId:void 0}))});C.on(I.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.mediaType===1&&Ce(i.room.userId,{eventId:32777,eventDesc:`${f.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&Ce(i.room.userId,{eventId:32776,eventDesc:`${f.SUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&Ce(i.room.userId,{eventId:32803,eventDesc:`${f.SUBSCRIBE} ${f.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(I.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.mediaType===1&&Ce(i.room.userId,{eventId:32779,eventDesc:`${f.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===4&&Ce(i.room.userId,{eventId:32778,eventDesc:`${f.UNSUBSCRIBE} ${i.kind}`,remoteUserId:i.userId}),i.mediaType===8&&Ce(i.room.userId,{eventId:32804,eventDesc:`${f.UNSUBSCRIBE} ${f.SMALL_VIDEO}`,remoteUserId:i.userId})});C.on(I.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&Ce(i.room.userId,{eventId:i.kind===f.VIDEO?32780:32781,eventDesc:`switch ${i.kind===f.VIDEO?"camera":"microphone"}`})});C.on(I.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&Ce(i.room.userId,{eventId:i.kind===f.VIDEO?32782:32783,eventDesc:`replace ${i.kind}`})});C.on(I.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r,n;switch(e){case"CONNECTED":t==="RECONNECTING"?(r=32795,n="signal reconnected"):(r=32791,n="signal connected");break;case"DISCONNECTED":t==="RECONNECTING"?(r=32796,n="signal reconnect fail"):(r=32790,n="signal disconnected");break;case"RECONNECTING":r=32794,n="signal reconnecting";break}r&&n&&Ce(i.userId,{eventId:r,eventDesc:n})});C.on(I.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let n=!!r,s=n?"downlink":"uplink",o,a;switch(e){case"CONNECTED":t==="RECONNECTING"?(o=n?32801:32798,a=`${s} reconnected`):(o=n?32793:32792,a=`${s} connected`);break;case"DISCONNECTED":t==="RECONNECTING"&&(o=n?32802:32799,a=`${s} reconnect fail`);break;case"RECONNECTING":o=n?32800:32797,a=`${s} reconnecting`;break}o&&a&&Ce(i.userId,{eventId:o,eventDesc:a,remoteUserId:r})});function Ce(i,t){let e=ie(w({},t),{timestamp:Ir()});zi.has(i)?zi.get(i).push(e):zi.set(i,[e])}function wu(i){if(zi.has(i)){let t=zi.get(i).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,str_event_json:e.eventDesc}));return zi.delete(i),t}return[]}var uC=h(_(),1);var TC=h(_(),1);var Bu=h(rt(),1);var As=class extends Bu.EventEmitter{constructor(e,r,n="userId"){super();this.mySelfId=e;this._log=r;this.key=n;p(this,"userMap",new Map);p(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let r=e[this.key],{userId:n,tinyId:s,role:o}=e;if(this.userMap.has(r))return;let a={userId:n,tinyId:s,role:o===20?"anchor":"audience"};this.userMap.set(r,a),this.emit("1",a)}deleteUser(e,r){let n=this.userMap.get(e);if(!n)return;let s=`peer leave [${e}]`;N(r)||(s+=`:${Cd[r]}`),this._log.info(s);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.muteState,flag:0})}this.userMap.delete(e),this.emit("2",n.userId)}setUserList(e){this.userMap.forEach(r=>{e.findIndex(n=>n[this.key]===r[this.key])<0&&this.deleteUser(r[this.key],0)}),e.forEach(r=>{!this.userMap.has(r[this.key])&&r[this.key]!==this.mySelfId&&this.addUser(r)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){!this.remotePublishedUserMap.has(e)||this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(r=>{let n=r[this.key];if(e.findIndex(s=>s[this.key]===r[this.key])<0){this._log.info(`remote [${n}] unpublish`);let s=r.muteState;r.flag=0,this.emit("5",r.userId),this.deleteRemotePublishedUser(n),this.emit("6",{prevMuteState:s,muteState:r.muteState,flag:0})}}),e.forEach(r=>{var u;let n=r[this.key];if(n===this.mySelfId)return;let{flag:s,userId:o,tinyId:a}=r,c=Bi(s,o),d=(u=this.remotePublishedUserMap.get(n))==null?void 0:u.muteState;if(d){let l=this.remotePublishedUserMap.get(n);l&&l.flag!==s&&(l.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(l.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",r),this.emit("6",{prevMuteState:Bi(0,o),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};var ev=h(_());var zr={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear"};var Av=h(_());var rv=h(_(),1);var Qr=(n=>(n[n.Idle=0]="Idle",n[n.Start=1]="Start",n[n.Update=2]="Update",n[n.Stop=3]="Stop",n))(Qr||{}),ke=class extends Error{};function t_(i,t){let e=[];return Et(e,i),Et(e,t),e}var Qi=class{constructor(t,e){this.instance=t;this.group=e;this.currentArgs=[];this.state=0;this.started=!1;this.abortStart=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=t_;let r=Qi.instances.get(t);r?r.set(e,this):Qi.instances.set(t,new Map([[e,this]]))}static get(t,e){let r=Qi.instances.get(t);return r&&r.get(e)||new Qi(t,e)}action(t,e,r){let n=this.resolve.bind(this),s=this.reject.bind(this),o=(...a)=>(this.state=t,this.currentArgs=a,e(...a).then(n,s));switch(this.state){case 0:return this.started&&t===1?Promise.reject(new ke("already started")):!this.started&&t===2?Promise.reject(new ke("not started")):o(...r);case 1:if(t===3&&this.abortStart)return o(...r);default:return new Promise((a,c)=>{let{group:d}=this,u={type:t,action(){return o(...this.args).then(a,c)},args:r,resolve:a,reject:c},l=this.cacheOp(u);l?u.reject(l):this.ops.push(u)})}}cacheOp(t){if(this.empty)switch(this.state){case 1:case 2:if(t.type===1)return new ke("already start");break;case 3:if(t.type!==1)return new ke(`${Qr[t.type]} not allowed when stopping`);break}else switch(t.type){case 3:if(this.rejectOther(),this.state===3)return new ke("already stop");break;case 2:switch(this.lastOpType){case 2:t.args=this.mergeUpdate(this.lastOp.args,t.args),this.abortLast("merge");break;case 3:return new ke(`${Qr[t.type]} not allowed after stop`)}break;case 1:switch(this.lastOpType){case 2:return new ke(`${Qr[t.type]} not allowed after update`);case 1:this.abortLast("duplicate start");break;case 3:if(this.startSame(this.currentArgs,t.args))return this.abortLast("keep start"),new ke("already start")}}}rejectOther(){let t=new ke("keep stop");for(;!this.empty;)this.ops.shift().reject(t)}resolve(t){return this.state===1?this.started=!0:this.state===3&&(this.started=!1),this.empty?this.state=0:this.ops.shift().action(),t}reject(t){throw!this.empty&&this.state===1&&this.ops.shift().reject(new ke("start failed")),this.empty?this.state=0:this.ops.shift().action(),t}abortLast(t="ignore"){this.ops.pop().reject(new ke(t))}get empty(){return this.ops.length===0}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}},ti=Qi;ti.instances=new WeakMap;var _v=h(_());var sv=h(_()),te={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},ii=(D=>(D[D.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",D[D.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",D[D.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",D[D.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",D[D.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",D[D.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",D[D.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",D[D.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",D[D.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",D[D.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",D[D.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",D[D.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",D[D.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",D[D.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",D[D.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",D[D.MIX_PARAMS_USER_Z_ORDER=5015]="MIX_PARAMS_USER_Z_ORDER",D[D.MIX_PARAMS_VIDEO_FRAMERATE=5016]="MIX_PARAMS_VIDEO_FRAMERATE",D[D.MIX_PARAMS_VIDEO_GOP=5017]="MIX_PARAMS_VIDEO_GOP",D[D.MIX_PARAMS_AUDIO_BITRATE=5018]="MIX_PARAMS_AUDIO_BITRATE",D[D.MIX_PARAMS_NOT_SELF=5019]="MIX_PARAMS_NOT_SELF",D[D.MIX_PARAMS_USER_STREAM=5020]="MIX_PARAMS_USER_STREAM",D[D.INVALID_OPERATION=5100]="INVALID_OPERATION",D[D.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",D[D.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",D[D.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",D[D.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",D[D.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",D[D.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",D[D.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",D[D.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",D[D.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",D[D.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",D[D.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",D[D.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",D[D.DEVICE_ERROR=5300]="DEVICE_ERROR",D[D.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",D[D.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",D[D.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",D[D.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",D[D.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",D[D.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",D[D.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",D[D.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",D[D.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",D[D.SERVER_ERROR=5400]="SERVER_ERROR",D[D.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",D[D.OPERATION_FAILED=5500]="OPERATION_FAILED",D[D.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",D[D.REJOIN_FAILED=5502]="REJOIN_FAILED",D[D.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",D[D.OPERATION_ABORT=5998]="OPERATION_ABORT",D[D.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",D))(ii||{});var uv=h(_());function Hu({code:i,params:t,enableDocLink:e=!1}){let r="",n,s=ii[i];try{n=$u[s]}catch(o){n=$u.UNKNOWN_ERROR}return oe(n)?r=n(t):re(n)&&(r=n),e&&(r+=" doc:"),r}var $u={INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${n}' must be type of ${s} when calling ${e}(), received type: ${_e(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let n=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${n}' must be instanceof ${s} when calling ${e}(), received type: ${_e(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_STREAM_TYPE:({fnName:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,MIX_PARAMS_USER_Z_ORDER({key:i}){return`'${i}' is required and must be between 1 and 15.`},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_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_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not exist.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) did not publish ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' you are calling, please check the API documentation.`},NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture and publish streams, please use the https protocol.",NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got server exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=gi(i),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`\u2018${i}\u2019 failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}};function gi(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Zi=class extends Error{constructor({code:e,extraCode:r,message:n="",messageParams:s,fnName:o="",originError:a}){let c;n?c=n:c=Hu({code:r||e,params:w({fnName:o,error:a},s)});super(c);p(this,"name","RtcError");p(this,"code");p(this,"extraCode");p(this,"functionName");p(this,"message");p(this,"originError");this.name=ii[e],this.code=e,this.extraCode=r,this.functionName=o,this.originError=a,this.message=c}static convertFrom(e,r,n){let s=e;if(e instanceof V){let{stack:o}=e,a={code:te.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case M.INVALID_PARAMETER:a.code=te.INVALID_PARAMETER;break;case M.INVALID_OPERATION:a.code=te.INVALID_OPERATION;break;case M.NOT_SUPPORTED:case M.NOT_SUPPORTED_H264:a.code=te.ENV_NOT_SUPPORTED,e.getCode()===M.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Be.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case M.DEVICE_NOT_FOUND:case M.DEVICE_AUTO_RECOVER_FAILED:a.code=te.DEVICE_ERROR;break;case M.JOIN_ROOM_FAILED:a.messageParams={fnParams:n};case M.SERVER_TIMEOUT:case M.SWITCH_ROLE_FAILED:a.code=te.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case M.API_CALL_ABORTED:a.code=te.OPERATION_ABORT;break;case M.INITIALIZE_FAILED:a.code=5300,a.extraCode=i_(e.name);break;case M.UNKNOWN:break;default:a.code=te.OPERATION_FAILED}s=new Zi(a),o&&(s.stack+=o.substr(o.indexOf(`
91
+ `)))}else s=new Zi({code:te.UNKNOWN_ERROR,fnName:r,originError:e});return s}};function i_(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var z=Zi;var za=(i,t)=>{if(t instanceof ke){let{stack:e}=t;t=new z({code:te.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
92
+ `)))}throw t};function Ri(i,t){return de((e,r)=>function(...n){let s=ti.get(this,typeof i=="string"?i:i(...n));return t&&(s.startSame=t.bind(this)),s.action(1,e.bind(this),n).catch(za.bind(null,r))})}function er(i,t){return de((e,r)=>function(...n){let s=ti.get(this,typeof i=="string"?i:i(...n));return t&&(s.mergeUpdate=t.bind(this)),s.action(2,e.bind(this),n).catch(za.bind(null,r))})}function Ai(i,t=!1){return de((e,r)=>function(...n){let s=ti.get(this,typeof i=="string"?i:i(...n));return s.abortStart=t,s.action(3,e.bind(this),n).catch(za.bind(null,r))})}function Qa(i,t=!1){return de((e,r)=>function(...n){let s=ti.get(this,typeof i=="string"?i:i(...n));return s.started=!1,e.call(this,...n)})}var Vv=h(_());var vv=h(_()),Fu={ENTER_ROOM:"enterRoom",SWITCH_ROLE:"switchRole",START_LOCAL_AUDIO:"startLocalAudio",UPDATE_LOCAL_AUDIO:"updateLocalAudio",START_LOCAL_VIDEO:"startLocalVideo",UPDATE_LOCAL_VIDEO:"updateLocalVideo",START_SCREEN_SHARE:"startScreenShare",UPDATE_SCREEN_SHARE:"updateScreenShare",START_REMOTE_VIDEO:"startRemoteVideo",UPDATE_REMOTE_VIDEO:"updateRemoteVideo",STOP_REMOTE_VIDEO:"stopRemoteVideo",MUTE_REMOTE_AUDIO:"muteRemoteAudio",DESTROY:"destroy"};var Gu={type:b.Object,properties:{cameraId:{type:b.String},useFrontCamera:{type:b.Boolean},fillMode:{type:b.String,values:["contain","cover","fill"]},mirror:{type:b.Boolean},small:{properties:{width:{type:b.Number},height:{type:b.Number},frameRate:{type:b.Number},bitrate:{type:b.Number}}},videoTrack:{instanceOf:MediaStreamTrack}}},Wu={type:b.Object,properties:{systemAudio:{type:b.Boolean},fillMode:{type:b.String,values:["contain","cover","fill"]},profile:{type:[b.String,b.Object],properties:{width:{type:b.Number},height:{type:b.Number},frameRate:{type:b.Number},bitrate:{type:b.Number}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},tr={type:[b.String,HTMLElement,null],validate(i,t,e){if(re(i)){let r=document.getElementById(i);if(!r)throw new z({code:te.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}});if(!(r instanceof HTMLElement))throw new z({code:te.INVALID_PARAMETER,extraCode:5010,fnName:e,messageParams:{key:t,type:_e(r)}})}}},Ku={name:"userId",required:!0,type:b.String},ju={type:b.Object,properties:{microphoneId:{type:b.String},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:b.Number,min:0,max:100},earMonitorVolume:{type:b.Number,min:0,max:100},echoCancellation:{type:b.Boolean},autoGainControl:{type:b.Boolean},noiseSuppression:{type:b.Boolean}}};function Ju(i,t,e,r){if(!/^[A-Za-z\d_-]*$/.test(i))throw new z({code:te.INVALID_PARAMETER,extraCode:5011,fnName:e,messageParams:{key:t}})}function Yu(i,t,e,r){if(re(i)){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i))throw new z({code:te.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else if(!(/^[1-9]\d*$/.test(String(i))&&i<4294967295))throw new z({code:te.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}function Za(i,t){if(!i)throw new z({code:te.INVALID_OPERATION,extraCode:5101,fnName:t})}function Xu(i,t,e){if(!i)throw new z({code:te.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var ri={type:b.Number,notLessThanZero:!0},r_={enterRoom:{name:"EnterRoomConfig",type:b.Object,required:!0,validate(i,t){if(this._room.isJoined)throw new z({code:te.INVALID_OPERATION,extraCode:5104,fnName:Fu.ENTER_ROOM})},properties:{sdkAppId:{required:!0,type:b.Number,allowEmpty:!1},userId:{required:!0,type:b.String,allowEmpty:!1},userSig:{required:!0,type:b.String,allowEmpty:!1},scene:{type:b.String,values:["live","rtc"]},role:{type:b.String,values:["audience","anchor"]},roomId:{required:!0,type:[b.String,b.Number],validate:Yu},proxy:{type:[b.Object,b.String],properties:{websocketProxy:{type:b.String},turnServer:{type:[b.Object,b.Array],properties:{url:{required:!0,type:b.String},username:{type:b.String},credential:{type:b.String},credentialType:{type:b.String,values:["password"]}}},loggerProxy:{type:b.String},webtransportProxy:{type:b.String}}},enableAutoPlayDialog:{type:b.Boolean},streamId:{type:b.String},userDefineRecordId:{type:b.String}}},startLocalVideo:{name:"LocalVideoConfig",type:b.Object,properties:{view:tr,publish:{type:b.Boolean},option:Gu}},updateLocalVideo:{name:"updateLocalVideoConfig",type:b.Object,required:!0,properties:{view:ie(w({},tr),{required:!1}),publish:{type:b.Boolean},mute:{type:b.Boolean},option:Gu}},startLocalAudio:{name:"LocalAudioConfig",type:b.Object,properties:{publish:{type:b.Boolean},option:ju}},updateLocalAudio:{name:"updateLocalAudioConfig",type:b.Object,required:!0,properties:{publish:{type:b.Boolean},mute:{type:b.Boolean},option:ju}},startScreenShare:{name:"ScreenShareConfig",type:b.Object,properties:{view:tr,publish:{type:b.Boolean},option:Wu}},updateScreenShare:{name:"updateScreenShareConfig",type:b.Object,required:!0,properties:{view:tr,publish:{type:b.Boolean},option:Wu}},muteRemoteAudio:[Ku,{name:"mute",required:!0,type:b.Boolean}],setRemoteAudioVolume:[Ku,{name:"volume",required:!0,type:b.Number,min:0,max:100}],startRemoteVideo:{name:"startRemoteVideoConfig",type:b.Object,required:!0,properties:{view:tr,userId:{type:b.String,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:b.Object,properties:{fillMode:{type:b.String,values:["contain","cover","fill"]},mirror:{type:b.Boolean}}}},validate(i,t,e){Za(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Xu(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new z({code:te.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:b.Object,required:!0,properties:{view:ie(w({},tr),{required:!1}),userId:{type:b.String,required:!0},streamType:{values:["main","sub"],required:!0},option:{type:b.Object,properties:{fillMode:{type:b.String,values:["contain","cover","fill"]},mirror:{type:b.Boolean}}}},validate(i,t,e){Za(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Xu(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new z({code:te.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:b.Object,required:!0,properties:{userId:{type:b.String,required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&N(i.streamType))throw new z({code:te.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){Za(this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:b.Number},{name:"enableInBackground",type:b.Boolean}],startMixTranscode:{name:"config",required:!0,type:b.Object,properties:{mode:{type:b.String,values:["preset-layout","manual"]},streamId:{type:b.String,validate:Ju},videoWidth:ri,videoHeight:ri,videoBitrate:ie(w({},ri),{allowEmpty:!1}),videoFramerate:{type:b.Number,validate(i,t,e,r){if(i<=0||i>30)throw new z({code:te.INVALID_PARAMETER,extraCode:5016,fnName:e})}},videoGop:{type:b.Number,validate(i,t,e,r){if(i<1||i>8)throw new z({code:te.INVALID_PARAMETER,extraCode:5017,fnName:e})}},audioSampleRate:ri,audioBitrate:{type:b.Number,validate(i,t,e,r){if(i<32||i>192)throw new z({code:te.INVALID_PARAMETER,extraCode:5018,fnName:e})}},audioChannels:{type:b.Number,values:[1,2]},backgroundColor:{type:b.Number},backgroundImage:{type:b.String},mixUsers:{required:!0,type:b.Array,arrayItem:{require:!0,type:b.Object,properties:{userId:{required:!0,type:b.String},roomId:{type:[b.String,b.Number],validate:Yu},pureAudio:{type:b.Boolean},width:ri,height:ri,locationX:ri,locationY:ri,zOrder:{type:b.Number},streamType:{values:["main","sub"]},renderMode:{type:b.Number,values:[0,1,2,4]}}}}},validate(i,t,e,r){let n=0,s=0,{mixUsers:o}=i,a=[];if(o.forEach((c,d)=>{if(a.push(c.userId),!c.pureAudio){if(!c.zOrder||c.zOrder<1||c>15)throw new z({code:te.INVALID_PARAMETER,extraCode:5015,fnName:e,messageParams:{key:`config.mixUsers[${d}].zOrder`}});c.width+c.locationX>n&&(n=c.width+c.locationX),c.height+c.locationY>s&&(s=c.height+c.locationY)}}),a.indexOf(this._room.userId)<0)throw new z({code:te.INVALID_PARAMETER,extraCode:5019,fnName:e});if(i.videoWidth<n||i.videoHeight<s)throw new z({code:te.INVALID_PARAMETER,extraCode:5020,fnName:e})}},startPublishCDNStream:{name:"options",required:!1,properties:{streamId:{type:b.String,validate:Ju},streamType:{values:["main","sub"]},appId:{type:b.Number,allowEmpty:!1},bizId:{type:b.Number,allowEmpty:!1},url:{type:b.String,allowEmpty:!1}}}},be={TRTC:r_};var Fv=h(_());function Zr(i){return i==="sub"?"auxiliary":"main"}function en(i){return i===zr.QOS_PREFERENCE_CLEAR?"detail":i===zr.QOS_PREFERENCE_SMOOTH?"motion":""}var zu="5.0.0-beta";var zv=h(_());function He(...i){return de((t,e)=>function(...r){try{Qu.call(this,i,r,e,this._name)}catch(n){return Promise.reject(n)}return t.apply(this,r)})}function ec(...i){return de((t,e)=>function(...r){try{Qu.call(this,i,r,e,this._name)}catch(n){throw n}return t.apply(this,r)})}function Qu(i,t,e,r){if(Xt(i))for(let n=0;n<i.length;n++)vs.call(this,{rule:i[n],value:t[n],key:i[n].name,fnName:e,className:r});else vs.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function vs({rule:i,value:t,key:e,fnName:r,className:n}){function s(c){return{code:te.INVALID_PARAMETER,extraCode:c,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(N(t)){if(i.required)throw new z(s(5001));if(N(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let c=!1;for(let d=0;d<i.type.length;d++)i.type[d]===null&&t===null&&(c=!0),oe(i.type[d])&&t instanceof i.type[d]&&(c=!0),re(i.type[d])&&_e(t)===i.type[d].toLowerCase()&&(c=!0);if(!c)throw new z({code:te.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(d=>xr(d)?Xn(d):re(d)?d:_e(d))},value:t}})}else if(!N(i.type)&&_e(t)!==i.type)throw new z(s(5002));if(i.allowEmpty===!1){let c=ce(t)&&(t===0||Number.isNaN(t)),d=re(t)&&t.trim()==="";if(c||d)throw new z(s(5003))}if(i.notLessThanZero&&ce(t)&&t<0)throw new z(s(5006));if(!N(i.min)&&ce(t)&&t<i.min)throw new z(s(5007));if(!N(i.max)&&ce(t)&&t>i.max)throw new z(s(5008));if(re(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new z(s(5004))}else if(oe(i.instanceOf)&&!(t instanceof i.instanceOf))throw new z(s(5004));if(i.values&&!i.values.includes(t))throw new z(s(5005));let{properties:o}=i;Yt(o)&&_i(t)&&Object.keys(o).forEach(c=>{vs.call(this,{rule:o[c],value:t&&t[c],key:`${c}`,fnName:r,className:n})});let{arrayItem:a}=i;Yt(a)&&Xt(t)&&t.forEach((c,d)=>{vs.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:r,className:n})}),oe(i.validate)&&i.validate.call(this,t,e,r,n,this)}var sy=h(_());function Re(){return de((i,t)=>function(...e){let r=this._log||loggerManager;e.length>0?r.info(`${t}() ${JSON.stringify(e,(n,s)=>{if(s===e||n in e)return s;try{return s instanceof HTMLElement?`id: ${s.id} type:${_e(s)}`:(JSON.stringify(s),s)}catch(o){return`type:${_e(s)}`}})}`):r.info(`${t}()`);try{let n=i.apply(this,e),s=ee();return Yn(n)?n.then(o=>(r.info(`${t}() success`),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:ee()-s}),o)).catch(o=>{throw o=z.convertFrom.call(this,o,t,e.length===1?e[0]:e),r.error(`${t}() failed ${o}`),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:t,error:o}),o}):(C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:t,cost:ee()-s}),n)}catch(n){throw n=z.convertFrom.call(this,n,t),r.error(`${t}() failed ${n}`),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:t,error:n}),n}})}var dy=h(_(),1);var ys=new WeakMap;function Zu(i,t){return de((e,r)=>function(...n){var a,c;let s=(a=ys.get(this))==null?void 0:a.get(t(...n));s&&s>0&&clearTimeout(s);let o=window.setTimeout(()=>{e.apply(this,n)},i);ys.has(this)?(c=ys.get(this))==null||c.set(t(...n),o):ys.set(this,new Map([[t(...n),o]]))})}var el=0,tc=new Set,We=null;cd(zu);var tn=class extends il.EventEmitter{constructor(e,r){super();p(this,"_room");p(this,"_eventListened",new Set);p(this,"_localVideoTrack",null);p(this,"_localAudioTrack",null);p(this,"_localScreenTrack",null);p(this,"_localScreenAudioTrack",null);p(this,"_localVideoConfig",null);p(this,"_localScreenConfig",null);p(this,"_localAudioConfig",null);p(this,"_remoteVideoConfigMap",new Map);p(this,"_remoteAudioConfigMap",new Map);p(this,"_remoteAudioMuteMap",new Map);p(this,"_log",P.createLogger({id:`t${el}`}));this._room=new e(w({logger:this._log,frameWorkType:tn.frameWorkType},r)),this._room.on("audio-volume",n=>{!n.find(s=>s.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(X.AUDIO_VOLUME,{result:n.sort((s,o)=>o.volume-s.volume)})}),this.on(X.REMOTE_AUDIO_UNAVAILABLE,({userId:n})=>{this._stopRemoteAudio({userId:n},!1).catch(()=>{})}),this.on(X.REMOTE_VIDEO_UNAVAILABLE,({userId:n,streamType:s})=>{this._stopRemoteVideo({userId:n,streamType:s},!1).catch(()=>{})}),ze(fe,fe).add("audioInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"add",device:n})}).add("audioInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"remove",device:n})}).add("videoInputAdded",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"add",device:n})}).add("videoInputRemoved",n=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"remove",device:n})}).add("audioOutputAdded",n=>T(this,null,function*(){if(this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"add",device:n}),We&&We.deviceId===Pn){let s=(yield Ji()).find(o=>o.deviceId===Pn);s&&We.groupId!==s.groupId&&(We=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))}})).add("audioOutputRemoved",n=>T(this,null,function*(){this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"remove",device:n});let s=(yield Ji())[0];s&&We&&(We.deviceId===n.deviceId||We.deviceId===Pn&&We.groupId!==s.groupId)&&(We=s,this.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}))})),wo(this,"trtc")}static create(){}static _create(e,r){el+=1,Xd();let n=new tn(e,r);return tc.add(n),We?n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:We}):Ji().then(s=>{s[0]&&(We=s[0],n.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:s[0]}))}),n}enterRoom(e){return T(this,null,function*(){var c,d;let{scene:r="rtc",enableAutoPlayDialog:n=!0,autoReceiveAudio:s=!0,autoReceiveVideo:o=!0}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!re(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=n,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=o;let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,role:e.role==="audience"?21:20,roomId:0,strRoomId:"",businessInfo:e.businessInfo||null,streamId:e.streamId||null,userDefineRecordId:e.userDefineRecordId||null};re(e.roomId)?(a.strRoomId=e.roomId,this._room.useStringRoomId=!0):a.roomId=e.roomId,ze(this,this._room).add("peer-join",u=>{let{userId:l}=u;this.emit(X.REMOTE_USER_ENTER,{userId:l})}).add("peer-leave",u=>{this.emit(X.REMOTE_USER_EXIT,{userId:u})}).add("banned",u=>{this._exitRoom().then(()=>{this.emit(X.KICKED_OUT,{reason:u.reason})})}).add("error",u=>{this._exitRoom().then(()=>{this.emit(X.ERROR,z.convertFrom(u))})}).add("signal-connection-state-changed",u=>{this.emit(X.CONNECTION_STATE_CHANGED,u)}).add("network-quality",u=>{this.emit(X.NETWORK_QUALITY,u)}).add("remote-published",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(m=>{ze(m,m).add("player-state-changed",S=>{let E=ie(w({},S),{userId:u.userId});m.kind===f.VIDEO&&(E.streamType=Zr(m.streamType)),this.emit(m.kind===f.AUDIO?X.AUDIO_PLAY_STATE_CHANGED:X.VIDEO_PLAY_STATE_CHANGED,E)}).add("error",S=>{S.getCode()===M.PLAY_NOT_ALLOWED&&this.emit(X.AUTOPLAY_FAILED)})})}).add("remote-unpublished",u=>{[u.remoteAudioTrack,u.remoteVideoTrack,u.remoteAuxiliaryTrack].forEach(m=>{Le(m)})}).add("remote-publish-state-changed",({prevMuteState:u,muteState:l})=>{let{userId:m}=l,S=this._room.remotePublishedUserMap.get(m),E=u.audioAvailable,y=u.videoAvailable,{audioAvailable:B,videoAvailable:x}=l;B||this._remoteAudioConfigMap.delete(m),x||this._remoteVideoConfigMap.delete(`${m}_${"main"}`),l.hasAuxiliary||this._remoteVideoConfigMap.delete(`${m}_${"sub"}`),E!==B&&this.emit(B?X.REMOTE_AUDIO_AVAILABLE:X.REMOTE_AUDIO_UNAVAILABLE,{userId:m}),y!==x&&this.emit(x?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:m,streamType:"main"}),u.hasAuxiliary!==l.hasAuxiliary&&this.emit(l.hasAuxiliary?X.REMOTE_VIDEO_AVAILABLE:X.REMOTE_VIDEO_UNAVAILABLE,{userId:m,streamType:"sub"})}).add("firewall-restriction",()=>{this.emit(X.ERROR,new z({code:te.OPERATION_FAILED,extraCode:5501}))}),this._handleReceiveMode(),yield this._room.join(a,r,tn.frameWorkType),this._checkTrackToPublish()})}exitRoom(){return T(this,null,function*(){return yield this._exitRoom()})}switchRole(e){return T(this,null,function*(){yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Le(fe),this.removeAllListeners(),this._room.destroy(),tc.delete(this),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare()}startLocalAudio(){return T(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,option:n}=e,s=new xt,o={},a={muted:!0};n&&(N(n.microphoneId)?N(n.audioTrack)||(o.customSource=n.audioTrack):o.deviceId=n.microphoneId,N(n.captureVolume),N(n.profile)||(re(n.profile)?uo[n.profile]&&s.setProfile(uo[n.profile]):s.setProfile(n.profile)),ce(n.earMonitorVolume)&&(a.muted=!(n.earMonitorVolume>0),a.volume=n.earMonitorVolume),N(n.echoCancellation)||(s.profile.echoCancellation=n.echoCancellation),N(n.noiseSuppression)||(s.profile.noiseSuppression=n.noiseSuppression),N(n.autoGainControl)||(s.profile.autoGainControl=n.autoGainControl)),s.on("5",c=>{this.emit(X.ERROR,new z({code:te.DEVICE_ERROR,extraCode:5309,messageParams:{error:c}}))}),s.on("2",c=>{this.emit(X.DEVICE_CHANGED,{type:"microphone",action:"active",device:c})}),s.on("4",c=>{let d;c.error&&(d=z.convertFrom(c.error)),this.emit(X.PUBLISH_STATE_CHANGED,ie(w({},c),{error:d}))}),yield s.capture(o),ze(s,s).add("player-state-changed",c=>{this.emit(X.AUDIO_PLAY_STATE_CHANGED,ie(w({},c),{userId:""}))}),yield this._updateAudioPlayOption({playOption:a,track:s}),r&&this._room.isJoined&&this._room.publish(s).catch(()=>{}),this._localAudioTrack=s,this._localAudioConfig=ie(w({},e),{publish:r})})}updateLocalAudio(e){return T(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:n,option:s}=e,o={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):N(s.audioTrack)||(this._localAudioTrack.setMediaStreamTrack(s.audioTrack),yield this._room.replaceTrack(this._localAudioTrack)),N(s.captureVolume),N(s.earMonitorVolume)||(o.muted=!(s.earMonitorVolume>0),o.volume=s.earMonitorVolume)),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),this._room.isJoined&&!N(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack)),N(n)||this._localAudioTrack.setMute(n),Et(this._localAudioConfig,e)})}stopLocalAudio(){return T(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack)),this._localAudioTrack.stop(),this._localAudioTrack.close(),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return T(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:n=!0,option:s}=e,o=new st,a={},c={};if(s&&(s.cameraId?a.deviceId=s.cameraId:N(s.useFrontCamera)?N(s.videoTrack)||(a.customSource=s.videoTrack):a.facingMode=s.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,N(s.profile)||(re(s.profile)?xi[s.profile]&&o.setProfile(xi[s.profile]):o.setProfile(s.profile)),N(s.fillMode)||(c.objectFit=s.fillMode),N(s.mirror)||(c.mirror=s.mirror),N(s.small)||(ts()?re(s.small)?o.small=xi[s.small]:o.small=s.small:this._log.warn("small stream is not supported"))),o.on("5",d=>{this.emit(X.ERROR,new z({code:te.DEVICE_ERROR,extraCode:5308,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(X.DEVICE_CHANGED,{type:"camera",action:"active",device:d})}),o.on("4",d=>{let u;d.error&&(u=z.convertFrom(d.error)),this.emit(X.PUBLISH_STATE_CHANGED,ie(w({},d),{error:u}))}),yield o.capture(a),(s==null?void 0:s.qosPreference)&&o.mediaTrack){let d=en(s.qosPreference);o.mediaTrack.contentHint=d}ze(o,o).add("player-state-changed",d=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,ie(w({},d),{userId:"",streamType:"main"}))}),yield this._updateVideoPlayOption({view:r,playOption:c,track:o}),n&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localVideoTrack=o,this._localVideoConfig=ie(w({},e),{view:r,publish:n})})}updateLocalVideo(e){return T(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:n,mute:s,option:o}=e,a={};if(o&&(o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):N(o.useFrontCamera)?N(o.videoTrack)||(this._localVideoTrack.setMediaStreamTrack(o.videoTrack),yield this._room.replaceTrack(this._localVideoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT),N(o.profile)||(re(o.profile)?xi[o.profile]&&this._localVideoTrack.setProfile(xi[o.profile]):this._localVideoTrack.setProfile(o.profile)),N(o.fillMode)||(a.objectFit=o.fillMode),N(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack)){let c=en(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}yield this._updateVideoPlayOption({view:r,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),this._room.isJoined&&!N(n)&&(n&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!n&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),N(s)||this._localVideoTrack.setMute(s),Et(this._localVideoConfig,e)})}stopLocalVideo(){return T(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack)),this._localVideoTrack.stop(),this._localVideoTrack.close(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return T(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:n=!0,option:s}=e,o=new gt;o.on("4",l=>{let m;l.error&&(m=z.convertFrom(l.error)),this.emit(X.PUBLISH_STATE_CHANGED,ie(w({},l),{error:m}))});let a=null;o.setMediaType(2);let c={},d={};s&&(N(s.profile)||(re(s.profile)?lo[s.profile]&&o.setProfile(lo[s.profile]):o.setProfile(s.profile)),s.systemAudio&&(c.systemAudio=!0,c.echoCancellation=s.echoCancellation,c.noiseSuppression=s.noiseSuppression,c.autoGainControl=s.autoGainControl),N(s.fillMode)||(d.objectFit=s.fillMode),s.videoTrack&&(c.videoTrack=s.videoTrack),s.audioTrack&&(c.audioTrack=s.audioTrack));let u=yield o.capture(c);if(s!=null&&s.qosPreference){let l=en(s.qosPreference);o.mediaTrack.contentHint=l}if(o.mediaTrack.addEventListener(f.ENDED,()=>{this._stopScreenShare(),this.emit(X.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Ii,a.setScreenAudioTrack(u.getAudioTracks()[0],u)),ze(o,o).add("player-state-changed",l=>{this.emit(X.VIDEO_PLAY_STATE_CHANGED,ie(w({},l),{userId:"",streamType:"sub"}))}),yield this._updateVideoPlayOption({view:r,playOption:d,track:o}),n&&this._room.isJoined){let l=[o];a&&l.push(a),this._room.publish(...l).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=ie(w({},e),{view:r,publish:n})})}updateScreenShare(e){return T(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:n,option:s}=e,o={};if(s&&(N(s.fillMode)||(o.objectFit=s.fillMode),s.qosPreference)){let a=en(s.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}yield this._updateVideoPlayOption({view:r,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),this._room.isJoined&&!N(n)&&(n&&!this._localScreenConfig.publish&&this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenConfig.publish&&!n&&this._room.unpublish(this._localScreenTrack)),Et(this._localScreenConfig,e)})}stopScreenShare(){return T(this,null,function*(){return yield this._stopScreenShare()})}usePlugin(){}startPlugin(e,r){return T(this,null,function*(){var n;e==="RTCAudioMixer"&&(this._room.startPlugin("RTCAudioMixer",r),this._room.isJoined&&this._localAudioTrack&&this._room.isMainStreamPublished&&(yield(n=this._room)==null?void 0:n.publish(this._localAudioTrack)))})}updatePlugin(e,r){}stopPlugin(e,r){return T(this,null,function*(){e==="RTCAudioMixer"&&this._room.stopPlugin("RTCAudioMixer",r)})}startRemoteVideo(e){return T(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${n}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(n);if(!c)return;let d={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;o&&(N(o.fillMode)||(d.objectFit=o.fillMode),N(o.mirror)||(d.mirror=o.mirror),s==="main"&&!N(o.small)&&this._room.changeType(o.small,u.user)),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:r,playOption:d,track:u}),this._remoteVideoConfigMap.set(a,e)})}updateRemoteVideo(e){return T(this,null,function*(){let{view:r,userId:n,streamType:s,option:o}=e,a=`${n}_${s}`;if(!this._remoteVideoConfigMap.has(a)||!this._room.remotePublishedUserMap.has(n))return;let c={};o&&(N(o.fillMode)||(c.objectFit=o.fillMode),N(o.mirror)||(c.mirror=o.mirror));let d=null,u=this._room.remotePublishedUserMap.get(n);s==="main"&&(u==null?void 0:u.muteState.hasVideo)&&(d=u.remoteVideoTrack),s==="sub"&&(u==null?void 0:u.muteState.hasAuxiliary)&&(d=u.remoteAuxiliaryTrack);let l=this._remoteVideoConfigMap.get(a);d&&(s==="main"&&o&&!N(o.small)&&this._room.changeType(o.small,d.user),yield this._updateVideoPlayOption({view:r,playOption:c,track:d,prevConfig:l})),Et(l,e)})}stopRemoteVideo(e){return T(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return T(this,null,function*(){let n=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:o,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;o.hasVideo&&e.streamType==="main"&&n.push(a),o.hasAuxiliary&&e.streamType==="sub"&&n.push(c)}for(let o of n)r&&(yield this._room.unsubscribe(o)),o.stop(),this._remoteVideoConfigMap.delete(`${o.userId}_${Zr(o.streamType)}`)})}muteRemoteAudio(e,r){return T(this,null,function*(){if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)s.muteState.hasAudio&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):yield this._startRemoteAudio({userId:e});this._remoteAudioMuteMap.set(e,r)})}setRemoteAudioVolume(e,r){if(e==="*"){let n=[...this._room.remotePublishedUserMap.values()];for(let s of n)this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let n=this._room.remotePublishedUserMap.get(e);n&&this._updateAudioPlayOption({playOption:{volume:r},track:n.remoteAudioTrack})}}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}startMixTranscode(e){let r=w({},e);return r.mixUsers=e.mixUsers.map(n=>{let s=w({},n);return N(n.streamType)||(s.streamType=Zr(n.streamType)),s}),this._room.startMixTranscode(r)}stopMixTranscode(){return this._room.stopMixTranscode()}startPublishCDNStream(e){let r=w({},e);return N(e.streamType)||(r.streamType=Zr(e.streamType)),this._room.startPublishCDNStream(r)}stopPublishCDNStream(){return this._room.stopPublishCDNStream()}on(e,r,n){return super.on(e,r,n),this._eventListened.add(e),this}off(e,r,n){return e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,n),this}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:n="main"}=e;if(r===""){if(n==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(n==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let s=this._room.remotePublishedUserMap.get(r);if(s)return n==="main"?s.remoteVideoTrack.mediaTrack:s.remoteAuxiliaryTrack.mediaTrack}return null}getAudioTrack(e){if(e){let r=this._room.remotePublishedUserMap.get(e);if(r)return r.remoteAudioTrack.mediaTrack}else if(this._localAudioTrack)return this._localAudioTrack.mediaTrack;return null}setCurrentSpeaker(e){var r;(r=this._localAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return T(this,null,function*(){let{userId:r,option:n}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let s=this._room.remotePublishedUserMap.get(r);if(!s)return;let o={};n&&(N(n.volume)||(o.volume=n.volume));let a=s.remoteAudioTrack;yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:o,track:a}),this._remoteAudioConfigMap.set(r,e)})}_stopRemoteAudio(e,r=!0){return T(this,null,function*(){let n=this._room.remotePublishedUserMap.get(e.userId);n!=null&&n.muteState.hasAudio&&(r&&(yield this._room.unsubscribe(n.remoteAudioTrack)),n.remoteAudioTrack.stop()),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return T(this,arguments,function*({view:e,playOption:r,track:n,prevConfig:s}){if(N(e)&&s&&s.view&&!Ur(r)){let a=qn(s.view);a&&(yield n.play(a,r))}if(!N(e)){let a=qn(e);a?yield n.play(a,r):n.stop()}})}_updateAudioPlayOption(s){return T(this,arguments,function*({playOption:e={},track:r,prevConfig:n}){r.isPlayCalled||(yield r.play(null,e)),N(e.muted)||r.setPlayerMute(e.muted),N(e.volume)||r.setAudioVolume(e.volume/100)})}_checkTrackToPublish(){var r,n,s;let e=[];if(((r=this._localAudioConfig)==null?void 0:r.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((n=this._localVideoConfig)==null?void 0:n.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_handleReceiveMode(){this._room.autoReceiveAudio&&ze(this,this).add(X.REMOTE_AUDIO_AVAILABLE,r=>T(this,[r],function*({userId:e}){if(this._remoteAudioMuteMap.get("*")||this._remoteAudioMuteMap.get(e))return;let n=this._room.remotePublishedUserMap.get(e);n&&(yield this._room.subscribe(n.remoteAudioTrack).catch(()=>{}),yield this._updateAudioPlayOption({track:n.remoteAudioTrack}).catch(()=>{}),this._remoteAudioConfigMap.set(e,{userId:e}))})),this._room.autoReceiveVideo&&ze(this,this).add(X.REMOTE_VIDEO_AVAILABLE,({userId:e,streamType:r})=>{let n=this._room.remotePublishedUserMap.get(e);n&&(r==="main"?this._room.subscribe(n.remoteVideoTrack).catch(()=>{}):r==="sub"&&this._room.subscribe(n.remoteAuxiliaryTrack).catch(()=>{}))})}_exitRoom(){return T(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),[...this._remoteAudioConfigMap.keys()].forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let r=e.includes("main")?"main":"sub",n=e.split(`_${r}`)[0];n&&this._stopRemoteVideo({userId:n,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)}),Le(this)})}_stopScreenShare(){return T(this,null,function*(){var e,r,n;if(!!this._localScreenTrack){if(this._room.isJoined){let s=[this._localScreenTrack];this._localScreenAudioTrack&&s.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...s)}this._localScreenTrack.stop(),this._localScreenTrack.close(),(r=this._localScreenAudioTrack)==null||r.stop(),(n=this._localScreenAudioTrack)==null||n.close(),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenAudioTrack=null,this._localScreenConfig=null}})}static setLogLevel(e,r){P.setLogLevel(e),N(r)||(r?P.enableUploadLog():P.disableUploadLog())}static isSupported(){return Ko()}static getCameraList(){return It()}static getMicrophoneList(){return et()}static getSpeakerList(){return Ji()}static setCurrentSpeaker(e){return T(this,null,function*(){(yield Ji()).forEach(n=>{n.deviceId===e&&(tc.forEach(s=>{s.setCurrentSpeaker(e),s.emit(X.DEVICE_CHANGED,{type:"speaker",action:"active",device:n})}),We=n)})})}},ne=tn;p(ne,"_loggerManager",P),p(ne,"EVENT",X),p(ne,"ERROR_CODE",te),p(ne,"TYPE",zr),p(ne,"frameWorkType",30),G([He(be.TRTC.enterRoom),Ri("room",([i],[t])=>i.roomId===t.roomId&&i.userId===t.userId&&i.sdkAppId===t.sdkAppId),de(i=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),i.call(this,t).catch(e=>{throw Le(this),e})}),Re()],ne.prototype,"enterRoom",1),G([Ai("room"),Re()],ne.prototype,"exitRoom",1),G([He(be.TRTC.switchRole),er("room",(i,t)=>t),Re()],ne.prototype,"switchRole",1),G([Re()],ne.prototype,"destroy",1),G([He(be.TRTC.startLocalAudio),Ri("audio",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.microphoneId)===((r=t==null?void 0:t.option)==null?void 0:r.microphoneId)}),Re()],ne.prototype,"startLocalAudio",1),G([He(be.TRTC.updateLocalAudio),er("audio"),Re()],ne.prototype,"updateLocalAudio",1),G([Ai("audio"),Re()],ne.prototype,"stopLocalAudio",1),G([He(be.TRTC.startLocalVideo),Ri("video",([i],[t])=>{var e,r;return((e=i==null?void 0:i.option)==null?void 0:e.cameraId)===((r=t==null?void 0:t.option)==null?void 0:r.cameraId)}),Re()],ne.prototype,"startLocalVideo",1),G([He(be.TRTC.updateLocalVideo),er("video"),Re()],ne.prototype,"updateLocalVideo",1),G([Ai("video"),Re()],ne.prototype,"stopLocalVideo",1),G([He(be.TRTC.startScreenShare),Ri("screen",()=>!0),Re()],ne.prototype,"startScreenShare",1),G([He(be.TRTC.updateScreenShare),er("screen"),Re()],ne.prototype,"updateScreenShare",1),G([Ai("screen"),Re()],ne.prototype,"stopScreenShare",1),G([He(be.TRTC.startRemoteVideo),Ri(i=>`v${i.userId}${i.streamType}`,()=>!0),Re()],ne.prototype,"startRemoteVideo",1),G([He(be.TRTC.updateRemoteVideo),er(i=>`v${i.userId}${i.streamType}`),Re()],ne.prototype,"updateRemoteVideo",1),G([He(be.TRTC.stopRemoteVideo),de(i=>function(t){return T(this,null,function*(){if(t.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(r=>{this._remoteVideoConfigMap.has(`${r.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:r.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${r.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:r.userId}).catch(()=>{}))}),Promise.all(e)}return i.call(this,t)})}),Ai(i=>`v${i.userId}${i.streamType}`,!0),Re()],ne.prototype,"stopRemoteVideo",1),G([Qa(i=>`v${i.userId}${i.streamType}`)],ne.prototype,"_stopRemoteVideo",1),G([He(...be.TRTC.muteRemoteAudio),Re()],ne.prototype,"muteRemoteAudio",1),G([ec(...be.TRTC.setRemoteAudioVolume),Zu(200,i=>i),Re()],ne.prototype,"setRemoteAudioVolume",1),G([ec(...be.TRTC.enableAudioVolumeEvaluation)],ne.prototype,"enableAudioVolumeEvaluation",1),G([He(be.TRTC.startMixTranscode)],ne.prototype,"startMixTranscode",1),G([Ri(i=>`a${i.userId}`,()=>!0)],ne.prototype,"_startRemoteAudio",1),G([de(i=>function(t){return T(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(ie(w({},t),{userId:e.userId})).catch(()=>{}))):i.call(this,t)})}),Ai(i=>`a${i.userId}`)],ne.prototype,"_stopRemoteAudio",1),G([Qa("room")],ne.prototype,"_exitRoom",1);var Ns=ne;var CL=h(_());var NN=h(_(),1);var ic=class{constructor(){this._set=new Set;C.on(I.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,n){return`${r}_${e}_${t}_${n}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:n}){return n.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,n.useStringRoomId))}};function s_(){return T(this,null,function*(){let i,t;try{let l=yield et();i=l&&l.length}catch(l){}try{let l=yield It();t=l&&l.length}catch(l){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:n,isH264DecodeSupported:s,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=Mt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:n,vp8Decode:o},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Ae.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Ae.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function rl(){return de(i=>{let t=new ic;return function(e,r,n){return T(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new V({code:M.INVALID_OPERATION,message:H({key:$.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new V({code:M.INVALID_OPERATION,message:H({key:$.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),this.role=e.role===21?"audience":"anchor",C.emit(I.JOIN_START,{room:this,roomId:s}),this.checkSystemResult=yield Mt.checkSystemRequirementsInternal(),this.checkDestroy();let o=Fe.getEnv();o||(o=Wt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(po.OLD_CLOUD_LADDER)?o=Wt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(po.WEBRTC)&&(o=Wt.WEBRTC))),Ae.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),s_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Mt.isWebRTCSupported()||!a&&!c)throw new V({code:M.NOT_SUPPORTED,message:H({key:$.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&(yield this.schedule(s,n,Ve)),console.log("scheduleResult",this.scheduleResult);let d=yield i.call(this,e,r,n);return this.roomId=s,this._joinedTimestamp=Fe.performanceNow(),C.emit(I.JOIN_SUCCESS,{room:this}),d}catch(d){throw t.delete({room:this,roomId:s}),C.emit(I.JOIN_FAILED,{room:this,error:d}),d}})}})}var kN=h(_(),1);var nl=()=>de(i=>function(...t){return T(this,null,function*(){C.emit(I.LEAVE_START,{room:this}),yield i.call(this),C.emit(I.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});var zN=h(_()),ol=h(rt());var VN=h(_()),ve={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4"},Ke={DISCONNECTED:"DISCONNECTED",CONNECTING:"CONNECTING",CONNECTED:"CONNECTED"},Rt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150},sl=[Rt.UPDATE_REMOTE_MUTE_STAT,Rt.UPLINK_NETWORK_STATS,Rt.USER_LIST_RES,Rt.MUTE_RESULT],se={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res"},pe={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc"};var rn=class{constructor(t){p(this,"_room");p(this,"_sdkAppId");p(this,"_userId");p(this,"_userSig");p(this,"_url");p(this,"_backupUrl");p(this,"_urlWithParam");p(this,"_backupUrlWithParam");p(this,"_socketInUse");p(this,"_socket");p(this,"_backupSocket");p(this,"_backupTimer",-1);p(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});p(this,"_currentState",Ke.DISCONNECTED);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_seq",0);p(this,"_log");p(this,"_emitter");p(this,"_lastMessageTime",-1);p(this,"_prevTime",-1);this._room=t.room,this._sdkAppId=t.sdkAppId,this._userId=t.userId,this._userSig=t.userSig,this._url=t.url,this._backupUrl=t.backupUrl;let e=`?sdkAppId=${encodeURIComponent(this._sdkAppId)}&userId=${encodeURIComponent(this._userId)}&userSig=${encodeURIComponent(this._userSig)}`;this._urlWithParam=`${this._url}${e}`,this._backupUrlWithParam=`${this._backupUrl}${e}`,this._seq=0,this._log=P.createLogger({id:"ws",userId:this._userId,sdkAppId:this._sdkAppId}),this._emitter=new ol.default}get isConnected(){return this._currentState===Ke.CONNECTED}get isConnecting(){return this._currentState===Ke.CONNECTING}get isOnline(){return this._currentState===Ke.CONNECTED&&Date.now()-this._lastMessageTime<12*1e3}connect(){return new Promise((t,e)=>{this._prevTime<0&&(this._prevTime=ee()),this._log.info(`connect to ${this._url}`),this.emitConnectionStateChanged(Ke.CONNECTING),this._socket=new WebSocket(this._urlWithParam),this.bindSocket(this._socket),this._backupTimer=setTimeout(()=>{this.isConnected||(this._log.info("trying to connect to backupUrl"),this.tryConnectBackup())},5e3),this.once(ve.CONNECTED,t),this.once(ve.RECONNECT_FAILED,e)})}tryConnectBackup(){this._backupSocket||(this.unbindAndCloseSocket(f.MAIN),this._log.debug(`try to connect to url: ${this._backupUrlWithParam}`),this._backupSocket=new WebSocket(this._backupUrlWithParam),this.bindSocket(this._backupSocket))}bindSocket(t){t.onopen=this.onopen.bind(this),t.onclose=this.onclose.bind(this),t.onerror=this.onerror.bind(this),t.onmessage=this.onmessage.bind(this)}unbindSocket(t){this.clearBackupTimer(),t.onopen=()=>{},t.onclose=()=>{},t.onerror=()=>{},t.onmessage=()=>{}}unbindAndCloseSocket(t){if(t===f.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(e){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(e){}this._backupSocket=null}}clearBackupTimer(){this._backupTimer!==-1&&(clearTimeout(this._backupTimer),this._backupTimer=-1)}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onopen(t){if(this.isConnected)return;this.isReconnecting&&!this._signalInfo.tinyId&&this.stopReconnection(),this.clearBackupTimer(),t.target===this._socket?(this.unbindAndCloseSocket(f.BACKUP),this._socketInUse=this._socket):(this.unbindAndCloseSocket(f.MAIN),this._socketInUse=this._backupSocket),this.emitConnectionStateChanged(Ke.CONNECTED),this._emitter.emit(ve.CONNECTED)}onclose(t){let{url:e}=t.target,r=t.target===this._socketInUse;this._log.info(`websocket[${e} InUse: ${r}] is closed with code: ${t.code}`),t.target===this._socketInUse&&(this.emitConnectionStateChanged(Ke.DISCONNECTED),(!t.wasClean||t.code!==1e3)&&(this._log.warn(`onclose code:${t.code} reason:${t.reason}`),this._log.warn("close current websocket and schedule a reconnect timeout"),this._socketInUse.onclose=()=>{},this._socketInUse.close(4011),this._socket=null,this._backupSocket=null,this._socketInUse=null,this.reconnect(f.MAIN)))}onerror(t){let{url:e}=t.target;this._log.error(`websocket[${e}] error observed`),this.isConnected?t.target===this._socketInUse&&(this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this._socketInUse=null,this.reconnect(f.MAIN)):(this.isReconnecting||C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:new Error("ws onerror")}),t.target==this._socket?(this.unbindAndCloseSocket(f.MAIN),this.reconnect(f.BACKUP)):(this.unbindAndCloseSocket(f.BACKUP),this.reconnect(f.MAIN)))}onmessage(t){if(!this.isConnected)return;this._lastMessageTime=Date.now();let e=JSON.parse(t.data),{cmd:r,data:n}=e,s=Object.values(Rt),a=Object.keys(Rt)[s.indexOf(r)],c=se[a];switch(sl.includes(r)||(this._log.debug(`received msg: ${t.data}`),this._log.info(`Received event: [ ${c||`unknown cmd: ${r}`} ]`)),r){case Rt.CHANNEL_SETUP_RESULT:{if(e.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,this._signalInfo.tinyId=e.tinyId,n.svrTime&&Nd(n.svrTime),this._log.info("ChannelSetup Success"),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",cost:ee()-this._prevTime}),this._prevTime=-1,this._emitter.emit(ve.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let d=new V({code:M.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:e.code,message:H({key:$.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e.code,errorMsg:e.message}})});this._log.error(`${e.code}, ${e.message}`),this.close(),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketConnect",error:d}),this._emitter.emit(ve.SETUP_FAILED,d)}break}case Rt.JOIN_ROOM_RESULT:{e.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this._emitter.emit(c,{data:e});break}case Rt.CHANNEL_RECONNECT_RESULT:{e.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",cost:ee()-this._prevTime}),this._prevTime=-1,this._room.syncUserList(),this._room.checkConnectionsToReconnect()):(this._log.warn(`reconnect failed, ${e.code} ${e.message}`),this._room.reJoin());break}default:this._emitter.emit(c,{data:e});break}}reconnect(t=f.MAIN){if(this.isReconnecting)return;if(this._reconnectionCount>=On){this._log.warn(`SDK has tried reconnect signal channel for ${On} times, but all failed. please check your network`);let n=new V({code:M.SIGNAL_CHANNEL_RECONNECTION_FAILED,message:H({key:$.SIGNAL_CHANNEL_RECONNECTION_FAILED})});C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"WebsocketReconnect",error:n}),this._emitter.emit(ve.RECONNECT_FAILED,n);return}this._reconnectionCount++,this._log.warn(`reconnect ${t} [${this._reconnectionCount}/${On}]`);let e=this.getReconnectionUrl(t);this.emitConnectionStateChanged(Ke.CONNECTING),this._prevTime<0&&(this._prevTime=ee()),t===f.MAIN?(this._socket=new WebSocket(e),this.bindSocket(this._socket)):(this._backupSocket=new WebSocket(e),this.bindSocket(this._backupSocket));let r=ft(this._reconnectionCount);this._reconnectionTimer=setTimeout(()=>{this._log.warn(`reconnect ${t} timeout(${r/1e3}s), try again`),this.clearReconnectionTimer(),this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this.reconnect(t===f.MAIN?f.BACKUP:f.MAIN)},r)}get isReconnecting(){return this._reconnectionTimer!==-1}getReconnectionUrl(t){let e=t===f.MAIN?this._urlWithParam:this._backupUrlWithParam;if(this._signalInfo.tinyId&&e.indexOf("&rc=1")===-1){let{roomId:r,useStringRoomId:n}=this._room;e+=`&rc=1&relayInnerIp=${this._signalInfo.relayInnerIp}&relayOuterIp=${this._signalInfo.relayIp}&relayPort=${this._signalInfo.relayPort}&roomId=${r}&useStringRoomId=${n}`}return e}send(t,e={}){if(this.isConnected){let r={cmd:t,data:e,userId:this._userId,tinyId:this._signalInfo.tinyId,seq:++this._seq};return this._socketInUse.send(JSON.stringify(r)),r.seq}}sendWaitForResponse({command:t,data:e,timeout:r=5e3,responseCommand:n,commandDesc:s,enableLog:o=!0}){return new Promise((a,c)=>{let d=setTimeout(()=>{this.off(n,u);let m=new V({code:M.API_CALL_TIMEOUT,message:H({key:$.API_CALL_TIMEOUT,data:{commandDesc:s,command:t}})});o&&this._log.warn(m),c(m)},r),u=m=>{m.data.seq===l&&(clearTimeout(d),this.off(n,u),a(m))};this.on(n,u);let l=this.send(t,e)})}sendWaitForResponseWithRetry(t){let{commandDesc:e,command:r,retries:n=0,retryTimeout:s=0}=t;return Tt({retryFunction:this.sendWaitForResponse,onRetrying:o=>{this._log.warn(`${e||r} timeout observed, retrying [${o}/${n}]`)},settings:{retries:n,timeout:s},context:this})(t)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this.isReconnecting&&(this._reconnectionCount=0,this.clearReconnectionTimer())}close(){this._log.info("close SignalChannel"),this.clearBackupTimer(),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this.emitConnectionStateChanged(Ke.DISCONNECTED)}on(t,e,r){this._emitter.on(t,e,r)}removeListener(t,e,r){this._emitter.removeListener(t,e,r)}once(t,e,r){this._emitter.once(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}emitConnectionStateChanged(t){t!==this._currentState&&(this._log.info(`${this._currentState} -> ${t}`),this._emitter.emit(ve.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:t}),this._currentState=t)}};var jD=h(_());var TD=h(_()),cl=h(rt());var iD=h(_());var rc=class{constructor(t,e,r){this._isUplink=r,this._connection=t,this._log=e,this._seiMessageList=[],this._seiPayloadType=243,this._mainVideoSenderOrReceiver=null,this._mainVideoAbortController=null,this._abortMap=new Map,this.onSEIMessage=null}get isRunning(){return!!this._mainVideoAbortController}start(t){this._mainVideoSenderOrReceiver=t;let e=t.createEncodedStreams(),r=e.readable,n=e.writable,s=new TransformStream({transform:this._isUplink?this.encodeVideoFrame.bind(this):this.decodeVideoFrame.bind(this)});this._mainVideoAbortController=new AbortController,r.pipeThrough(s).pipeTo(n,{signal:this._mainVideoAbortController.signal}).catch(()=>{})}restart(t){this.stop(),this.start(t)}stop(){var t;(t=this._mainVideoAbortController)==null||t.abort(),this._mainVideoAbortController=null}destroy(){this.stop(),this._abortMap.forEach(t=>t.abort()),this._abortMap.clear(),this._log=null,this.onSEIMessage=null,this._mainVideoSenderOrReceiver=null,this._connection=null}handleEncodedStreams(){try{let t=this._connection.getPeerConnection();this.clearUnusedSenderOrReceiver(t),this._isUplink?t.getSenders().forEach((e,r)=>{if(r===1){if(e===this._mainVideoSenderOrReceiver)return;this.isRunning?this.restart(e):this.start(e)}else{if(this._abortMap.has(e))return;this.pipeSenderOrReceiver(e)}}):t.getReceivers().forEach((e,r)=>{var n;this._abortMap.has(e)||e===this._mainVideoSenderOrReceiver||(r===1&&((n=e.track)==null?void 0:n.kind)===f.VIDEO?this.isRunning?this.restart(e):this.start(e):this.pipeSenderOrReceiver(e))})}catch(t){this._log.warn(t)}}pipeSenderOrReceiver(t){let{readable:e,writable:r}=t.createEncodedStreams(),n=new AbortController;this._abortMap.set(t,n),e.pipeTo(r,{signal:n.signal}).catch(()=>{})}clearUnusedSenderOrReceiver(t){this._abortMap.forEach((e,r)=>{(this._isUplink?t.getSenders():t.getReceivers()).find(s=>s===r)||(e.abort(),this._abortMap.delete(r))})}push(t,e){e&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t)}hasSEI(t){let e=new DataView(t);return e.getInt32(0)===1&&e.getInt8(4)===6}isEmptyFrame(t){return t.type==="empty"||t.data.byteLength===0}getNaluCount(t){let e=0,r=0,n=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(n.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encodeVideoFrame(t,e){try{if(this._connection.isH264&&this._seiMessageList.length>0&&!this.isEmptyFrame(t)){let n=9-this.getNaluCount(t.data);if(n<=0)return;let s=this._seiMessageList.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),o=s.reduce((l,m)=>l+m.dataView.byteLength,0),a=new ArrayBuffer(o+t.data.byteLength),c=new DataView(a),d=new DataView(t.data),u=0;for(let l=0;l<s.length;l++)for(let m=0;m<s[l].dataView.byteLength;m++)c.setInt8(u++,s[l].dataView.getInt8(m));for(let l=0;l<t.data.byteLength;l++)c.setInt8(u++,d.getInt8(l));t.data=a,this._log.debug(`${s.length} sei sent`)}}catch(r){this._log.warn(r)}e.enqueue(t)}decodeVideoFrame(t,e){try{if(this._connection.isH264&&!this.isEmptyFrame(t)&&this.hasSEI(t.data)){let r=[],n=new DataView(t.data),s=0,o=-1,a=-1;for(let c=0;c<t.data.byteLength;c++){let d=n.getUint8(c);if(d===0)s++;else if(d===1){if(s===2||s===3){let u=c-s;if(o===-1?o=u:a===-1&&(a=u,r.push(new Ds(new DataView(n.buffer.slice(o,a)))),o=u,a=-1),!(n.getUint8(c+1)===6)){t.data=new DataView(n.buffer.slice(u)).buffer;break}}s=0}else s=0}this._log.debug(`${r.length} sei received`),oe(this.onSEIMessage)&&r.reverse().forEach(c=>{this.onSEIMessage({seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer})})}}catch(r){this._log.warn(r)}e.enqueue(t)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(e/255),n=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<r;a++)s.push(255);s.push(n);let o=new DataView(t);return s.push(...new Uint8Array(o.buffer)),s.push(128),new Ds(new DataView(new Uint8Array(s).buffer),!0)}},Ds=class{constructor(t,e=!1){this.dataView=t,this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:t}=this,e=this.dataView.byteLength-2,r=[],n=0;for(let o=t;o<=e;o++){let a=this.dataView.getInt8(o);switch(a){case 0:case 1:case 2:case 3:n===2&&(r.push(3),n=0),a==0?n++:n=0,r.push(a);break;default:n=0,r.push(a);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:t}=this,e=this.dataView.byteLength-1,r=[],n=0;for(let o=t;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:n++,r.push(this.dataView.getInt8(o));break;case 3:n!==2&&r.push(this.dataView.getInt8(o)),n=0;break;default:r.push(this.dataView.getInt8(o)),n=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let o=this.dataView.getUint8(s);if(e++,o===255)t+=255;else{t+=o;break}}let r=new ArrayBuffer(t),n=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)n.setInt8(s,this.dataView.getInt8(e));return n}},al=rc;var nc=0,sc=!1,Os=new Set,o_=i=>nc>2&&!sc&&Os.size===0&&i,ac=!1,ct=class{constructor(t){p(this,"userId");p(this,"tinyId");p(this,"_sdpSemantics");p(this,"_isUplink");p(this,"_room");p(this,"_log");p(this,"_signalChannel");p(this,"_isErrorObserved",!1);p(this,"_waitForPeerConnectionConnectedPromise");p(this,"_waitForPeerConnectionConnectedPromiseReject",null);p(this,"_peerConnection",null);p(this,"_emitter",new cl.default);p(this,"_currentState","DISCONNECTED");p(this,"_isReconnecting",!1);p(this,"_reconnectionCount",0);p(this,"_reconnectionTimer",-1);p(this,"_isFirstConnection",!0);p(this,"_prevTime",-1);p(this,"_enableSEI");p(this,"_sei");p(this,"_localAddress");p(this,"_remoteAddress");this.userId=t.userId,this.tinyId=t.tinyId,this._room=t.room,this._sdpSemantics=t.room.sdpSemantics,this._isUplink=t.isUplink,this._log=P.createLogger({id:"n",userId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=t.signalChannel,this._enableSEI=t.enableSEI,this._enableSEI&&rs&&(this._sei=new al(this,this._log,this._isUplink))}beforeConnect(){this._prevTime<0&&(this._prevTime=ee())}afterConnect(t){return T(this,null,function*(){try{yield t,this._isFirstConnection?(this._isFirstConnection=!1,C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",cost:Math.min(ee()-this._prevTime,30*1e3)})):this._isReconnecting&&C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",cost:ee()-this._prevTime}),this._prevTime=-1}catch(e){throw this._isFirstConnection?(this._isFirstConnection=!1,C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionConnect",error:e})):this._isReconnecting&&this._reconnectionCount>=3&&C.emit(I.API_SUCCESS_RATE,{room:this._room,apiName:"PeerConnectionReconnect",error:e}),e}})}initialize(){let t={encodedInsertableStreams:this._enableSEI&&rs,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(t),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(){this._log.info("close connection"),this.closePeerConnection(),this._sei&&(this._sei.destroy(),this._sei=null),Os.delete(this)}closePeerConnection(t=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,t&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new V({code:M.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return mr;let t=null;if(this._isUplink){if(!is()||this._peerConnection.getSenders().length===0)return mr;t=this._peerConnection.getSenders()[0].transport}else{if(!Br()||this._peerConnection.getReceivers().length===0)return mr;t=this._peerConnection.getReceivers()[0].transport}return t?t.state:mr}onConnectionStateChange(t){let e=this._peerConnection.iceConnectionState,r=this.getDTLSTransportState();if(this._log.info(`connectionState: ${t.target.connectionState}, ICE: ${e}, DTLS: ${r}`),t.target.connectionState===De.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),t.target.connectionState===De.FAILED||t.target.connectionState===De.CLOSED){let n=`connection ${t.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${r}`,s=new V({message:n,code:M.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(t.target.connectionState===De.CONNECTED||t.target.connectionState===De.COMPLETED)&&(this.logSelectedCandidate(),Ae.logSuccessEvent({userId:this._room.userId,eventType:di.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(t){return t===this._currentState?!1:(t==="CONNECTED"?(nc=0,sc=!1,ac=!0,Os.add(this)):Os.delete(this),C.emit(I.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:t,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:t}),this._currentState=t,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return T(this,null,function*(){if(!this._peerConnection)return;let t=yield this._peerConnection.getStats();for(let[,e]of t)if(Hi(e)){let r=t.get(e.localCandidateId),n=t.get(e.remoteCandidateId);r&&(this._log.info(`local candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port} ${r.networkType||""} ${r.candidateType==="relay"?`relayProtocol:${r.relayProtocol}`:""}`),this._localAddress=`${r.ip||r.address}:${r.port}`),n&&(this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`),this._remoteAddress=`${n.protocol}:${n.ip||n.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((t,e)=>{if(this._currentState==="CONNECTED")return t();this._waitForPeerConnectionConnectedPromiseReject=e;let r=a=>{a.state==="CONNECTED"&&(clearTimeout(o),s(),t())},n=({room:a})=>{a===this._room&&(clearTimeout(o),s(),e(new V({code:M.API_CALL_ABORTED,message:H({key:$.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{C.off(I.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",r,this)},o=setTimeout(()=>{s();let a=new V({code:M.API_CALL_TIMEOUT,message:"connection timeout"});nc+=1,o_(this._signalChannel.isConnected)&&(this._log.warn("firewall restrition"),sc=!0,this._emitter.emit("firewall-restriction")),e(a)},Rd);C.on(I.LEAVE_SUCCESS,n,this),this._emitter.on("connection-state-changed",r,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(ve.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=hr()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let t=new V({code:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?$.UPLINK_RECONNECTION_FAILED:$.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",t),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(ve.CONNECTED,this.reconnect,this),-1)}on(t,e,r){this._emitter.on(t,e,r)}off(t,e,r){this._emitter.off(t,e,r)}getIsReconnecting(){return this._isReconnecting}get isH264(){var t,e;return!!((e=(t=this._peerConnection)==null?void 0:t.remoteDescription)!=null&&e.sdp.includes("H264"))}};var OD=h(_()),uc=h(fl());var At=function(i){return uc.default.parse(i)},vi=function(i){return uc.default.write(i)},El=function(i){let t=At(i);return t.media.forEach(e=>{e.type===f.AUDIO&&e.fmtp.forEach(r=>{r.config+=";sprop-stereo=1;stereo=1"})}),vi(t)};function Tl(i){let t=At(i);return t.media.forEach(e=>{var r,n;if(e.type===f.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&s.has(Number(d[1]))&&s.add(a)});let o=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(r=e.rtcpFb)==null?void 0:r.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(n=e.payloads)==null?void 0:n.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),vi(t)}var PD=h(_());function Ps(i){return Object.keys(i).filter(t=>i[t])}var lc=class extends ct{constructor(e){super(ie(w({},e),{isUplink:!1}));p(this,"_flag",0);p(this,"role","anchor");p(this,"remoteAudioTrack");p(this,"remoteVideoTrack");p(this,"remoteAuxiliaryTrack");p(this,"ssrc",{audio:0,video:0,auxiliary:0});p(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=new ps(this._room,this),this.remoteVideoTrack=new Yr(this._room,this),this.remoteAuxiliaryTrack=new ms(this._room,this)}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Bi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var r,n,s;e!==this._flag&&(this._flag=e,(r=this.remoteAudioTrack)==null||r.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(){super.close(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,o;let r=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&r!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:r,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:r,state:e})),n}onTrack(e){let r=e.streams[0],{track:n}=e,s=r.id===Nn?f.MAIN:f.AUXILIARY;this._log.debug(`ontrack ${s} ${n.kind}`);let o=f.AUDIO;n.kind===f.VIDEO&&(o=s===f.MAIN?f.VIDEO:f.AUXILIARY);let a=this.remoteAudioTrack;o===f.VIDEO?a=this.remoteVideoTrack:o===f.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setMediaStream(r),a.setMediaStreamTrack(n)}addRRTRLine(e){let r=e.split(`\r
93
+ `),n=new Map;r.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&r[a+1]&&!/^a=rtcp-fb:/.test(r[a+1])&&n.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...n];for(let o=0;o<s.length;o++){let[a,c]=s[o];r.splice(a+o,0,c)}return r.join(`\r
94
+ `)}addSPSDescription(e){let r=At(e);return r.media.forEach(n=>{n.type===f.VIDEO&&n.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),vi(r)}removeSDESDescription(e){let r=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],n=At(e);return n.media.forEach(s=>{!s.ext||(s.ext=s.ext.filter(o=>!r.includes(o.uri)))}),vi(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}isSubscribeSmall(e){return N(e.smallVideo)&&!this.subscribeState.smallVideo}subscribe(e,r){return T(this,null,function*(){var n,s;try{if((((n=this._peerConnection)==null?void 0:n.connectionState)===De.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===De.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._peerConnection||this._isSDPExchanging){let o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(r)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new V({code:M.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(n){return T(this,arguments,function*({remoteTracks:e,streamType:r}){if(this._currentState==="CONNECTED"&&(r==="main"&&!this.isMainStreamSubscribed||r==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${r} stream already unsubscribed`);return}let s=w({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(s).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${r} [${Ps(s)}]`),yield this.sendSubscription(o,s),o==="unsubscribe"&&(this.remoteAudioTrack.setMediaStreamTrack(null),this.remoteVideoTrack.setMediaStreamTrack(null),this.remoteAuxiliaryTrack.setMediaStreamTrack(null),this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,r=this.subscribeState){let n={srcTinyId:this.tinyId,srcUserId:this.userId},s=pe.UNSUBSCRIBE,o=se.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:r.audio,bigVideo:r.video,auxVideo:r.auxiliary,smallVideo:r.smallVideo,srcTinyId:this.tinyId},s=pe.SUBSCRIBE_CHANGE,o=se.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:n,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new V({code:a.code,message:H({key:$.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return T(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(r){throw this.closePeerConnection(!0),r}})}exchangeSDP(e){return T(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:r,sdp:n}=this._peerConnection.localDescription,s={type:r,sdp:n,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:pe.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:se.SUBSCRIBE_RESULT,timeout:gd});if(!this._peerConnection){let a=new V({code:M.INVALID_OPERATION,message:H({key:$.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(r){throw this._isSDPExchanging=!1,r}})}createOffer(){return T(this,null,function*(){let e={voiceActivityDetection:!1};$r()&&this._sdpSemantics===ui?(this._peerConnection.addTransceiver(f.AUDIO,{direction:he.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:he.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:he.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let r=yield this._peerConnection.createOffer(e);if(r.sdp){let{isH264DecodeSupported:n}=yield Zn();n||(this._log.warn("remove h264 desc from sdp"),r.sdp=Tl(r.sdp)),r.sdp=this.addRRTRLine(r.sdp),r.sdp=this.addSPSDescription(r.sdp),r.sdp=El(r.sdp),this._sdpSemantics===ui&&(r.sdp=this.removeSDESDescription(r.sdp))}yield this._peerConnection.setLocalDescription(r)})}onSubscribeResult(e){return T(this,null,function*(){let{code:r,message:n=""}=e&&e.data||{},{type:s,sdp:o}=e&&e.data&&e.data.data||{};if(r===bn)throw new V({code:M.NOT_SUPPORTED_H264,message:H({key:$.NOT_SUPPORTED_H264DECODE})});try{if(r!==0)throw new V({code:r,message:H({key:$.EXCHANGE_SDP_FAILED,data:{errMsg:n}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:s,sdp:o}),this.updateSSRC(o)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{At(e).media.forEach(n=>{if(!!n.ssrcs)if(n.type===f.AUDIO){let s=n.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(Nn)});s&&(this.ssrc.audio=Number(s.id))}else{let s=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Nn)}),o=n.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(fd)});s&&(this.ssrc.video=Number(s.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(r){}}getSubscribeState(){return this.subscribeState}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return T(this,null,function*(){if(!(oi(lc.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(r){let n=ft(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:r}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=r}},bs=lc;G([Yi(ct.prototype.afterConnect),us(ct.prototype.beforeConnect)],bs.prototype,"connect",1);var Il=bs;var wO=h(_());var qD=h(_(),1);var Ms=new Map;function gl(i){let t=Pt(),e=t.createMediaStreamDestination(),r=[];i.forEach(s=>{let o=new MediaStream;o.addTrack(s);let a=t.createMediaStreamSource(o);a.connect(e),r.push(a)});let n=e.stream.getAudioTracks()[0];return Ms.set(n,{destination:e,track:n,mediaStreamSourceList:r}),n}function Rl(i){if(Ms.has(i)){let{destination:t,track:e,mediaStreamSourceList:r}=Ms.get(i);e.stop(),t.disconnect(),r.forEach(n=>{n.disconnect()}),Ms.delete(i)}}var hO=h(_());var ZD=h(_());var __="let width,height,offscreen,ctx;onmessage=function(e){const{action,data}=e.data;switch(action){case'render':offscreen=data.canvas;width=offscreen.width;height=offscreen.height;ctx=offscreen.getContext('2d');draw(data.readable,data.writable);break}};function draw(readable,writable){const transformer=new TransformStream({async transform(cameraFrame,controller){ctx.drawImage(cameraFrame,0,0,width,height);const frame=new VideoFrame(offscreen,{timestamp:cameraFrame.timestamp});cameraFrame.close();controller.enqueue(frame)}});readable.pipeThrough(transformer).pipeTo(writable)}",f_=new Blob([__],{type:"application/javascript"}),pc=class{constructor(t){p(this,"width");p(this,"height");p(this,"canvas");p(this,"offscreen");p(this,"smallGenerator");p(this,"smallWritable");p(this,"bigProcessor");p(this,"bigReadable");p(this,"worker");let{videoTrack:e}=t;this.width=void 0,this.height=void 0,this.canvas=null,this.offscreen=null,this.smallGenerator=new MediaStreamTrackGenerator({kind:"video"}),this.smallWritable=this.smallGenerator.writable,this.bigProcessor=new MediaStreamTrackProcessor({track:e}),this.bigReadable=this.bigProcessor.readable,this.initWorker()}initWorker(){try{this.worker=new Worker(URL.createObjectURL(f_)),P.info("init worker processor success")}catch(t){P.warn(`init worker processor failed. ${t.error}`)}}setCanvasRect(t,e){this.width=t,this.height=e,this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e,this.offscreen=this.canvas.transferControlToOffscreen(),this.worker.postMessage({action:"render",data:{canvas:this.offscreen,readable:this.bigReadable,writable:this.smallWritable}},[this.offscreen,this.bigReadable,this.smallWritable])}generateVideoTrack(){let t=new MediaStream([this.smallGenerator]);return t==null?void 0:t.getTracks()[0]}destroy(){this.worker.terminate()}},Al=pc;var iO=h(_());var mc=class{constructor(t){p(this,"_player");p(this,"_canvas");p(this,"_canvasCtx");this._player=t,this._canvas=document.createElement("canvas"),this._canvasCtx=this._canvas.getContext("2d")}setCanvasRect(t,e){!this._canvas||(this._canvas.width=t,this._canvas.height=e)}drawVideoToCanvas(){let t=this._player.getElement();this._canvas&&this._canvasCtx&&t&&this._canvasCtx.drawImage(t,0,0,this._canvas.width,this._canvas.height)}generateVideoTrack(t){return this._canvas.captureStream(t).getVideoTracks()[0]}generateStreamFromTrack(t){let e=new MediaStream;return e.addTrack(t),e}destroy(){var t;(t=this._player)==null||t.stop(),this._canvas&&(this._canvas.width=0,this._canvas.height=0,this._canvas=null,this._canvasCtx=null)}get canvas(){return this._canvas}get canvasCtx(){return this._canvasCtx}get canDrawVideoToCanvas(){if(this._player){let t=this._player.getElement();if(t)return t.readyState===t.HAVE_ENOUGH_DATA}return!1}},hc=mc;var _c=class{constructor(t){p(this,"_player");p(this,"_processor");p(this,"_initOffscreenSuccess");p(this,"_localVideoTrack");p(this,"_interval");this._localVideoTrack=t,this._player=t.player,this._processor=null,this._initOffscreenSuccess=!1}initialize(){return T(this,null,function*(){if(Wo()&&(navigator==null?void 0:navigator.hardwareConcurrency)>=6)try{yield this.initOffscreen(),this._initOffscreenSuccess=!0,P.info("Initialize VideoGenerator successfully!")}catch(t){this.initCanvas()}else this.initCanvas()})}generateSmallVideoTrack(t){let e=this.getSmallVideoProfile(t),r;return this._initOffscreenSuccess?(this._processor.setCanvasRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate)):(this._processor.setCanvasRect(e.width,e.height),this._player.setRect(e.width,e.height),r=this._processor.generateVideoTrack(e.frameRate),this._interval=le.run(Kt,this.render.bind(this),{fps:e.frameRate})),r}render(){this._processor instanceof hc&&this._processor.drawVideoToCanvas()}destroy(){le.clearTask(this._interval),this._processor&&this._processor.destroy()}initOffscreen(){this._processor=new Al({videoTrack:this._localVideoTrack.mediaTrack})}initCanvas(){this._player=new Ki({track:this._localVideoTrack.mediaTrack,muted:!0,objectFit:"cover",mirror:!1,container:null,id:"video-player",log:this._localVideoTrack.log}),this._player.play().then(()=>{P.info("VideoGenerator: play local video success")}).catch(()=>{P.error("VideoGenerator: Failed to play local video")}),this._processor=new hc(this._player)}getSmallVideoProfile(t){let e=this._localVideoTrack.mediaTrack,r=this._localVideoTrack.profile;if(fi){let c=e.getSettings();c&&c.width&&c.height&&(r.width=c.width,r.height=c.height)}let n,s=r.width*r.height,o=t.width*t.height;return P.info(`big res: ${r.width}*${r.height} small res: ${t.width}*${t.height} `),s>o?n=s/o:(P.warn(`Small stream resolution is larger than big stream, which is invalid. big: ${r.width} * ${r.height} small: ${t.width} * ${t.height}`),n=s/(160*120)),{width:r.width/Math.sqrt(n),height:r.height/Math.sqrt(n),frameRate:t.frameRate}}},sn=_c;var Cl={voiceActivityDetection:!1},fc=class extends ct{constructor(e){super(ie(w({},e),{isUplink:!0}));p(this,"localMainAudioTrack",null);p(this,"localMainVideoTrack",null);p(this,"localAuxAudioTrack",null);p(this,"localAuxVideoTrack",null);p(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});p(this,"_mixedAudioTrack",null);p(this,"_isSDPExchanging",!1);p(this,"_isPublishingAux",!1);p(this,"_publishingLocalAudioTrack");p(this,"_publishingLocalVideoTrack");p(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});p(this,"_smallGenerator");p(this,"_audioManager");this._audioManager=e.audioManager,this._smallGenerator=null}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var r,n,s,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Qt()?(e.audio=!!((r=a[0])!=null&&r.track),e.bigVideo=!!((n=a[1])!=null&&n.track),e.smallVideo=!!((s=a[2])!=null&&s.track),e.auxVideo=!!((o=a[3])!=null&&o.track)):a.forEach(c=>{c.track&&(c.track.kind===f.AUDIO?e.audio=!0:(e.bigVideo=!0,this._smallGenerator&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents(),this.localMainVideoTrack&&this.localMainVideoTrack.canvasTrack&&this.localMainVideoTrack.destoryCanvasTrack()}close(){super.close(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null)}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,r){var o,a,c;let n=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&n!==e&&(r?r.emit("connection-state-changed",{prevState:n,state:e}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:n,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:n,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:n,state:e}))),s}publish(s){return T(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,isAuxiliary:n}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),r&&(this._publishingLocalVideoTrack=r),this._isPublishingAux=n;let o;return r&&!n&&r.small&&(this._smallGenerator=new sn(r),yield this._smallGenerator.initialize(),o=this._smallGenerator.generateSmallVideoTrack(r.small)),this.updateMediaSettings(),$r()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:r,smallTrack:o,isAuxiliary:n}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:r,smallTrack:o}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,n?(r&&(this.localAuxVideoTrack=r),e&&(this.localAuxAudioTrack=e)):(r&&(this.localMainVideoTrack=r),e&&(this.localMainAudioTrack=e)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,r),this.sendMutedFlag(),{localAudioTrack:e,localVideoTrack:r}})}publishByTransceiver(o){return T(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n,isAuxiliary:s}){var l,m;this._log.info("publish by transceiver");let a=new MediaStream;r&&Wn&&xd&&r.genCanvasTrack();let c=(r==null?void 0:r.canvasTrack)||(r==null?void 0:r.mediaTrack),d=(l=this._audioManager)!=null&&l.isNeedToUseDestination()?(m=this._audioManager)==null?void 0:m.mediaStreamTrack:e==null?void 0:e.mediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||f.AUDIO,{direction:he.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?f.VIDEO:c||f.VIDEO,{direction:he.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n||f.VIDEO,{direction:he.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||f.VIDEO:f.VIDEO,{direction:he.SENDONLY,streams:[a]}),yield this.connect();else{let S=[];if(d&&(u[0].sender.track?yield u[0].sender.replaceTrack(d):(yield u[0].sender.replaceTrack(d),S.push(0)),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:f.AUDIO})),c){let E=s?3:1;yield u[E].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:r.profile.bitrate,type:f.VIDEO,videoType:s?f.AUXILIARY:f.BIG}),S.push(E),n&&(yield u[2].sender.replaceTrack(n),yield this.setBandwidth({bandwidth:r.small.bitrate,type:f.VIDEO,videoType:f.SMALL}),S.push(2))}yield this.setTransceiverDirection(he.SENDONLY,S),yield this.doPublishChange(),r==null||r.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),r==null||r.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return T(this,arguments,function*({localAudioTrack:e,localVideoTrack:r,smallTrack:n}){var d;this._log.info("publish by addtrack");let o=r==null?void 0:r.mediaTrack,a=e!=null&&e.mediaTrack?(d=this._audioManager)==null?void 0:d.mediaStreamTrack:null;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){a&&(yield this.addTrack(a,e)),o&&(yield this.addTrack(o,r));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),n)){let u=new MediaStream;u.addTrack(n),this._peerConnection.addTrack(n,u)}yield this.connect()})}installTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.on("mute",this.sendMutedFlag,this),r==null||r.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(r=>{r&&(r==null||r.off("mute",this.sendMutedFlag,this),r==null||r.off("unmute",this.sendMutedFlag,this))})}unpublish(n){return T(this,arguments,function*({localAudioTrack:e,localVideoTrack:r}){var u,l,m,S;if(!Qt()){if(e&&e.mediaTrack&&!r&&this.localMainVideoTrack){yield this.removeTrack(e.mediaTrack,e),this.localMainAudioTrack=null;return}if(r&&r.mediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(r.mediaTrack,r),this.localMainVideoTrack=null;return}let E=yield this.doUnpublish();return this.uninstallTrackMuteEvents(e,r),this.emitConnectionStateChangedEvent("DISCONNECTED",r),E}let s=r&&r===this.localAuxVideoTrack,o=e==null?void 0:e.mediaTrack,a=r==null?void 0:r.mediaTrack,c=this._peerConnection.getSenders(),d=[];if(o)if((u=this._audioManager)!=null&&u.isNeedToUseDestination()){if(((l=this._audioManager)==null?void 0:l.hasAudioTrack)&&this._audioManager.hasMusic&&(this._audioManager.destroyAllMusic(),yield c[0].replaceTrack(null)),this._audioManager.hasAudioTrack&&this._audioManager.hasScreenAudioTrack){let E=s?(m=this.localMainAudioTrack)==null?void 0:m.mediaTrack:(S=this.localAuxAudioTrack)==null?void 0:S.mediaTrack;yield c[0].replaceTrack(E||null)}}else yield c[0].replaceTrack(null),d.push(0),this.localMainAudioTrack=null;a&&(s?(yield c[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=ie(w({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield c[1].replaceTrack(null),yield c[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=ie(w({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(he.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,r),r==null||r.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return T(this,null,function*(){let r={state:this.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:pe.PUBLISH_STATE_CHANGE,data:r,responseCommand:se.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:pe.UNPUBLISH,commandDesc:"unpublish",responseCommand:se.UNPUBLISH_RESULT,enableLog:e}).catch(r=>{if(r.getCode()===M.API_CALL_TIMEOUT)return Promise.resolve();throw r})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:r}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":r&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),fi){if(n&&n.mediaTrack){let a=n.mediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.mediaTrack){let a=s.mediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(o&&o.mediaTrack){let a=o.mediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.profile.bitrate*1e3}}else n&&n.mediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=n.profile.bitrate*1e3,this._mediaSettings.audioFs=n.profile.sampleRate),s&&s.mediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:pe.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:se.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(this._log.warn)}addTrack(e,r){return T(this,null,function*(){var s;if(!this._peerConnection)return;let n=r===this.localAuxAudioTrack||r===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${n?f.AUXILIARY:f.MAIN} stream`),(s=this._sei)==null||s.handleEncodedStreams(),Qt()?yield this.addTrackByTransceiver(e,n):yield this.addTrackBySender(e,r)})}addTrackByTransceiver(e,r){return T(this,null,function*(){var s;let n=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)n[0].sender.track?(this.mixAudioTrack(n[0].sender.track,e),yield n[0].sender.replaceTrack(this._mixedAudioTrack)):yield n[0].sender.replaceTrack(e);else{let o=r?3:1;if(yield n[o].sender.replaceTrack(e),o===1&&((s=this.localMainVideoTrack)==null?void 0:s.small)){this._smallGenerator=new sn(this.localMainVideoTrack),yield this._smallGenerator.initialize();let a=this._smallGenerator.generateSmallVideoTrack(this.localMainVideoTrack.small);yield n[2].sender.replaceTrack(a)}n[o].direction===he.INACTIVE&&(yield this.setTransceiverDirection(he.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e,r){return T(this,null,function*(){Qt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",e));let n=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===e.kind);if(n&&n.track){this._log.warn("sender already exists, remove sender first");let o=n.track;this.removeSender(n),yield this.updateOffer("remove",o)}let{mediaStream:s}=r;if(this._peerConnection.addTrack(e,s),e.kind===f.VIDEO&&r instanceof st&&r.small){this._smallGenerator=new sn(r),yield this._smallGenerator.initialize();let o=this._smallGenerator.generateSmallVideoTrack(r.small),a=new MediaStream;a.addTrack(o),this._peerConnection.addTrack(o,a)}yield this.updateOffer("add",e)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===_r||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,r=At(e);for(let n=0;n<r.media.length;n++)if(Number(r.media[n].mid)===0&&r.media[n].type===f.VIDEO)return!0;return!1}removeSender(e){let r=null;Qt()&&(r=this._peerConnection.getTransceivers().find(n=>n.sender&&n.sender.track===e.track)),this._peerConnection.removeTrack(e),r&&oe(r.stop)&&(this._log.info("stop transceiver"),r.stop())}removeTrack(e,r){return T(this,null,function*(){if(!this._peerConnection)return;let n=r===this.localAuxAudioTrack||r===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${n?f.AUXILIARY:f.MAIN} stream`),Qt()?yield this.removeTrackByTransceiver(e,n):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,r){return T(this,null,function*(){var s,o;let n=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)if(this._mixedAudioTrack){let a=r?(s=this.localMainAudioTrack)==null?void 0:s.mediaTrack:(o=this.localAuxAudioTrack)==null?void 0:o.mediaTrack;yield n[0].sender.replaceTrack(a||null),this.destroyMixedAudioTrack()}else yield n[0].sender.replaceTrack(null);else{let a=r?3:1;yield n[a].sender.replaceTrack(null),a===1&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(he.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,r){return T(this,null,function*(){if(!we)return;let n=!1,s=!1;this._log.info(`setting transceiver ${r.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(r.forEach(d=>{o[d].direction!==e&&(o[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
95
+ `).map(d=>{if(d.match(new RegExp(`a=(${he.INACTIVE}|${he.RECVONLY}|${he.SENDONLY})`))&&a++,r.includes(a)){if(e===he.INACTIVE&&d.includes(`a=${he.RECVONLY}`))return s=!0,`a=${e}`;if(e===he.SENDONLY&&d.includes(`a=${he.INACTIVE}`))return s=!0,`a=${he.RECVONLY}`}return d}).join(`\r
96
+ `);s&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return T(this,null,function*(){var n,s;if(e.kind===f.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),(s=(n=this.localMainVideoTrack)==null?void 0:n.mediaStream)==null||s.removeTrack(e),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let r=this._peerConnection.getSenders().find(o=>o.track===e);r&&(this.removeSender(r),e.kind===f.VIDEO&&this._smallGenerator&&(this._smallGenerator.destroy(),this._smallGenerator=null,this._peerConnection.getSenders().forEach(o=>{o.track&&o.track.kind===f.VIDEO&&this.removeSender(o)}))),yield this.updateOffer("remove",e)})}replaceTrack(e,r){return T(this,null,function*(){var o,a,c;let n=(o=this._peerConnection)==null?void 0:o.getSenders();if(!n||n.length===0)return;let s=r===this.localAuxAudioTrack||r===this.localAuxVideoTrack;if(this._log.info(`is replacing ${e.kind} track on ${s?f.AUXILIARY:f.MAIN} stream`),e.kind===f.AUDIO&&n[0])if(this._mixedAudioTrack&&((a=this.localMainAudioTrack)==null?void 0:a.mediaTrack)&&((c=this.localAuxAudioTrack)==null?void 0:c.mediaTrack)){this.destroyMixedAudioTrack();let d=s?this.localMainAudioTrack.mediaTrack:this.localAuxAudioTrack.mediaTrack;this.mixAudioTrack(e,d),yield n[0].replaceTrack(this._mixedAudioTrack)}else yield n[0].replaceTrack(e);if(e.kind===f.VIDEO){if(!s&&n[1]&&(yield n[1].replaceTrack(e),this._smallGenerator&&n[2])){this._log.info("replacing smallVideo"),this._smallGenerator.destroy(),this._smallGenerator=new sn(this.localMainVideoTrack),yield this._smallGenerator.initialize();let d=this._smallGenerator.generateSmallVideoTrack(this._room.smallStreamConfig);yield n[2].replaceTrack(d)}s&&n[3]&&(yield n[3].replaceTrack(e))}})}updateOffer(e,r){return T(this,null,function*(){try{let n=yield this._peerConnection.createOffer(Cl);we&&n.sdp&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(n);let s=this.updateMediaSettings(),o={action:e,trackId:r.id,kind:r.kind===f.VIDEO?"bigVideo":r.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:s,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${o.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:pe.PUBLISH_CHANGE,data:o,responseCommand:se.UPDATE_OFFER_RESULT,timeout:Id,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),n.sdp&&this.updateSSRC(n.sdp)}catch(n){throw this._log.error(n),n}})}setBandwidth(o){return T(this,arguments,function*({bandwidth:e,type:r,videoType:n,sdp:s}){if(!Jo())return s?r===f.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e):void 0;let a=0;r===f.VIDEO&&(n===f.SMALL?a=2:n===f.AUXILIARY?a=3:a=1);let c=this._peerConnection.getSenders()[a];if(c){let d=c.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield c.setParameters(d),this._log.info(`${n||""}${r} bandwidth ${e} kbps`),s}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),s)return r===f.VIDEO?this.updateVideoBandwidthRestriction(s,e,n):this.updateAudioBandwidthRestriction(s,e)}}return s})}updateVideoBandwidthRestriction(e,r,n){let s="AS";we&&(s="TIAS",r=r*1e3);let o=0,a=-1;return n===f.SMALL?o=1:n===f.AUXILIARY&&(o=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===o?`${c}b=${s}:${r}\r
97
+ `:c)),e}updateAudioBandwidthRestriction(e,r){let n="AS";return we&&(n="TIAS",r=r*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
98
+ c=IN $2\r
99
+ b=${n}:${r}\r
100
+ `),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return T(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return T(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP(),this._isSDPExchanging=!1}catch(e){throw this._isSDPExchanging=!1,e}})}createOffer(){return T(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Cl);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:pe.PUBLISH,responseCommand:se.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof gt||this.localAuxVideoTrack instanceof gt,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(r=>{let{code:n,message:s,data:o}=r.data;return n===0?this.acceptAnswer(o):this.checkPublishResultCode(n,s)})}setSDPDirection(e,r,n="all"){let s=At(e);return s.media.forEach(o=>{(n==="all"||o.type===n)&&(o.direction=r)}),vi(s)}acceptAnswer(e){return T(this,null,function*(){var r,n,s,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let l=((r=this._publishingLocalVideoTrack)==null?void 0:r.profile.bitrate)||((n=this.localMainVideoTrack)==null?void 0:n.profile.bitrate),m=((s=this._publishingLocalAudioTrack)==null?void 0:s.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(l){let S=this._isPublishingAux?f.AUXILIARY:f.BIG;c=yield this.setBandwidth({bandwidth:l,type:f.VIDEO,sdp:c,videoType:S})}m&&(c=yield this.setBandwidth({bandwidth:m,type:f.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:l}=this._room;c=yield this.setBandwidth({bandwidth:l.bitrate,type:f.VIDEO,videoType:f.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var s,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let n={audio:!!((s=this.localMainAudioTrack)!=null&&s.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(n)}`),this._signalChannel.send(pe.UPDATE_MUTE_STAT,n)}getIsReconnecting(){return this._isReconnecting}reconnect(){return T(this,null,function*(){if(!(oi(fc.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:pe.UNPUBLISH,responseCommand:se.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(r){let n=ft(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${n/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},n)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&C.emit(I.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{At(e).media.forEach((n,s)=>{if(n.type===f.AUDIO){let o=n.ssrcs&&n.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===_r&&n.ssrcGroups){n.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let o=n.ssrcs&&n.ssrcs[0];if(!o)return;switch(s){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.id);break;default:break}}})}catch(r){}}getVideoTrackId(e=f.VIDEO){if(this._peerConnection){let r=this._peerConnection.getSenders();if(e===f.AUXILIARY&&r[3]&&r[3].track)return r[3].track.id;if(e===f.VIDEO&&r[1]&&r[1].track)return r[1].track.id}if(this.localMainVideoTrack&&e===f.VIDEO){let r=this.localMainVideoTrack.mediaTrack;if(r)return r.id}if(this.localAuxVideoTrack&&e===f.AUXILIARY){let r=this.localAuxVideoTrack.mediaTrack;if(r)return r.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,r){if(e!==0)throw e===bn?(this._log.error(Be.NOT_SUPPORTED_H264ENCODE),new V({code:M.NOT_SUPPORTED_H264,message:H({key:$.NOT_SUPPORTED_H264ENCODE})})):new V({code:M.UNKNOWN,message:H({key:$.SIGNAL_RESPONSE_FAILED,data:{signalResponse:se.PUBLISH_RESULT,code:e,message:r}})})}sendSEI(e,r){var n;(n=this._sei)==null||n.push(e,r)}mixAudioTrack(e,r){this._log.info("mix audio track"),this._mixedAudioTrack=gl([e,r])}destroyMixedAudioTrack(){this._mixedAudioTrack&&(this._log.info("destroy audio track"),Rl(this._mixedAudioTrack),this._mixedAudioTrack=null)}},Ls=fc;G([Yi(ct.prototype.afterConnect),us(ct.prototype.beforeConnect)],Ls.prototype,"connect",1);var vl=Ls;var qO=h(_());var on=class{constructor(t,e){p(this,"_log");p(this,"_prevReportTime");p(this,"_prevReport",{});p(this,"_prevEncoderImplementation");p(this,"_prevQualityLimitationReason");p(this,"_prevDecoderImplementationMap",new Map);this._log=e,this._prevReportTime=0,this._prevEncoderImplementation="",this._prevQualityLimitationReason=""}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(t){return T(this,null,function*(){var s;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},r=t.getPeerConnection(),n=t.getSSRC();if(r)try{(yield r.getStats()).forEach(a=>{if(a.type==="outbound-rtp")if(a.mediaType===f.VIDEO){if(!we&&N(a.trackId))return;a.ssrc===n.video&&!N(a.encoderImplementation)&&this._prevEncoderImplementation!==a.encoderImplementation&&(this._log.info(`encoderImplementation change to ${a.encoderImplementation}`),this._prevEncoderImplementation=a.encoderImplementation),a.ssrc===n.video&&!N(a.qualityLimitationReason)&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),this._prevQualityLimitationReason=a.qualityLimitationReason);let c=f.VIDEO;a.ssrc===n.small?c=f.SMALL:a.ssrc===n.auxiliary&&(c=f.AUXILIARY),e[c].bytesSent=a.bytesSent,e[c].packetsSent=a.packetsSent,e[c].framesEncoded=a.framesEncoded}else a.mediaType===f.AUDIO&&(e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent);else a.type==="candidate-pair"?Hi(a)&&ce(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3)):a.type==="media-source"&&(a.kind===f.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0):a.kind===f.VIDEO&&(a.trackIdentifier===t.getVideoTrackId(f.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===t.getVideoTrackId(f.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(N(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0),!N(a.frameWidth)){let c=f.SMALL;a.trackIdentifier===t.getVideoTrackId(f.VIDEO)||a.ssrc===n.video?c=f.VIDEO:(a.trackIdentifier===t.getVideoTrackId(f.AUXILIARY)||a.ssrc===n.auxiliary)&&(c=f.AUXILIARY),e[c].frameWidth=a.frameWidth,e[c].frameHeight=a.frameHeight,e[c].framesSent=a.framesSent}}),e.audio.audioLevel===0&&(e.audio.audioLevel=((s=t.localMainAudioTrack)==null?void 0:s.getInternalAudioLevel())||0)}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(t){return T(this,null,function*(){let e={tinyId:t.tinyId,userId:t.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,jitter:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0}},r=t.getPeerConnection();if(r)try{let{ssrc:n}=t,{muteState:s}=t;(yield r.getStats()).forEach(a=>{if(a.type==="inbound-rtp"){if(a.mediaType===f.AUDIO&&a.ssrc===n.audio&&s.hasAudio){e.audio.packetsReceived=a.packetsReceived,e.audio.bytesReceived=a.bytesReceived,e.audio.packetsLost=a.packetsLost,a.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=a.insertedSamplesForDeceleration),a.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=a.removedSamplesForAcceleration);let{remoteAudioTrack:c}=t;c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)),e.hasAudio=!0}else if(a.mediaType===f.VIDEO){if(we&&a.bytesReceived===0)return;let c;a.ssrc===n.video&&s.hasVideo&&(e.video.packetsReceived=a.packetsReceived,e.video.bytesReceived=a.bytesReceived,e.video.packetsLost=a.packetsLost,e.video.framesReceived=a.framesReceived,e.video.framesDecoded=a.framesDecoded,e.video.fpsDecoded=a.framesPerSecond,e.hasVideo=!0,c=t.remoteVideoTrack,a.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==a.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${a.decoderImplementation}`),this._prevDecoderImplementationMap.set(e.userId,a.decoderImplementation))),a.ssrc===n.auxiliary&&s.hasAuxiliary&&(e.auxiliary.packetsReceived=a.packetsReceived,e.auxiliary.bytesReceived=a.bytesReceived,e.auxiliary.packetsLost=a.packetsLost,e.auxiliary.framesReceived=a.framesReceived,e.auxiliary.framesDecoded=a.framesDecoded,e.auxiliary.fpsDecoded=a.framesPerSecond,c=t.remoteAuxiliaryTrack,e.hasAuxiliary=!0),c&&(c.stat.packetsReceived=a.packetsReceived,c.stat.bytesReceived=a.bytesReceived,c.stat.packetsLost=a.packetsLost,c.stat.framesReceived=a.framesReceived,c.stat.framesDecoded=a.framesDecoded,a.jitterBufferDelay&&(c.stat.jitterBufferDelay=Math.floor(a.jitterBufferDelay/a.jitterBufferEmittedCount*1e3)))}}else a.type==="candidate-pair"&&Hi(a)&&ce(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3));N(a.frameWidth)||((a.trackIdentifier===t.getMainStreamVideoTrackId()||a.ssrc===n.video)&&(e.video.frameWidth=a.frameWidth,e.video.frameHeight=a.frameHeight,t.remoteVideoTrack.stat.frameWidth=a.frameWidth,t.remoteVideoTrack.stat.frameHeight=a.frameHeight),(a.trackIdentifier===t.getAuxStreamVideoTrackId()||a.ssrc===n.auxiliary)&&(e.auxiliary.frameWidth=a.frameWidth,e.auxiliary.frameHeight=a.frameHeight,t.remoteAuxiliaryTrack.stat.frameWidth=a.frameWidth,t.remoteAuxiliaryTrack.stat.frameHeight=a.frameHeight)),N(a.audioLevel)||(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0)}),e.audio.audioLevel===0&&(e.audio.audioLevel=t.remoteAudioTrack.getInternalAudioLevel()||0)}catch(n){this._log.warn(`failed to getStats on receiver connection ${n}`)}return e})}getStats(t,e){return T(this,null,function*(){let r={};t&&(r=yield this.getSenderStats(t));let n=[];for(let[s,o]of e){let a=yield this.getReceiverStats(o);n.push(a)}return{senderStats:r,receiverStats:n}})}getDifferenceValue(t,e){if(ji(t))return e;let r=e-t;return r<0?0:r}prepareReport({stats:t,report:e,freezeMap:r}){if(!ji(t.senderStats)){let u={uint32_audio_level:t.senderStats.audio.audioLevel*mi,uint32_audio_energy:t.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent},l=[],m={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded};if(l.push(m),t.senderStats.small.bytesSent){let E={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0};l.push(E)}if(t.senderStats.auxiliary.bytesSent){let E={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0};l.push(E)}let S={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:u,msg_video_status:l,msg_network_status:S}}let{statInterval:n}=this;e.msg_down_stream_info=[],t.receiverStats.forEach(u=>{let l={msg_user_info:{str_identifier:u.userId,uint64_tinyid:u.tinyId},msg_network_status:{uint32_rtt:u.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(u.hasAudio){let m={uint32_audio_codec_bitrate:u.audio.bytesReceived,uint32_audio_total_bitrate:u.audio.bytesReceived,uint32_audio_level:u.audio.audioLevel*1e8,uint32_audio_energy:u.audio.totalAudioEnergy*1e6,uint32_audio_receive:u.audio.packetsReceived,uint32_audio_origin_lost:u.audio.packetsLost};l.msg_audio_status=m}if(u.hasVideo){let m=r.get(`${u.userId}_${Ed}`),S=m?m.duration:0,E={uint32_video_stream_type:2,uint32_video_receive_fps:u.video.framesReceived,uint32_video_width:u.video.frameWidth,uint32_video_height:u.video.frameHeight,uint32_video_codec_bitrate:u.video.bytesReceived,uint32_video_receive:u.video.packetsReceived,uint32_video_origin_lost:u.video.packetsLost,uint32_video_block_time:S,uint32_video_dec_fps:u.video.framesDecoded};l.msg_video_status.push(E)}if(u.hasAuxiliary){let m=r.get(`${u.userId}_${Dn}`),S=m?m.duration:0,E={uint32_video_stream_type:7,uint32_video_receive_fps:u.auxiliary.framesReceived,uint32_video_width:u.auxiliary.frameWidth,uint32_video_height:u.auxiliary.frameHeight,uint32_video_codec_bitrate:u.auxiliary.bytesReceived,uint32_video_receive:u.auxiliary.packetsReceived+u.auxiliary.packetsLost,uint32_video_origin_lost:u.auxiliary.packetsLost,uint32_video_block_time:S,uint32_video_dec_fps:u.auxiliary.framesDecoded};l.msg_video_status.push(E)}e.msg_down_stream_info.push(l)});let s=this._prevReport;if(this._prevReport=JSON.parse(JSON.stringify(e)),e.msg_up_stream_info.msg_audio_status&&s.msg_up_stream_info.msg_audio_status){let u=s.msg_up_stream_info.msg_audio_status,l=e.msg_up_stream_info.msg_audio_status,m=this.getDifferenceValue(u.uint32_audio_codec_bitrate,l.uint32_audio_codec_bitrate);l.uint32_audio_codec_bitrate=Math.round(m*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=l.uint32_audio_codec_bitrate}let o=s.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(u=>{let l=o.find(B=>B.uint32_video_stream_type===u.uint32_video_stream_type);if(!l||l.uint32_video_codec_bitrate===0){u.uint32_video_codec_bitrate=0,u.uint32_video_enc_fps=0,u.uint32_video_codec_fps=0;return}let m=l.uint32_video_codec_bitrate,S=l.uint32_video_enc_fps,E=l.uint32_video_codec_fps,y=this.getDifferenceValue(m,u.uint32_video_codec_bitrate);u.uint32_video_codec_bitrate=Math.round(y*8/n),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=u.uint32_video_codec_bitrate,u.uint32_video_enc_fps=Math.round(this.getDifferenceValue(S,u.uint32_video_enc_fps)/n),u.uint32_video_codec_fps=Math.round(this.getDifferenceValue(E,u.uint32_video_codec_fps)/n)});let c=e.msg_down_stream_info,d=s.msg_down_stream_info;return c.forEach(u=>{let l=d.find(m=>m.msg_user_info.uint64_tinyid===u.msg_user_info.uint64_tinyid);if(!!l){if(u.msg_audio_status&&l.msg_audio_status){let m=u.msg_audio_status,S=l.msg_audio_status;m.uint32_audio_origin_lost=this.getDifferenceValue(S.uint32_audio_origin_lost,m.uint32_audio_origin_lost),m.uint32_audio_receive=this.getDifferenceValue(S.uint32_audio_receive,m.uint32_audio_receive),m.uint32_audio_receive+=m.uint32_audio_origin_lost;let E=this.getDifferenceValue(S.uint32_audio_codec_bitrate,m.uint32_audio_codec_bitrate);m.uint32_audio_codec_bitrate=Math.round(E*8/n),m.uint32_audio_total_bitrate=Math.round(E*8/n)}if(u.msg_video_status&&l.msg_video_status){let m=l.msg_video_status;u.msg_video_status=u.msg_video_status.filter(E=>m.find(y=>y.uint32_video_stream_type===E.uint32_video_stream_type)),u.msg_video_status.forEach(E=>{let y=m.find(J=>J.uint32_video_stream_type===E.uint32_video_stream_type),B=y.uint32_video_receive,x=y.uint32_video_origin_lost,F=y.uint32_video_codec_bitrate,Ee=y.uint32_video_receive_fps,A=y.uint32_video_dec_fps;E.uint32_video_origin_lost=this.getDifferenceValue(x,E.uint32_video_origin_lost),E.uint32_video_receive=this.getDifferenceValue(B,E.uint32_video_receive)+E.uint32_video_origin_lost;let U=this.getDifferenceValue(F,E.uint32_video_codec_bitrate);E.uint32_video_codec_bitrate=Math.round(U*8/n);let v=this.getDifferenceValue(Ee,E.uint32_video_receive_fps);E.uint32_video_receive_fps=Math.round(v/n),E.uint32_video_dec_fps=Math.round(this.getDifferenceValue(A,E.uint32_video_dec_fps)/n)})}}}),e}getStatsReport(n){return T(this,arguments,function*({uplinkConnection:t,downlinkConnections:e,freezeMap:r}){let s={msg_up_stream_info:{msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_codec_fps:0,uint32_video_capture_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_final_lost:0,uint32_video_enc_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_format:0,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},o=yield this.getStats(t,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(s))),this.prepareReport({stats:o,report:s,freezeMap:r}),this._prevReportTime=Date.now(),s})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var ub=h(_());var yl=h(rt());var Ec=class extends yl.default{constructor({signalChannel:e,room:r}){super();p(this,"_room");p(this,"_signalChannel");p(this,"_log");p(this,"_uplinkRTT",0);p(this,"_uplinkLoss",0);p(this,"_downlinkRTT",0);p(this,"_downlinkLoss",0);p(this,"_downlinkPrevStatMap",new Map);p(this,"_downlinkLossAndRTTMap",new Map);p(this,"_interval",-1);p(this,"_uplinkNetworkQuality",0);p(this,"_downlinkNetworkQuality",0);this._room=r,this._signalChannel=e,this._log=P.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink network quality change ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:r,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink network quality change ${this.downlinkNetworkQuality} -> ${e}, rtt: ${r}, loss: ${n}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(se.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(ve.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let r=e.data.data;if(r.delay&&this.updateDelay(r.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let n=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(n&&this.isPeerConnectionDisconnected(n)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=r.expectAudPkg+r.expectVidPkg,o=r.recvAudPkg+r.recvVidPkg,a=s-o;s===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/s*100),this._uplinkRTT=r.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return T(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],r=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===De.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<r.length;a++){let c=r[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:u,totalPacketsReceived:l}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l});continue}let m=0,S=this._downlinkPrevStatMap.get(c),E=u-S.totalPacketsLost,y=l-S.totalPacketsReceived;E<=0||y<0?m=0:m=Math.round(E/(E+y)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:l}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:m,userId:r[a].getUserId(),audioDelay:r[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:r[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:s,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=s,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,s)})}getStat(e){return T(this,null,function*(){let r={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Br())return r;let n=e.getReceivers();try{for(let s=0;s<n.length;s++)(yield n[s].getStats()).forEach(c=>{c.type==="candidate-pair"&&ce(c.currentRoundTripTime)&&(r.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===f.AUDIO||c.mediaType===f.VIDEO)&&(r.totalPacketsLost+=c.packetsLost,r.totalPacketsReceived+=c.packetsReceived)});return r}catch(s){return r}})}getAverageLossAndRTT(e){let r={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(n=>{r.rtt+=n.rtt,r.loss+=n.loss}),Object.keys(r).forEach(n=>{r[n]=Math.round(r[n]/e.length)})),r}getNetworkQuality(e,r){return e>50||r>500?5:e>30||r>350?4:e>20||r>200?3:e>10||r>100?2:e>=0||r>=0?1:0}handleSignalConnectionStateChange(e){e.state===Ke.DISCONNECTED?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state===Ke.CONNECTED&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===De.DISCONNECTED||e.connectionState===De.FAILED||e.connectionState===De.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on(lu.CONNECTION_STATE_CHANGED,this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=le.run(vt,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];C.emit(I.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(Ec.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{delay:2e3})}stop(){this._log.info("stop network quality calculating"),this._interval!==-1&&(le.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:r}=this._room;e.forEach(({srcTinyId:n,videoDelay:s,audioDelay:o})=>{let a=r.get(n);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:s,audioDelay:o})}})}},yi=Ec;p(yi,"EVENT_NETWORK_QUALITY","0");var LM=h(_(),1);var kb=h(_(),1);var _b=h(_(),1);var $t=new WeakMap;function an({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(n,s,o){let a=Tt({retryFunction:o.value,settings:i,onError(c,d,u){t&&t.call(this,c,()=>{var l;(l=$t.get(n))!=null&&l.has(s)?d():u(c)},u)},onRetrying:(c,d)=>{var u;oe(e)&&e(c,d),(u=$t.get(n))!=null&&u.has(s)&&($t.get(n).get(s).stopRetry=d)},onRetryFailed:r});return o.value=function(...c){let d=$t.get(n);return d?d.set(s,{args:c}):$t.set(n,new Map([[s,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=$t.get(n))==null?void 0:u.delete(s)})},o}}function cn({fnName:i,callback:t,validateArgs:e=!0}){return function(r,n,s){let o=s.value;return s.value=function(...a){var c,d;if((c=$t.get(r))!=null&&c.has(i)){let{stopRetry:u,args:l}=$t.get(r).get(i),m=!0;if(e){for(let S of l)if(!a.find(E=>E===S)){m=!1;break}}m&&(t&&t.apply(this,a),u&&u(),(d=$t.get(r))==null||d.delete(i))}return o.apply(this,a)},s}}var ks=class{constructor(t){p(this,"_frameWorkType");p(this,"_component");p(this,"_room");p(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});p(this,"_keyPrefix");p(this,"_log");p(this,"_intervalId");p(this,"_firstPublishedUserList");p(this,"_networkQuality");p(this,"_basicInfo");p(this,"_pathJoinRoom");p(this,"_pathLeaveRoom");p(this,"_pathMainVideoMap");p(this,"_pathMainAudioMap");p(this,"_pathAuxiliaryMap");p(this,"_remoteStreamStatMap");p(this,"_localStreamStat");p(this,"_apiSuccessRateMap",new Map);p(this,"_eventMap",new Map);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this._room=t.room,this._keyPrefix="key_point",this._log=P.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&oe(this[e])&&(this[e]=xo({fn:this[e],context:this}))}),this.initData(),this.installEvents(),this._intervalId=le.run(vt,this.setStorage.bind(this),{delay:2e4})}get _storageKey(){return`${this._keyPrefix}_${this._room.userId}`}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Ve,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:ci[Jn()],uint32_framework:this._frameWorkType,uint32_component:this._component},this._pathJoinRoom={uint64_start_time:0,uint64_init_audio_start_time:0,uint64_init_audio_end_time:0,uint64_init_camera_start_time:0,uint64_init_camera_end_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_init_audio_ret:0,int32_init_camera_ret:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,this._apiSuccessRateMap.clear()}addEvent(t,e){return this._eventMap.set(t,e),C.on(t,e),this}installEvents(){this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(I.JOIN_START,this.handleJoinStart).addEvent(I.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(I.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(I.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(I.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(I.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(I.JOIN_FAILED,this.handleJoinFailed).addEvent(I.LEAVE_START,this.handleLeaveStart).addEvent(I.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(I.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(I.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(I.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(I.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(I.PUBLISH_START,this.handlePublishStart).addEvent(I.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(I.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(I.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(I.PLAY_TRACK_START,this.handlePlayStart).addEvent(I.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(I.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!qt(t)||!this.hitTest(t.room)||e==="PLAYING"&&(r===f.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(I.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(I.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(I.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(I.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let n=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,o=r.hasAudio||r.hasVideo||r.hasSmall,a=r.hasAuxiliary;!n&&o&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&a&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(I.API_SUCCESS_RATE,this.handleAPISuccessRate)}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),le.clearTask(this._intervalId)}handleJoinStart(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now(),this.checkStorage())}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof V?Number(e.getExtraCode()||e.getCode()):M.UNKNOWN,this._pathJoinRoom.int32_end_ret=2))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=3))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=3),this.report())}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){!this.hitTest(t)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var n;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:ie(w({},T_),{msg_user_info:new dn({userId:t,tinyId:(n=this._room.remotePublishedUserMap.get(t))==null?void 0:n.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:n}){if(!this.hitTest(t))return;let{userId:s,tinyId:o,role:a}=e,c=new dn({userId:s,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),u=`${s}_${r}`,l=this._remoteStreamStatMap.get(u);l&&l.subscribeStartTime===0&&(l.subscribeStartTime=d),r==="main"?(e.muteState.hasVideo&&(n.video||n.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&n.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&n.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:d})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let n=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(n);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!qt(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!qt(t)||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),n=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(n&&(n.statsToReport.uint64_render_first_frame_time===0&&(n.statsToReport.uint64_render_first_frame_time=r),s)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-n.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&s){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=s;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=r-o.sendSubscribeCMDTime)}}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:n,videoDelay:s,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(n);if(a)a.totalRTT+=e,a.totalLoss+=r,s&&(a.totalVideoDelay=(a.totalVideoDelay||0)+s,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,u,l;s&&(d=s,u=1),o&&(c=o,l=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(n,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:l,videoDelayCount:u})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_up_stream_info:e,msg_down_stream_info:r}=t.report;if(e.msg_video_status[0]){let{uint32_video_codec_bitrate:n,uint32_video_enc_fps:s,uint32_video_width:o,uint32_video_height:a}=e.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=s,this._localStreamStat.totalVideoWidth+=o,this._localStreamStat.totalVideoHeight+=a,this._localStreamStat.videoCount++}if(e.msg_audio_status){let{uint32_audio_level:n}=e.msg_audio_status;Math.floor(n/mi*100)>0&&(this._localStreamStat.totalAudioLevel+=n/mi,this._localStreamStat.audioLevelCount++)}r.forEach(n=>{let{msg_user_info:s,msg_audio_status:o,msg_video_status:a}=n,c=s.str_identifier,d=this._room.remotePublishedUserMap.get(c);if(a.forEach(u=>{let l=u.uint32_video_stream_type===2,m=u.uint32_video_stream_type===7,S=`${c}_${l?"main":"auxiliary"}`,E=this._remoteStreamStatMap.get(S);if(!!E&&(l&&(d==null?void 0:d.remoteVideoTrack.isSubscribed)||m&&(d==null?void 0:d.remoteAuxiliaryTrack))){E.totalVideoFPS+=u.uint32_video_receive_fps,E.totalVideoBitrate+=u.uint32_video_codec_bitrate,E.videoCount++,E.statsToReport.uint32_video_width===0&&(E.statsToReport.uint32_video_width=u.uint32_video_width),E.statsToReport.uint32_video_height===0&&(E.statsToReport.uint32_video_height=u.uint32_video_height);let y=l?d.remoteVideoTrack:d.remoteAuxiliaryTrack;y.stat.jitterBufferDelay&&(E.videoJitterBufferDelay=y.stat.jitterBufferDelay),y.stat.framesReceived&&(E.statsToReport.uint32_video_consume_render_rate=Math.floor(y.stat.framesDecoded/y.stat.framesReceived*En(10,6)))}}),o){let u=`${c}_${"main"}`,l=this._remoteStreamStatMap.get(u);this._remoteStreamStatMap.has(u)&&l&&(d==null?void 0:d.remoteAudioTrack.isSubscribed)&&(l.totalAudioBitrate+=o.uint32_audio_codec_bitrate,l.audioCount++,d.remoteAudioTrack.stat.jitterBufferDelay&&(l.audioJitterBufferDelay=d.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(o.uint32_audio_level/mi*100)>0&&(l.totalAudioLevel+=o.uint32_audio_level/mi,l.audioLevelCount++))}})}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_start_time===0&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_start_time===0&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5},n=e instanceof V?e.getExtraCode()||e.getCode():r[e.name]||M.UNKNOWN;t.mediaType===1&&this._pathJoinRoom.uint64_init_audio_end_time===0&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&this._pathJoinRoom.uint64_init_camera_end_time===0&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleAPISuccessRate({room:t,apiName:e,error:r,cost:n}){if(!this.hitTest(t))return;let s=Nl[e],o={uint32_function_request_type:s,uint32_avg_value:0,uint32_max_value:0,uint32_request_count:1,uint32_success_count:0,msg_error_code:[]};if(r){let{code:c,extraCode:d}=r;Ae.uploadEvent({log:`stat-${e}-failed-${d||c||M.UNKNOWN}`,userId:this._room.userId,error:r});let u={int32_error_code:d||c,error_count:1};o.msg_error_code.push(u)}else ce(n)&&(o.uint32_avg_value=n,o.uint32_max_value=n,o.uint32_success_count=1);let a=this._apiSuccessRateMap.get(s);a?(a.uint32_success_count+o.uint32_success_count>0&&(a.uint32_avg_value=(a.uint32_avg_value*a.uint32_success_count+o.uint32_avg_value)/(a.uint32_success_count+o.uint32_success_count)),a.uint32_max_value=Math.max(a.uint32_max_value,o.uint32_max_value),a.uint32_request_count+=1,a.uint32_success_count=a.uint32_success_count+o.uint32_success_count,o.msg_error_code.forEach(c=>{let d=a.msg_error_code.find(u=>u.int32_error_code===c.int32_error_code);d?d.error_count+=1:a.msg_error_code.push(c)})):this._apiSuccessRateMap.set(s,o)}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&lr)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&pr)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&yn)>=0}hitTest(t){return t===this._room}checkStorage(){return T(this,null,function*(){try{let t=Fi.getItem(this._storageKey);t&&(yield this.upload(t),Fi.deleteItem(this._storageKey))}catch(t){this._log.warn(t)}})}setStorage(){this.prepareReport();let t=this.getReportData();t.msg_path_enter_room.uint64_start_time!==0&&Fi.setItem(this._storageKey,t)}prepareReport(){if(this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(n){let{totalLoss:u,count:l,audioDelayCount:m,videoDelayCount:S,totalAudioDelay:E,totalVideoDelay:y}=n;t.statsToReport.uint32_avg_down_loss=Math.floor(u/l),m&&E&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(E/m),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),S&&y&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(y/S))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,f.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,f.VIDEO)),t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,Ni);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=c,t.statsToReport.uint32_video_block_time=Math.min(a,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),o.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0,(t.subscribeStartTime===0||t.subscribeStartTime-t.streamAddedTime>100||t.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),t.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>Ni&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+Ni)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>Ni&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+Ni)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Ni&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Ni)}getReportData(){return{uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new dn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Vr(this._signalInfo.relayIp),uint32_client_ip:Vr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*2147483648),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Vr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,msg_function_request_stats:[...this._apiSuccessRateMap.values()]}}report(){return T(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),Fi.deleteItem(this._storageKey),this.initData()}catch(t){this._log.warn(t)}})}upload(t){return T(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0||[ao,ud,ld].findIndex(s=>s===location.host)>=0)return;let e=Number(this._room.sdkAppId),r=hi(e,ki.KEY_POINT),n=yield zt({url:r,body:JSON.stringify(t)});if(n.data!=="ok")throw`key point upload failed: ${n.data}`})}};G([an({settings:{timeout:500,retries:3}})],ks.prototype,"upload",1);var Ni=5e3,T_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},dn=class{constructor(t){p(this,"str_identifier");p(this,"str_tinyid");p(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Nl=(g=>(g[g.enterRoom=50001]="enterRoom",g[g.exitRoom=50002]="exitRoom",g[g.switchRole=50003]="switchRole",g[g.destroy=50004]="destroy",g[g.startLocalAudio=50005]="startLocalAudio",g[g.updateLocalAudio=50006]="updateLocalAudio",g[g.stopLocalAudio=50007]="stopLocalAudio",g[g.startLocalVideo=50008]="startLocalVideo",g[g.updateLocalVideo=50009]="updateLocalVideo",g[g.stopLocalVideo=50010]="stopLocalVideo",g[g.startScreenShare=50011]="startScreenShare",g[g.updateScreenShare=50012]="updateScreenShare",g[g.stopScreenShare=50013]="stopScreenShare",g[g.enableAudioVolumeEvaluation=50014]="enableAudioVolumeEvaluation",g[g.startRemoteVideo=50015]="startRemoteVideo",g[g.updateRemoteVideo=50016]="updateRemoteVideo",g[g.stopRemoteVideo=50017]="stopRemoteVideo",g[g.muteRemoteAudio=50018]="muteRemoteAudio",g[g.setRemoteAudioVolume=50019]="setRemoteAudioVolume",g[g.startMixTranscode=50020]="startMixTranscode",g[g.stopMixTranscode=50021]="stopMixTranscode",g[g.startPublishCDNStream=50022]="startPublishCDNStream",g[g.stopPublishCDNStream=50023]="stopPublishCDNStream",g[g.PeerConnectionConnect=50024]="PeerConnectionConnect",g[g.PeerConnectionReconnect=50025]="PeerConnectionReconnect",g[g.WebsocketConnect=50026]="WebsocketConnect",g[g.WebsocketReconnect=50027]="WebsocketReconnect",g[g.schedule=50028]="schedule",g))(Nl||{}),Dl=ks;var Jb=h(_(),1);var wb=h(_(),1);var Tc=class{constructor(){p(this,"_startTime");p(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ee())}stop(){this._endTime===0&&(this._endTime=ee())}getDuration(){return this._endTime===0?ee()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},rr=Tc;var Sc=class{constructor(t){p(this,"_room",null);p(this,"_durationMap");p(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(I.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(I.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var o;let{userId:n}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${n}_${"main"}`,f.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${n}_${"main"}`,f.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${n}_${"auxiliary"}`,f.VIDEO);let s=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(n);!s||(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(n,f.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(n,f.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(n,f.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}handleSubscribed({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;if(r.muteState.hasAudio&&e==="main")if(r.remoteAudioTrack.isSubscribed){let o=new rr,a=this._durationMap.get(s);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[o],video:[]})}else this.stopDurationItem(s,f.AUDIO);if(r.muteState.hasVideo||r.muteState.hasAuxiliary)if(r.remoteVideoTrack.isSubscribed||r.remoteAuxiliaryTrack.isSubscribed){let o=new rr,a=this._durationMap.get(s);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(s,{userId:n,type:e,audio:[],video:[o]})}else this.stopDurationItem(s,f.VIDEO)}handleStreamStopped({room:t,streamType:e,remotePublishedUser:r}){if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDurationItem(s,f.AUDIO),this.stopDurationItem(s,f.VIDEO)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let n=`${t}_${r}`,s=new rr,o=this._durationMap.get(n);o?this.isRecording(o[e])||o[e].push(s):this._durationMap.set(n,{userId:t,type:r,audio:e===f.AUDIO?[s]:[],video:e===f.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let n=this._durationMap.get(t)[e].find(s=>s.endTime===0);n&&n.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((n,s)=>n+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},Ol=Sc;var aP=h(_(),1);var Ic=class{constructor(t){p(this,"_room");p(this,"_renderFreezeMap",new Map);p(this,"_isVideoPlayingEventFiredMap",new Map);p(this,"_dataFreezeMap",new Map);p(this,"_monitorFreezeData",new Map);p(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}installEvents(){this._eventMap.set(I.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(I.PLAY_TRACK_START,this.onPlayTrackStart).set(I.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:n}=r,s=`${n}_${e}`;this.stopDataFreeze({key:s,userId:n,type:e})}).set(I.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:n}=r;if(e.hasVideo&&!r.hasVideo){let s="main",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",o=`${r.userId}_${s}`;this.stopDataFreeze({key:o,userId:n,type:s})}}).set(I.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:n})=>{if(!(!qt(t)||!this.hitTest(t.room)||n!==f.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===f.MUTE?this.onVideoTrackMuted(t):r===f.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(I.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>C.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>C.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){let{userId:e,streamType:r}=t,n=`${e}_${r}`,s=this._dataFreezeMap.get(n),o=new rr;s?s.durationItemList.push(o):this._dataFreezeMap.set(n,{userId:e,type:r,durationItemList:[o],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(t){let{userId:e,streamType:r}=t,n=`${e}_${r}`;this.stopDataFreeze({key:n,userId:e,type:r})}onHearBeatReport({room:t,report:e}){!this.hitTest(t)||e.msg_down_stream_info.forEach(r=>{let n=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!n)return;let{userId:s,muteState:o}=n;r.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&this.handleRenderFreeze({userId:s,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let n=this._dataFreezeMap.get(t);if(!n||!n.isFreezing())return;let s=n.durationItemList[n.durationItemList.length-1];s.stop();let o=s.getDuration();o>_o?this._monitorFreezeData.set(t,{userId:e,type:r,duration:o}):n.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let n=r.getDuration();return e+Math.min(n,5e3)},0)}handleRenderFreeze(n){return T(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,o=this._renderFreezeMap.get(s);if(e<=2){let a=ee();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=ee();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:t}){if(!qt(t)||!this.hitTest(t.room)||t.kind!==f.VIDEO||t.hasFlag)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let n=r.durationItemList[r.durationItemList.length-1];n.stop(),n.getDuration()<_o&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,n=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=ee(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=s-o.startTime;r=e.renderFreezeTotal+Math.min(a,5e3),n=e.freezeTimeline.length}return{renderFreeze:r,count:n}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},bl=Ic;var AP=h(_(),1);var Ml=h(gc(),1);var Rc=class{constructor(t){p(this,"_room");p(this,"_log");p(this,"_config",null);p(this,"_data");p(this,"_remoteVideoTrackMap",new Map);this._room=t,this._log=P.createLogger({id:"mix",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.installEvents()}get isPresetLayoutMode(){return this._config&&this._config.mode===li.MODE.PRESET_LAYOUT}get isMixing(){return!!this._data}installEvents(){C.on(I.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.on(I.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.on(I.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}uninstallEvents(){C.off(I.REMOTE_TRACK_SUBSCRIBED,this.onSubscribed,this),C.off(I.REMOTE_TRACK_UNSUBSCRIBED,this.onUnSubscribed,this),C.off(I.REMOTE_PUBLISH_STATE_CHANGED,this.onRemotePublishedChanged,this)}reset(){this.uninstallEvents(),this._config=null}onSubscribed({track:t}){t.room!==this._room||t.kind!==f.VIDEO||(this._remoteVideoTrackMap.set(`${t.userId}_${t.streamType}`,!1),this.isMixing&&this.hasAvailablePlaceHolder()&&this._config&&this.startMixTranscode(this._config))}onUnSubscribed({track:t}){t.room!==this._room||t.kind!==f.VIDEO||this.handleRemoteTrackUnavailable(`${t.userId}_${t.streamType}`)}onRemotePublishedChanged({room:t,prevMuteState:e,muteState:r}){t===this._room&&(e.hasVideo&&!r.hasVideo&&this.handleRemoteTrackUnavailable(`${r.userId}_${"main"}`),e.hasAuxiliary&&!r.hasAuxiliary&&this.handleRemoteTrackUnavailable(`${r.userId}_${"auxiliary"}`))}handleRemoteTrackUnavailable(t){if(this._remoteVideoTrackMap.has(t)){let e=this._remoteVideoTrackMap.get(t);this._remoteVideoTrackMap.delete(t),this.isMixing&&this.isPresetLayoutMode&&e&&this._config&&this.startMixTranscode(this._config)}}startMixTranscode(t){return T(this,null,function*(){try{this.resetIsUsedFlag(),this._config=t;let e=this.getInputParam(t),r=this.getOutputParam(t),n=this.getOutputSessionId({config:t,roomId:this._room.roomId,userId:this._room.userId});this.isMixing&&this._data&&n!==this._data.outputSessionId&&(this._log.info("startMixTranscode() streamId changed, stop mixing before start"),yield this.doStopMixTranscode()),yield this.doStartMixTranscode({outputSessionId:n,inputParam:e,outputParam:r})}catch(e){throw this.resetIsUsedFlag(),e}})}doStartMixTranscode(n){return T(this,arguments,function*({outputSessionId:t,inputParam:e,outputParam:r}){let s={roomId:String(this._room.roomId),mcuRequestTime:Date.now(),outputSessionId:t,inputParam:e,outputParam:r};this._log.info(`startMixTranscode: ${JSON.stringify(s)}`);let o=yield this._room.sendStartMixTranscode(s),{code:a}=o.data,{message:c}=o.data;if(a!==0)throw a===-102083&&(c=`Please enable relayed-push in ${vn} and try later, refer to ${Li}tutorial-26-advanced-publish-cdn-stream.html`),this._log.error(`startMixTranscode failed, errCode: ${a} errMsg: ${c}`),new V({code:M.START_MIX_TRANSCODE_FAILED,message:H({key:$.START_MIX_TRANSCODE_FAILED,data:{message:c},link:{className:"Client",fnName:"startMixTranscode"}})});this._data=s})}reStartMixTranscode(){!this.isMixing||this._config&&this.startMixTranscode(this._config)}stopMixTranscode(){return T(this,null,function*(){if(!this.isMixing)throw new V({code:M.INVALID_OPERATION,message:H({key:$.MIX_TRANSCODE_NOT_STARTED})});yield this.doStopMixTranscode(),this.resetIsUsedFlag()})}doStopMixTranscode(){return T(this,null,function*(){let t={mcuRequestTime:Date.now(),outputSessionId:this._data.outputSessionId,streamType:this._data.outputParam.streamType};this._log.info(`stopMixTranscode: ${JSON.stringify(t)}`);let e=yield this._room.sendStopMixTranscode(t),{code:r,message:n}=e.data;if(r===0)this._data=void 0;else throw this._log.error(`stopMixTranscode failed, errCode: ${r} errMsg: ${n}`),new V({code:M.STOP_MIX_TRANSCODE_FAILED,message:H({key:$.STOP_MIX_TRANSCODE_FAILED,data:{message:n},link:{className:"Client",fnName:"stopMixTranscode"}})})})}getOutputSessionId({config:t,userId:e,roomId:r}){return re(t.streamId)&&t.streamId.length>0?t.streamId:(0,Ml.default)(`${r}_${e}_main`)}getInputParam(t){let e=t.mixUsers.map(r=>({userId:r.userId,roomId:String(r.roomId||this._room.roomId),width:r.width||0,height:r.height||0,locationX:r.locationX||0,locationY:r.locationY||0,zOrder:r.zOrder,streamType:!N(r.streamType)&&r.streamType===Dn?1:0,inputType:r.pureAudio?li.STREAM_TYPE.IT_PURE_AUDIO:li.STREAM_TYPE.IT_AUDIO_VIDEO,renderMode:r.renderMode||0}));return t.mode===li.MODE.PRESET_LAYOUT&&(e.forEach(r=>{if(r.userId===li.PLACE_HOLDER.REMOTE){let n=[...this._remoteVideoTrackMap.entries()].find(([,s])=>!s);if(n){let[s]=n,o=s.split("_");r.userId=o.slice(0,o.length-1).join("_"),r.streamType=o.splice(-1)[0]==="auxiliary"?1:0,this._remoteVideoTrackMap.set(s,!0)}}}),e=e.filter(r=>r.userId!==li.PLACE_HOLDER.REMOTE)),e}getOutputParam(t){let e=t.streamId||"";return{streamId:e,streamType:e.length>0?1:0,width:N(t.videoWidth)?640:t.videoWidth,height:N(t.videoHeight)?480:t.videoHeight,videoBps:t.videoBitrate||0,fps:t.videoFramerate||15,gop:t.videoGOP||2,audioSampleRate:t.audioSampleRate||48e3,audioBps:t.audioBitrate||64,audioChannels:t.audioChannels||1,backgroundColor:t.backgroundColor||0,backgroundImg:t.backgroundImage||"",extraInfo:"",videoCodec:2,audioCodec:0}}hasAvailablePlaceHolder(){var t,e;return!(!this.isPresetLayoutMode||((t=this._data)==null?void 0:t.inputParam.length)===((e=this._config)==null?void 0:e.mixUsers.length))}resetIsUsedFlag(){this._remoteVideoTrackMap.forEach((t,e)=>{this._remoteVideoTrackMap.set(e,!1)})}},Ll=Rc;var UP=h(_(),1),Us=h(gc(),1);var un=class{constructor(t){p(this,"_room");p(this,"_publishTencentMainStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishTencentAuxStreamObj",{params:null,streamId:void 0,isPublishing:!1});p(this,"_publishGivenCDNData",null);p(this,"_isPublishingGivenCDN",!1);this._room=t}get _isPublishingTencentCDN(){return this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing}generatePublishCDNStreamId(t,e){if(!t){let r=`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(e)}`;return/^[A-Za-z\d_-]*$/.test(r)||(r=(0,Us.default)(r)),`${this._room.sdkAppId}_${r}`}return t}convertStreamType(t){return t==="main"?t:"aux"}generatePublishCDNSessionId(t){return(0,Us.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)}startPublishCDN(t){return T(this,null,function*(){let{streamId:e="",streamType:r="main",appId:n,bizId:s,url:o}=t;yield this.startPublishTencentCDN({streamId:e,streamType:r}),n&&s&&o&&(yield this.startPublishGivenCDN({streamType:r,appId:n,bizId:s,url:o}))})}stopPublishCDN(){return T(this,null,function*(){if(!this._isPublishingTencentCDN)throw new V({code:M.INVALID_OPERATION,message:H({key:$.INVALID_OPERATION_STOP_PUBLISH_CDN})});yield this.stopPublishTencentCDN(),this._isPublishingGivenCDN&&(yield this.stopPublishGivenCDN())})}startPublishTencentCDN(t){return T(this,null,function*(){if(t.streamType==="auxiliary"?(this._publishTencentAuxStreamObj.params=t,this._publishTencentAuxStreamObj.isPublishing=!0):(this._publishTencentMainStreamObj.params=t,this._publishTencentMainStreamObj.isPublishing=!0),!this._room.isJoined)return;let e=this.generatePublishCDNStreamId(t.streamId,t.streamType),r=this.generatePublishCDNSessionId(t.streamType),n=t.streamType==="auxiliary"?1:0,s={requestTime:Date.now(),sessionId:r,streamId:e,streamType:n};yield this.doStartPublishTencentCDN(s,t.streamType)})}doStartPublishTencentCDN(t,e){return T(this,null,function*(){try{P.info(`startPublishTencentCDN: ${JSON.stringify(t)}`);let r=yield this._room.sendStartPublishCDN(t,!0),{code:n}=r.data,{message:s}=r.data;if(n===0)e==="auxiliary"?this._publishTencentAuxStreamObj.streamId=t.streamId:this._publishTencentMainStreamObj.streamId=t.streamId;else throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,n===-102083&&(s=`Please enable relayed-push in ${vn} and try later, refer to ${Li}tutorial-26-advanced-publish-cdn-stream.html`),P.error(`startPublishTencentCDN failed, errCode: ${n}, errMsg: ${s}`),new V({code:M.START_PUBLISH_CDN_FAILED,message:H({key:$.START_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(r){throw e==="auxiliary"?this._publishTencentAuxStreamObj.isPublishing=!1:this._publishTencentMainStreamObj.isPublishing=!1,r}})}resetPublishTencentParam(t){t==="main"&&(this._publishTencentMainStreamObj={params:null,streamId:void 0,isPublishing:!1}),t==="auxiliary"&&(this._publishTencentAuxStreamObj={params:null,streamId:void 0,isPublishing:!1})}stopPublishTencentCDN(){return T(this,null,function*(){if(!this._room.isJoined){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary");return}this._publishTencentMainStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("main")),this._publishTencentAuxStreamObj.isPublishing&&(yield this.doStopPublishTencentCDN("auxiliary"))})}doStopPublishTencentCDN(t){return T(this,null,function*(){let e={requestTime:Date.now(),sessionId:(0,Us.default)(`${this._room.roomId}_${this._room.userId}_${this.convertStreamType(t)}`)};P.info(`stopPublishTencentCDN: ${JSON.stringify(e)}`);let r=yield this._room.sendStopPublishCDN(e,!0),{code:n,message:s}=r.data;if(n===0)this.resetPublishTencentParam(t);else if(n===-102069)P.warn("stopPublishTencentCDN failed, can not stopPublishTencentCDN in auto relayed-push mode"),this.resetPublishTencentParam(t);else throw P.error(`stopPublishTencentCDN failed, errCode: ${n} errMsg: ${s}`),new V({code:M.STOP_PUBLISH_CDN_FAILED,message:H({key:$.STOP_PUBLISH_CDN_FAILED,data:{message:s},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}startPublishGivenCDN(t){return T(this,null,function*(){let e=t.streamType==="main"?this._publishTencentMainStreamObj.streamId:this._publishTencentAuxStreamObj.streamId,r={pushRequestTime:Date.now(),pushAppId:t.appId,pushBizId:t.bizId,pushCdnUrl:t.url,pushStreamType:this.convertStreamType(t.streamType),pushStreamId:e};if(P.info(`startPublishGivenCDN: ${JSON.stringify(r)}`),this._publishGivenCDNData=r,this._isPublishingGivenCDN=!0,!!this._room.isJoined)try{let n=yield this._room.sendStartPublishCDN(r,!1),{code:s,message:o}=n.data;if(s!==0)throw P.error(`startPublishGivenCDN failed, errCode: ${s}, errMsg: ${o}`),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,new V({code:M.START_PUBLISH_CDN_FAILED,message:H({key:$.START_PUBLISH_CDN_FAILED,data:{message:o},link:{className:"Client",fnName:"startPublishCDNStream"}})})}catch(n){throw this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1,n}})}stopPublishGivenCDN(){return T(this,null,function*(){if(!this._room.isJoined||!this._publishGivenCDNData){this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;return}let{pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n}=this._publishGivenCDNData,s={pushRequestTime:Date.now(),pushAppId:t,pushBizId:e,pushCdnUrl:r,pushStreamType:n};P.info(`stopPublishGivenCDN: ${JSON.stringify(s)}`);let o=yield this._room.sendStopPublishCDN(s,!1),{code:a,message:c}=o.data;if(a===0)this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1;else throw P.error(`stopPublishGivenCDN failed, errCode: ${a} errMsg: ${c}`),new V({code:M.STOP_PUBLISH_CDN_FAILED,message:H({key:$.STOP_PUBLISH_CDN_FAILED,data:{message:c},link:{className:"Client",fnName:"stopPublishCDNStream"}})})})}handleCDNConfigForJoinData(t){let e=t,r;if(this._publishTencentMainStreamObj.isPublishing||this._publishTencentAuxStreamObj.isPublishing){let n={};re(e)&&(n=JSON.parse(e)),n.Str_uc_params||(n.Str_uc_params={}),this._publishTencentMainStreamObj.isPublishing&&(this._publishTencentMainStreamObj.streamId?n.Str_uc_params.userdefine_streamid_main=this._publishTencentMainStreamObj.streamId:this._publishTencentMainStreamObj.params&&(n.Str_uc_params.userdefine_streamid_main=this.generatePublishCDNStreamId(this._publishTencentMainStreamObj.params.streamId,"main"))),this._publishTencentAuxStreamObj.isPublishing&&(this._publishTencentAuxStreamObj.streamId?n.Str_uc_params.userdefine_streamid_aux=this._publishTencentAuxStreamObj.streamId:this._publishTencentAuxStreamObj.params&&(n.Str_uc_params.userdefine_streamid_aux=this.generatePublishCDNStreamId(this._publishTencentAuxStreamObj.params.streamId,"auxiliary"))),e=JSON.stringify(n)}if(this._isPublishingGivenCDN&&this._publishGivenCDNData){let{pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}=this._publishGivenCDNData;r={pushRequestTime:Date.now(),pushAppId:n,pushBizId:s,pushCdnUrl:o,pushStreamType:a,pushStreamId:c}}return{bussinessInfo:e,pushUserCdnInfo:r}}reset(){this.resetPublishTencentParam("main"),this.resetPublishTencentParam("auxiliary"),this._publishGivenCDNData=null,this._isPublishingGivenCDN=!1}};var XP=h(_(),1);function Ul(a){return T(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:n,version:s,frameWorkType:o}){let c={delta:0,count:[1,1],msg:[]};try{let d=new FormData;d.append("userId",String(i)),d.append("sdkAppId",String(t)),d.append("isStrGroupId",String(e)),d.append("groupId",String(r)),d.append("sdkVersion",s),d.append("userSig",String(n)),d.append("frameWorkType",String(o));let u=ee(),l=yield I_(d,c,t);return c.delta=ee()-u,l}catch(d){let u=Xt(d)?d[0]:d,l=ce(u.code)?u.code:0,m=`get websocket url failed: ${u.message.includes("timeout")?"timeout":u.message}`,S=new V({code:M.SCHEDULE_FAILED,extraCode:l,message:H({key:$.JOIN_ROOM_FAILED,data:{error:m,code:l}})});throw P.error(S),S}})}function kl(i,t=f.MAIN){let e;return jn(i)?e=t===f.MAIN?fr.MAIN_OVERSEA:fr.BACKUP_OVERSEA:e=t===f.MAIN?fr.MAIN:fr.BACKUP,`https://${e}/api/v1/config`}function S_(i,t,e){return new Promise((r,n)=>{zt({url:i,body:t,timeout:e.timeout}).then(s=>{s.data.code===0?r(s.data.data):n({code:s.data.code,message:s.data.msg})}).catch(n)})}var xl=(i,t)=>Tt({retryFunction:S_,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function I_(i,t,e){return new Promise((r,n)=>{let s=null;Vo([xl(o=>t.count[0]=o+1,(o,a)=>{t.msg[0]=o.message,s||a()})(kl(e,f.MAIN),i,{get timeout(){return wi(2+t.count[0])*1e3}}),xl(o=>t.count[1]=o+1,(o,a)=>{t.msg[1]=o.message,s||a()})(kl(e,f.BACKUP),i,{get timeout(){return wi(2+t.count[1])*1e3}})]).then(o=>{s=o,r(s)}).catch(n)})}var g_=0;var Vs=class extends ue{constructor(e){super("room");this.seq=g_++;this.role="anchor";this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null};this._log=P.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this._isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,bt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),bt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),bt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this.keyPointManager=new Dl({room:this,frameWorkType:e.frameWorkType,component:e.component}),this.callDurationCalculator=new Ol({room:this}),this.badCaseDetector=new bl({room:this}),this.mixTranscodeManager=new Ll(this),this.publishCDNManager=new un(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}getLogger(){return this._log}get isJoined(){return this.state==="joined"}addTrack(e){return T(this,null,function*(){return this.publish(e)})}removeTrack(e){return T(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return T(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}getRemoteAudioStats(){return T(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return T(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let n of this.quality.downlinkInfo)e.downlinksRTT[n.userId]=n.rtt;return e})}getRemoteVideoStats(){return T(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(n=>{let s=e==="auxiliary"?n.remoteAuxiliaryTrack:n.remoteVideoTrack;r[n.userId]=s.stat}),r})}checkDestroy(){if(this._isDestroyed)throw new V({code:M.INVALID_OPERATION,message:H({key:$.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Be.INVALID_DESTROY),new V({code:M.INVALID_OPERATION,message:H({key:$.INVALID_DESTROY})});this._log.info("destroy room"),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this._isDestroyed=!0,C.emit(I.ROOM_DESTROY,{room:this})}startMixTranscode(e){return this.mixTranscodeManager.startMixTranscode(e)}stopMixTranscode(){return this.mixTranscodeManager.stopMixTranscode()}startPublishCDNStream(){return T(this,arguments,function*(e={}){if(this._log.info(`startPublishCDNStream with params: ${JSON.stringify(e)}; isJoined: ${this.isJoined}; hasMainStream: ${this.isMainStreamPublished}; hasAuxStream: ${!!this.isAuxStreamPublished};`),this.isJoined){if(e.streamType==="main"&&!this.isMainStreamPublished)throw new V({code:M.INVALID_OPERATION,message:H({key:$.INVALID_OPERATION_START_PUBLISH_CDN})});if(e.streamType==="auxiliary"&&!this.isAuxStreamPublished)throw new V({code:M.INVALID_OPERATION,message:H({key:$.INVALID_OPERATION_START_PUBLISH_CDN})})}yield this.publishCDNManager.startPublishCDN(e)})}stopPublishCDNStream(){return this.publishCDNManager.stopPublishCDN()}schedule(e,r,n){return T(this,null,function*(){var o;let s=ee();try{let a=yield Ul({userId:this.userId,sdkAppId:this.sdkAppId,roomId:e,useStringRoomId:this.useStringRoomId,version:n,userSig:this.userSig,frameWorkType:r});this._log.info(`schedule: ${JSON.stringify(a)}`),this.scheduleResult=w(w({},this.scheduleResult),a),ce((o=a.config)==null?void 0:o.retryCount)&&Sd(a.config.retryCount),C.emit(I.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult}),C.emit(I.API_SUCCESS_RATE,{room:this,apiName:"schedule",cost:ee()-s})}catch(a){throw C.emit(I.API_SUCCESS_RATE,{room:this,apiName:"schedule",error:a}),a}})}};var VM=h(_(),1);var ln=new WeakMap,ni=new WeakMap;function Vl(){return function(i,t,e){let r=e.value,n=({fn:s,args:o,context:a,resolve:c,reject:d})=>{s.apply(a,o).then(c,d).finally(()=>{let u=ln.get(a);u&&(u.shift(),u[0]&&n(w({},u[0])))})};return e.value=function(...s){return new Promise((o,a)=>{if(ln.has(this)){let c=ln.get(this),{length:d}=c;c.push({fn:r,args:s,context:this,resolve:o,reject:a}),d===0&&n({fn:r,args:s,context:this,resolve:o,reject:a})}else ln.set(this,[{fn:r,args:s,context:this,resolve:o,reject:a}]),n({fn:r,args:s,context:this,resolve:o,reject:a})})},e}}function wl(){return function(i,t,e){let r=e.value;return e.value=function(...n){return ln.delete(this),r.apply(this,n)},e}}function Bl(i){return function(t,e,r){let n=r.value,s=a=>ce(i)?a[i]:i(...a),o=({fn:a,args:c,context:d,resolve:u,reject:l})=>{a.apply(d,c).then(u,l).finally(()=>{if(ni.has(d)&&ni.get(d).has(s(c))){let m=ni.get(d).get(s(c));m.shift(),m[0]&&o(w({},m[0]))}})};return r.value=function(...a){return new Promise((c,d)=>{if(ni.has(this))if(ni.get(this).has(s(a))){let u=ni.get(this).get(s(a)),{length:l}=u;u.push({fn:n,args:a,context:this,resolve:c,reject:d}),l===0&&o({fn:n,args:a,context:this,resolve:c,reject:d})}else ni.get(this).set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),o({fn:n,args:a,context:this,resolve:c,reject:d});else{let u=new Map;u.set(s(a),[{fn:n,args:a,context:this,resolve:c,reject:d}]),ni.set(this,u),o({fn:n,args:a,context:this,resolve:c,reject:d})}})},r}}var $M=h(_(),1),Hl=h(rt(),1);var $l=Symbol("instance"),pn=Symbol("abortCtrl"),Di=Symbol("cacheResult"),Ac=class{constructor(t,e,r){p(this,"oldState");p(this,"newState");p(this,"action");p(this,"error");this.oldState=t,this.newState=e,this.action=r}toString(){return`${this.action}ing`}},mn=class extends Error{constructor(e,r,n){super(r);p(this,"state");p(this,"message");p(this,"cause");this.state=e,this.message=r,this.cause=n}},hn=new Map,R_=Object.getPrototypeOf((()=>T(void 0,null,function*(){}))()).constructor;function Cc(i,t,e={}){return(r,n,s)=>{let o=e.action||n;if(!e.context){let c=hn.get(r)||[];hn.has(r)||hn.set(r,c),c.push({from:i,to:t,action:o})}let a=s.value;s.value=function(...c){return T(this,null,function*(){var S;let d=this;if(e.context&&(d=Je.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===t)return d[Di];let u=null;if(Array.isArray(i)?i.length==0?d[pn]&&(d[pn].aborted=!0):(typeof d.state!="string"||!i.includes(d.state))&&(u=new mn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not in from config`)):i!==d.state&&(u=new mn(d._state,`${d.name} ${o} to ${t} failed: current state ${d._state} not from ${i}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let l=d.state;ws.call(d,new Ac(l,t,o));let m={aborted:!1};d[pn]=m;try{let E=a.apply(this,c);return E instanceof R_?d[Di]=yield E:d[Di]=E,m.aborted||(d[pn]=void 0,ws.call(d,t),(S=e.success)==null||S.call(this,d[Di])),d[Di]}catch(E){let y=E instanceof Error?E.message:String(E);if(ws.call(d,l,y),e.fail)e.fail.call(this,new mn(d._state,`action '${o}' failed :${y}`,E instanceof Error?E:new Error(y)));else{if(e.ignoreError)return E;throw E}}})}}}var A_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{})();function ws(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(Je.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t})}var C_,v_,je=class extends Hl.default{constructor(e,r,n){super();p(this,"name");p(this,"groupName");p(this,"_state",je.INIT);p(this,C_);p(this,v_);this.name=e,this.groupName=r,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);let s=n[$l];s?this.name=s.name+"-"+s.count++:n[$l]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),r=hn.get(e)||[],n=new Set,s=[],o=[],a=new Set,c=Object.getPrototypeOf(e);hn.has(c)&&(c.stateDiagram.forEach(u=>n.add(u)),c.allStates.forEach(u=>a.add(u))),r.forEach(({from:u,to:l,action:m})=>{typeof u=="string"?s.push({from:u,to:l,action:m}):u.length?u.forEach(S=>{s.push({from:S,to:l,action:m})}):o.push({to:l,action:m})}),s.forEach(({from:u,to:l,action:m})=>{a.add(u),a.add(l),a.add(m+"ing"),n.add(`${u} --> ${m}ing : ${m}`),n.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),n.add(`${m}ing --> ${u} : ${m} \u{1F534}`)}),o.forEach(({to:u,action:l})=>{n.add(`${l}ing --> ${u} : ${l} \u{1F7E2}`),a.forEach(m=>{m!==u&&n.add(`${m} --> ${l}ing : ${l}`)})});let d=[...n];return Object.defineProperty(this,"stateDiagram",{value:d}),d}static get(e){let r;return typeof e=="string"?(r=je.instances.get(e),r||je.instances.set(e,r=new je(e,void 0,Object.create(je.prototype)))):(r=je.instances2.get(e),r||je.instances2.set(e,r=new je(e.constructor.name,void 0,Object.create(je.prototype)))),r}static getState(e){var r;return(r=je.get(e))==null?void 0:r.state}updateDevTools(e={}){A_(je.UPDATEAFSM,w({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){ws.call(this,e)}},Je=je;C_=Di,v_=pn,p(Je,"STATECHANGED","stateChanged"),p(Je,"UPDATEAFSM","updateAFSM"),p(Je,"INIT","[*]"),p(Je,"ON","on"),p(Je,"OFF","off"),p(Je,"instances",new Map),p(Je,"instances2",new WeakMap);var{isString:Bs,isPlainObject:y_,isUndefined:si,getNetworkType:N_,getTerminalType:D_,isEmpty:_n}=Fe,dt=class extends Vs{constructor(e){super(e);this.privateMapKey="";this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isPublishing=!1;this._isRelayChanged=!1;this.uplinkConnection=null;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._networkType=N_();this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=null;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.audioManager=null;this._stats=new on(this,this._log),this.userManager=new As(this.userId,this._log),this._version=Ve,this.sdpSemantics=_r,si(e.sdpSemantics)?Mt.isUnifiedPlanDefault()&&(this.sdpSemantics=ui):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${this._networkType}`),this.audioManager=new ls({log:this._log}),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=si(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI,this._initBusinessInfo(e)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.remotePublishedUserMap.values()].map(e=>[e.tinyId,e.userId]))}join(e,r,n){return T(this,null,function*(){this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var o=Lc(a,[]);!this.isJoined||(C.emit(I.REMOTE_PUBLISH_STATE_CHANGED,w({room:this},o)),this.emit("remote-publish-state-changed",w({},o)))});let s=String(e.roomId||e.strRoomId);return this._joinOptions=e,new Promise((o,a)=>T(this,null,function*(){this._joinReject=a;try{this.checkDestroy(),yield this.initialize(),yield this.doJoin(e),o()}catch(c){this.reset(),a(c)}this._joinReject=null}))})}afterJoin(e){return T(this,null,function*(){yield e,this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})})}doJoin(e){return new Promise((r,n)=>{var d;si(e.role)||(this.role=e.role===20?"anchor":"audience"),si(e.privateMapKey)||(this.privateMapKey=e.privateMapKey);let s={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,trtcRole:this.role==="anchor"?20:21,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:D_(),netType:ci[this._networkType],bussinessInfo:this._businessInfo},{bussinessInfo:o,pushUserCdnInfo:a}=this.publishCDNManager.handleCDNConfigForJoinData(this._businessInfo);Object.assign(s,{bussinessInfo:o,pushUserCdnInfo:a}),this._log.debug(`join room signal data: ${JSON.stringify(s)}`);let c=5e3;((d=this.scheduleResult.config)==null?void 0:d.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(c=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{this._log.error("join room timeout observed"),n(new V({code:M.JOIN_ROOM_FAILED,message:H({key:$.JOIN_ROOM_TIMEOUT})}))},c),C.emit(I.JOIN_SEND_CMD,{room:this}),this._signalChannel.once(ve.SETUP_FAILED,u=>{this.clearJoinTimeout(),C.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),n(u)}),this._signalChannel.send(pe.JOIN_ROOM,s),this._signalChannel.once(se.JOIN_ROOM_RESULT,u=>{this.clearJoinTimeout();let{code:l,message:m,data:S}=u.data;C.emit(I.JOIN_RECEIVED_CMD_RES,{room:this,code:l}),l===0?(this._log.info("Join room success, start heartbeat"),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=S.publishers,r()):(this._log.error(`Join room failed result: ${l} error: ${m}`),n(new V({code:M.JOIN_ROOM_FAILED,extraCode:l,message:H({key:$.JOIN_ROOM_FAILED,data:{error:m,code:l}})})))})})}reJoin(){return T(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this._joinOptions.roomId}`),this._signalChannel.close(),yield this._signalChannel.connect(),yield this.doJoin(ie(w({},this._joinOptions),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey})),this._log.warn("reJoin success"),Ae.logSuccessEvent({userId:this.userId,eventType:di.REJOIN}),this.checkConnectionsToReconnect(),this.uplinkConnection&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection(),this.mixTranscodeManager.reStartMixTranscode()}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),Ae.logFailedEvent({userId:this.userId,eventType:di.REJOIN,error:e}),this.emit("error",new V({code:M.JOIN_ROOM_FAILED,message:H({key:$.REJOIN_ROOM_FAILED,data:{roomId:this._joinOptions.roomId}})}))}})}initialize(){this._log.info("setup signal channel");let{mainUrl:e,backupUrl:r}=this.getSignalChannelUrl();return this._signalChannel=new rn({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:r,room:this}),this._networkQuality||(this._networkQuality=new yi({signalChannel:this._signalChannel,room:this}),this._networkQuality.on(yi.EVENT_NETWORK_QUALITY,n=>{this.emit("network-quality",n)})),this._signalChannel.on(ve.CONNECTION_STATE_CHANGED,n=>{C.emit(I.SIGNAL_CONNECTION_STATE_CHANGED,w({room:this},n)),this.emit("signal-connection-state-changed",n)}),this._signalChannel.on(ve.RECONNECT_FAILED,n=>{this.reset(),this.emit("error",n)}),this._signalChannel.once(ve.SETUP_SUCCESS,n=>{this.tinyId=n.signalInfo.tinyId,C.emit(I.JOIN_SIGNAL_CONNECTION_END,{room:this})}),this._signalChannel.on(se.PEER_JOIN,n=>{let{srcTinyId:s,userId:o,role:a}=n.data.data;this.userManager.addUser({userId:o,tinyId:s,role:a})}),this._signalChannel.on(se.PEER_LEAVE,n=>{let{userId:s,reason:o=0}=n.data.data;this.userManager.deleteUser(s,o)}),this._signalChannel.on(se.UPDATE_REMOTE_MUTE_STAT,n=>{Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(n.data)}),this._signalChannel.on(se.CLIENT_BANNED,n=>{let s=n.data.data,{reason:o}=s;if(Ae.uploadEvent({log:`stat-banned:${o}`,userId:this.userId}),o==="user_time_out"){this._log.warn(`${o} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[o==="kick"?"error":"info"](`user was banned because of [${o}]`),this.reset(),this.emit("banned",{reason:o})}),C.emit(I.JOIN_SIGNAL_CONNECTION_START,{room:this}),this._signalChannel.connect()}leave(){return T(this,null,function*(){try{yield this.doHeartbeat()}catch(e){}C.emit(I.LEAVE_SEND_CMD,{room:this}),this._log.info("leave() => leaving room"),this._signalChannel.send(pe.LEAVE_ROOM),this.reset()})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId)})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=le.run(vt,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),le.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return T(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),r=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this._signalChannel)!=null&&a.isConnected))return;let n=this._signalChannel.isConnected?wu(this.userId):[],s=w({str_sdk_version:Pi,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:ci[this._networkType]},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},r);C.emit(I.HEARTBEAT_REPORT,{room:this,report:s}),this._signalChannel.send(pe.ON_QUALITY_REPORT,s);let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this._signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){let r=e.data.userList.map(({userId:n,srcTinyId:s,flag:o})=>{let a=this.remotePublishedUserMap.get(n);return a&&this._changeBigSmallRecords.has(n)&&this.checkSubscribeBigSmallVideo(a),{userId:n,tinyId:s,flag:o}});C.emit(I.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:r}),this.userManager.setRemotePublishedUserList(r)}closeUplink(){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(),this.uplinkConnection=null),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:r,flag:n}){let s=new Il({userId:e,tinyId:r,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,flag:n});this.userManager.addRemotePublishedUser(s),this.installDownlinkEvents(s,e),this.emit("remote-published",s)}closeDownLinkConnection(e){let r=this.remotePublishedUserMap.get(e);r&&(r.getIsReconnecting()&&r.stopReconnection(),r.close(),this.emit("remote-unpublished",r))}installDownlinkEvents(e,r){e.on("error",n=>{let s=n.getCode();s!==M.ICE_TRANSPORT_ERROR&&(s===M.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(r),this.emit("error",n))}),e.on("connection-state-changed",n=>{this.emit("media-connection-state-changed",ie(w({},n),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=le.run(vt,this.syncUserList.bind(this)))}stopSyncUserListInterval(){le.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this._signalChannel)!=null&&e.isConnected?this._signalChannel.sendWaitForResponse({command:pe.GET_USER_LIST,responseCommand:se.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:r})=>{let{code:n,message:s}=r;if(n===0)return(r.data&&r.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw H({key:$.SIGNAL_RESPONSE_FAILED,data:{signalResponse:se.USER_LIST_RES,code:n,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(!this._signalChannel.isOnline||!ac)return!1;let e=this.getAllConnections();if(e.length===0)return!1;for(let r=0;r<e.length;r++)if(e[r].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){this.getAllConnections().forEach(r=>{if(!r.getIsReconnecting()){let n=r.getPeerConnection();n&&n.connectionState===De.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}destroy(){this._isDestroyed||(super.destroy(),this._joinReject&&(this._joinReject(new V({code:M.INVALID_OPERATION,message:H({key:$.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners())}switchRole(e){return T(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink(),yield this.doSwitchRole(e))})}doSwitchRole(e){let r={command:pe.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey},responseCommand:se.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(r.data)}`),this._signalChannel.sendWaitForResponseWithRetry(r).then(n=>{let{code:s,message:o}=n.data;if(s!==0)throw new V({code:M.SWITCH_ROLE_FAILED,message:H({key:$.SWITCH_ROLE_FAILED,data:{message:o,code:s}})});this.role=e}).catch(n=>{throw n instanceof V&&n.getCode()===M.API_CALL_TIMEOUT&&(n=new V({code:M.SWITCH_ROLE_FAILED,message:H({key:$.SWITCH_ROLE_TIMEOUT})})),this._log.error(n),n})}publish(...e){return T(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor")return;C.emit(I.PUBLISH_START,{room:this});let r={},n={};this._isPublishing=!0,e.forEach(s=>{!s.mediaTrack||(s instanceof xt&&(s instanceof Ii?(n.audio=s,this.audioManager.addScreenAudioTrack(s)):(r.audio=s,this.audioManager.addAudioTrack(s))),s instanceof st&&(s instanceof gt&&s.mediaType===2?n.video=s:r.video=s),s.setPublishStarting())});try{let s=_n(r),o=_n(n);(!s||!o)&&!this.uplinkConnection&&(this.uplinkConnection=new vl({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this._signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",a=>{this.emit("media-connection-state-changed",ie(w({},a),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",a=>{let c=a.getCode();c!==M.ICE_TRANSPORT_ERROR&&(c===M.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",a))})),s||(this._log.info("publish() => main stream"),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.video,isAuxiliary:!1}),this._log.info("main stream is published")),o||(this._log.info("publish() => aux stream"),yield this.uplinkConnection.publish({localAudioTrack:n.audio,localVideoTrack:n.video,isAuxiliary:!0}),this._log.info("aux stream is published")),this._isPublishing=!1,e.forEach(a=>{!a.mediaTrack||(this.localTracks.add(a),a.publish(this))})}catch(s){throw e.forEach(o=>{let a="error";s.message.includes("timeout")?a="timeout":s.code===M.API_CALL_ABORTED&&(a="api-call"),o.setPublishStopped(a,a==="error"?s:void 0)}),this._isPublishing=!1,s}})}unpublish(...e){return T(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let r={},n={};e.forEach(s=>{!s.mediaTrack||(s instanceof xt&&(s instanceof Ii?n.audio=s:r.audio=s),s instanceof st&&(s instanceof gt&&s.mediaType===2?n.video=s:r.video=s))});try{_n(r)||(this._log.info("unpublish() => main stream"),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video})),_n(n)||(this._log.info("unpublish() => aux stream"),yield this.uplinkConnection.unpublish({localAudioTrack:n.audio,localVideoTrack:n.video}))}catch(s){}e.forEach(s=>{!s.mediaTrack||(s.unpublish(),this.localTracks.delete(s))}),this.localTracks.size===0&&this.closeUplink()})}addTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.setPublishStarting(),this.uplinkConnection.addTrack(e.mediaTrack,e).then(r=>(e.publish(this),r)))}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e.mediaTrack,e).then(r=>(e.unpublish(),r))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.replaceTrack(e.mediaTrack,e).then(r=>{C.emit(I.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return T(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}subscribe(...e){return T(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=w({},n.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(r);a&&a.options.smallVideo&&n.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),C.emit(I.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:n,subscribeState:o}),this._log.info(`subscribe() => ${s} [${Ps(o)}] prev: [${Ps(n.subscribeState)}]`),yield n.subscribe(o,s),n.remoteVideoTrack.setMediaType(o.smallVideo?8:4),e.forEach(c=>c.subscribe()),C.emit(I.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})}catch(o){let a=o instanceof V?o.getCode():M.UNKNOWN,c=o;throw o instanceof V?a===M.REMOTE_STREAM_NOT_EXIST&&(c=new V({code:M.API_CALL_ABORTED,message:H({key:$.API_CALL_ABORTED,data:{message:o.message,userId:r,streamType:s}})}),this._log.warn(c)):(c=new V({code:a,message:H({key:$.SUBSCRIBE_FAILED,data:{message:o.message,userId:r,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return T(this,null,function*(){let{userId:r}=e[0],n=this.remotePublishedUserMap.get(r);if(!n)return;let s=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${s}`),yield n.unsubscribe({remoteTracks:e,streamType:s}),e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),C.emit(I.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:n})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,r){if(e<=0){this._enableAudioVolumeEvaluation=!1,le.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null;return}e=Math.floor(Math.max(e,100)),C.emit(I.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&(le.clearTask(this._audioVolumeIntervalId),this._audioVolumeIntervalId=null),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=le.run(Kt,()=>{var s,o;let n=[];if((s=this.uplinkConnection)!=null&&s.localMainAudioTrack){let a=Math.floor(this.uplinkConnection.localMainAudioTrack.getAudioLevel()*100);n.push({userId:"",volume:a})}(o=this.remotePublishedUserMap)==null||o.forEach(a=>{if(a.muteState.hasAudio){let c=Math.floor(a.remoteAudioTrack.getAudioLevel()*100);n.push({userId:a.userId,volume:c})}}),this.emit("audio-volume",n)},{fps:1e3/e,backgroundTask:r})}getLocalAudioStats(){return T(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r.audio.bytesSent,packetsSent:r.audio.packetsSent}}return e})}getLocalVideoStats(){return T(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:r,packetsSent:n,framesEncoded:s,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return T(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let r=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=r.rtt}for(let[,r]of this.remotePublishedUserMap){let n=yield this._stats.getReceiverStats(r);e.downlinksRTT[n.userId]=n.rtt}return e})}getRemoteVideoStats(e){return T(this,null,function*(){let r={};for(let[n,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(r[n]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(r[n]=s.remoteAuxiliaryTrack.stat);return r})}getRemoteAudioStats(){return T(this,null,function*(){let e={};for(let[r,n]of this.remotePublishedUserMap)n.muteState.hasAudio&&(e[r]=n.remoteAudioTrack.stat);return e})}setProxyServer(e){if(Bs(e)){if(!e.startsWith("wss://"))throw new V({code:M.INVALID_PARAMETER,message:"invalid websocket url"});this.proxy_ws=e}else if(y_(e)){let{websocketProxy:r,loggerProxy:n}=e;r&&(this.proxy_ws=r),n&&dd(n)}}setTurnServer(e,r){this._log.info(`set turn server: ${JSON.stringify(e)} ${r||""}`);let n=[];Array.isArray(e)?e.forEach(s=>n.push(Fe.getTurnServer(s))):Fe.isPlainObject(e)&&n.push(Fe.getTurnServer(e)),this._turnServers=n,r&&(this._iceTransportPolicy=r)}sendStartMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:pe.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:se.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this._signalChannel.sendWaitForResponse({command:pe.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:se.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?pe.START_PUBLISH_TENCENT_CDN:pe.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?se.START_PUBLISH_TENCENT_CDN_RES:se.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,r=!0){return this._signalChannel.sendWaitForResponse({command:r?pe.STOP_PUBLISH_TENCENT_CDN:pe.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:r?se.STOP_PUBLISH_TENCENT_CDN_RES:se.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},r=Fe.getEnv();return r?(e.mainUrl=`wss://${r}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this._signalChannel)==null?void 0:e.getSignalInfo())||{}}reset(){this.mixTranscodeManager.reset(),this.publishCDNManager.reset(),this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink(),this._signalChannel&&(this._log.info("destroying SignalChannel"),this._signalChannel.close()),this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners()}checkSubscribeBigSmallVideo(e){return T(this,null,function*(){let r=e==null?void 0:e.muteState.hasSmall,n=e==null?void 0:e.muteState.hasVideo;if(!r&&!n||!e.isBigStreamSubscribed&&!e.isSmallStreamSubscribed)return;let s=e.getUserId(),o=this._changeBigSmallRecords.get(s)||{},a=e.getSubscribeState(),{options:c,isSubscribing:d,reSubscribeCount:u}=o;if(c.video&&a.video||c.smallVideo&&a.smallVideo&&r||d)return;let l={audio:a.audio,auxiliary:a.auxiliary,video:c.video,smallVideo:c.smallVideo};if(r&&e.isBigStreamSubscribed||e.isSmallStreamSubscribed)try{c&&!d&&u>=1&&(o.isSubscribing=!0,o.reSubscribeCount=u-1,!r&&e.isSmallStreamSubscribed&&(l.video=!0,l.smallVideo=!1),yield e==null?void 0:e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${Er-o.reSubscribeCount}.`),o.isSubscribing=!1,o.reSubscribeCount=Er)}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${Er-o.reSubscribeCount}.`),o.isSubscribing=!1,u===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,r){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Er};this._changeBigSmallRecords.set(r.userId,s),this._log.info(`set [${r.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let r={};if(Bs(e.businessInfo)&&(r=JSON.parse(e.businessInfo)),!si(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new V({code:M.INVALID_PARAMETER,message:H({key:$.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!si(e.streamId))if(Bs(e.streamId)&&String(e.streamId)&&String(e.streamId).length<=64)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_streamid_main=e.streamId;else throw new V({code:M.INVALID_PARAMETER,message:H({key:$.INVALID_STREAMID})});if(!si(e.userDefineRecordId)){let n=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(n)===null)throw new V({code:M.INVALID_PARAMETER,message:H({key:$.INVALID_USER_DEFINE_RECORDID})});r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!si(e.userDefinePushArgs))if(Bs(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)r.Str_uc_params||(r.Str_uc_params={}),r.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new V({code:M.INVALID_PARAMETER,message:H({key:$.INVALID_USER_DEFINE_PUSH_ARGS})});_n(r)||(this._businessInfo=JSON.stringify(r))}startPlugin(e,r){return T(this,null,function*(){var n;e==="RTCAudioMixer"&&(yield(n=this.audioManager)==null?void 0:n.addMusicSource(r))})}stopPlugin(e,r){return T(this,null,function*(){var n;e==="RTCAudioMixer"&&((n=this.audioManager)==null||n.removeMusicSource(r))})}};G([Yi(dt.prototype.afterJoin),Cc(["left",Je.INIT],"joined"),rl()],dt.prototype,"join",1),G([Cc("joined","left",{ignoreError:!0}),nl(),wl(),cn({fnName:"publish",validateArgs:!1}),cn({fnName:"unsubscribe",validateArgs:!1})],dt.prototype,"leave",1),G([Vl(),an({settings:{retries:hr,timeout:i=>ft(i)},onError(i,t,e){var r;(r=i.message)!=null&&r.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${i}`),e(i))}})],dt.prototype,"publish",1),G([cn({fnName:"publish",callback(...i){var t;(t=this.uplinkConnection)==null||t.close(),this.uplinkConnection=null,i.forEach(e=>e.setPublishStopped("api-call"))}})],dt.prototype,"unpublish",1),G([Bl((...i)=>i[0].userId),an({settings:{retries:hr,timeout:i=>ft(i)},onError(i,t,e){i.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${i}`),e(i))}})],dt.prototype,"subscribe",1),G([cn({fnName:"subscribe",callback(...i){i.forEach(t=>{var e;(e=this.remotePublishedUserMap.get(t.userId))==null||e.closePeerConnection()})}})],dt.prototype,"unsubscribe",1);Ns.create=()=>Ns._create(dt);var DL=Ns;export{DL as default};