dingrtc 3.7.4 → 3.8.2-beta.0
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/dist/index.d.ts +20 -5
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +4 -4
- package/package.json +4 -4
package/dist/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"webrtc-adapter";import{Environment as e,getReporter as t,SystemType as r,BrowserType as n,DingRTCError as i,ErrorCode as o,setGslb as a,isString as s,EventEmitter as c,parseAudioDeviceError as u,parseVideoDeviceError as d,addTimer as l,isObject as p,isNumber as f,removeTimer as v,Debouncer as h,tryJsonStringify as m,EventBus as y,createUuid as g,parseScreenShareError as b,getProtobufRoot as S,isPrivateIP as k,SdkType as P,uniqBy as w,VideoSourceInfo as O,TraceEvent as T,registerReporter as E,setLogLevel as I}from"@dingrtc/shared";export{ErrorCodeAndMsgMap}from"@dingrtc/shared";import R from"sdp-transform";import{DingRTCChannel as A}from"@dingrtc/channel";function _(e,t,r,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,i)}function M(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function a(e){_(o,n,i,a,s,"next",e)}function s(e){_(o,n,i,a,s,"throw",e)}a(void 0)}))}}function C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function D(e){return D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},D(e)}function x(e){var t=function(e,t){if("object"!=D(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=D(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==D(t)?t:t+""}function j(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,x(n.key),n)}}function L(e,t,r){return t&&j(e.prototype,t),r&&j(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function N(e,t){if(t&&("object"==D(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function F(e){return F=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},F(e)}function G(e,t){return G=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},G(e,t)}function U(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&G(e,t)}function V(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var B={exports:{}},q={exports:{}};!function(e){function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(q);var H=q.exports;!function(e){var t=H.default;function r(){e.exports=r=function(){return i},e.exports.__esModule=!0,e.exports.default=e.exports;var n,i={},o=Object.prototype,a=o.hasOwnProperty,s=Object.defineProperty||function(e,t,r){e[t]=r.value},c="function"==typeof Symbol?Symbol:{},u=c.iterator||"@@iterator",d=c.asyncIterator||"@@asyncIterator",l=c.toStringTag||"@@toStringTag";function p(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{p({},"")}catch(n){p=function(e,t,r){return e[t]=r}}function f(e,t,r,n){var i=t&&t.prototype instanceof S?t:S,o=Object.create(i.prototype),a=new D(n||[]);return s(o,"_invoke",{value:A(e,r,a)}),o}function v(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}i.wrap=f;var h="suspendedStart",m="suspendedYield",y="executing",g="completed",b={};function S(){}function k(){}function P(){}var w={};p(w,u,(function(){return this}));var O=Object.getPrototypeOf,T=O&&O(O(x([])));T&&T!==o&&a.call(T,u)&&(w=T);var E=P.prototype=S.prototype=Object.create(w);function I(e){["next","throw","return"].forEach((function(t){p(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,r){function n(i,o,s,c){var u=v(e[i],e,o);if("throw"!==u.type){var d=u.arg,l=d.value;return l&&"object"==t(l)&&a.call(l,"__await")?r.resolve(l.__await).then((function(e){n("next",e,s,c)}),(function(e){n("throw",e,s,c)})):r.resolve(l).then((function(e){d.value=e,s(d)}),(function(e){return n("throw",e,s,c)}))}c(u.arg)}var i;s(this,"_invoke",{value:function(e,t){function o(){return new r((function(r,i){n(e,t,r,i)}))}return i=i?i.then(o,o):o()}})}function A(e,t,r){var i=h;return function(o,a){if(i===y)throw Error("Generator is already running");if(i===g){if("throw"===o)throw a;return{value:n,done:!0}}for(r.method=o,r.arg=a;;){var s=r.delegate;if(s){var c=_(s,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===h)throw i=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=y;var u=v(e,t,r);if("normal"===u.type){if(i=r.done?g:m,u.arg===b)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=g,r.method="throw",r.arg=u.arg)}}}function _(e,t){var r=t.method,i=e.iterator[r];if(i===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=n,_(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var o=v(i,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,b;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=n),t.delegate=null,b):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,b)}function M(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(M,this),this.reset(!0)}function x(e){if(e||""===e){var r=e[u];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,o=function t(){for(;++i<e.length;)if(a.call(e,i))return t.value=e[i],t.done=!1,t;return t.value=n,t.done=!0,t};return o.next=o}}throw new TypeError(t(e)+" is not iterable")}return k.prototype=P,s(E,"constructor",{value:P,configurable:!0}),s(P,"constructor",{value:k,configurable:!0}),k.displayName=p(P,l,"GeneratorFunction"),i.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===k||"GeneratorFunction"===(t.displayName||t.name))},i.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,P):(e.__proto__=P,p(e,l,"GeneratorFunction")),e.prototype=Object.create(E),e},i.awrap=function(e){return{__await:e}},I(R.prototype),p(R.prototype,d,(function(){return this})),i.AsyncIterator=R,i.async=function(e,t,r,n,o){void 0===o&&(o=Promise);var a=new R(f(e,t,r,n),o);return i.isGeneratorFunction(t)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},I(E),p(E,l,"Generator"),p(E,u,(function(){return this})),p(E,"toString",(function(){return"[object Generator]"})),i.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},i.values=x,D.prototype={constructor:D,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(C),!e)for(var t in this)"t"===t.charAt(0)&&a.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=n)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,i){return s.type="throw",s.arg=e,t.next=r,i&&(t.method="next",t.arg=n),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var c=a.call(o,"catchLoc"),u=a.call(o,"finallyLoc");if(c&&u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&a.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),C(r),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;C(r)}return i}}throw Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:x(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=n),b}},i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(B);var Y=(0,B.exports)(),W=Y;try{regeneratorRuntime=Y}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=Y:Function("r","regeneratorRuntime = r")(Y)}var J,Q,K,z,$,X,Z,ee,te,re,ne,ie,oe,ae,se=V(W);function ce(e,t,r){return(t=x(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(J||(J={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(Q||(Q={})),function(e){e.MIC="mic",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(K||(K={})),function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(z||(z={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}($||($={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(X||(X={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(Z||(Z={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(ee||(ee={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(te||(te={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(re||(re={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(ne||(ne={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(ie||(ie={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(oe||(oe={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(ae||(ae={}));var ue,de={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};!function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(ue||(ue={}));var le="3.7.2",pe=-999,fe="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.browserType,e.browserVersion,e.system,e.systemVersion;var ve="onertc_state_sync",he="onertc_internal_track_event",me=t().log,ye=new(function(){return L((function t(){C(this,t),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.browser=e.browserType,this.browserVersion=e.browserVersion}),[{key:"getSupportedCodec",value:(t=M(se.mark((function e(){var t,r,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=7,r.createOffer();case 7:if(n=e.sent.sdp){e.next=10;break}return e.abrupt("return",t);case 10:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 24:throw e.prev=24,e.t0=e.catch(1),me.error("get supportedCodecs failed"),new i(o.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 28:case"end":return e.stop()}}),e,null,[[1,24]])}))),function(){return t.apply(this,arguments)})},{key:"checkSupported",value:function(){var t=!1;try{var r=window.RTCPeerConnection,n=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,i=window.WebSocket;t=!!(r&&n&&i)}catch(e){return!1}var o=!1;o=e.isChrome()||e.isFirefox()?parseInt(e.browserVersion,10)>=69:e.isOpera()?parseInt(e.browserVersion,10)>=45:e.isSafari()?parseInt(e.browserVersion,10)>=11:(e.isWeixin()||e.isQQBrowser(),!0);var a=t&&o;return me.debug("checkSystemRequirements, api:",t,"browser",o),a}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(r.ANDROID)&&this.system!==r.IOS&&(!(this.browser===n.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===n.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var t}()),ge=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},n=r.setParameters,i=r.getParameters;return!(!n||!i)&&(!e.isFirefox()&&(e.isSafari()?parseInt(e.browserVersion)>=14:e.isChrome()?parseInt(e.browserVersion)>=81:!e.isAndroid()))};function be(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Se(e,t){if(e){if("string"==typeof e)return be(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?be(e,t):void 0}}function ke(e){return function(e){if(Array.isArray(e))return be(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Se(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Pe(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Pe=function(){return!!e})()}var we=new(function(){function e(){var t,r,n,i;return C(this,e),r=this,n=F(n=e),t=N(r,Pe()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:ge()}),Object.defineProperty(t,"grouptalk",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(t,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(t,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),t}return U(e,c),L(e,[{key:"setClientConfig",value:function(e){var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU;"string"==typeof r&&(this.gslb=[r],a(r)),Array.isArray(r)&&s(r[0])&&(this.gslb=r,a(r[0])),null!=n&&ge()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i))}}])}()),Oe=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},Te=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,ke(i.parameters.resolution)),n.sort(Oe),n},Ee=function(e,t){var r,n=e.media,a=n.audio,s=n.video;if(t===ie.QuotaLimit)return r=new i(o.QuotaLimitExceed);if(a)r=new i(o.SubscribeAudioStreamFailed,t);else if(s){var c=s.source;c===z.CAMERA?r=new i(o.SubscribeVideoStreamFailed,t):c===z.SCREENCAST&&(r=new i(o.SubscribeScreenShareFailed,t))}return r},Ie=function(e,t){var r,n=e.trackMediaType;if(t===ie.QuotaLimit)return r=new i(o.QuotaLimitExceed);if("audio"===n)r=new i(o.PublishAudioStreamFailed,t);else{var a=e.source;a===z.CAMERA?r=new i(o.PublishVideoStreamFailed,t):a===z.SCREENCAST&&(r=new i(o.PublishScreenShareFailed,t))}return r},Re=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?we.audioSFU?n?n.replaceStream(e):i=new pr(null,r,e):n?n.replaceTrack(a[0]):i=new pr(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new fr(o[0],r)),i},Ae=function(e){return"object"===D(e.video)&&e.video.source===z.SCREENCAST};function _e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Me(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_e(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_e(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ce(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return De(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?De(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function De(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function xe(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(xe=function(){return!!e})()}var je=function(){function e(){var t,r,n,i,o;return C(this,e),r=this,n=F(n=e),t=N(r,xe()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(o=M(se.mark((function r(){var n;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!t.checking){r.next=2;break}return r.abrupt("return");case 2:return t.checking=!0,r.next=5,e.getDevices();case 5:n=r.sent,t.compareDevices(n,"audiooutput"),t.compareDevices(n,"videoinput"),t.compareDevices(n,"audioinput"),t.deviceList=n,t.checking=!1;case 11:case"end":return r.stop()}}),r)}))),function(){return o.apply(this,arguments)})}),Object.defineProperty(t,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(e,r){var n,i=e.filter((function(e){return e.kind===r})),o=t.deviceList.filter((function(e){return e.kind===r})),a=i.map((function(e){return e.deviceId})),s=o.map((function(e){return e.deviceId})),c=i.filter((function(e){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),d={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},l=Ce(c);try{for(l.s();!(n=l.n()).done;){var p=n.value;t.emit(d[r],{device:p,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var f,v=Ce(u);try{for(v.s();!(f=v.n()).done;){var h=f.value;t.emit(d[r],{device:h,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),e._instance?N(t,e._instance):(t.deviceList=[],ye.checkSupported()?(e.getDevices({audio:!0,video:!0},!0).then((function(e){t.deviceList=e,t.addEventListeners()})),t):N(t))}return U(e,c),L(e,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):l(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return e._instance}},{key:"getMedias",value:function(e,t){var r,n,i=this;return Ae(e)?null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t):null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t}))}},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(n,a){var s;if(null!==(s=navigator.mediaDevices)&&void 0!==s&&s.enumerateDevices){var c=!1;t.audio&&t.video?c=e.audioPermitted&&e.videoPermitted:t.audio?c=e.audioPermitted:t.video&&(c=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(i){var o=i.filter((function(e){return e.deviceId})),s=o.filter((function(e){return"videoinput"===e.kind})),u=o.filter((function(e){return"audioinput"===e.kind})),d=o.filter((function(e){return"audiooutput"===e.kind})),l=[];t.audio&&(l=l.concat(u,d)),t.video&&(l=l.concat(s)),0!==l.length||c||r?l.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(l)):n(l):navigator.mediaDevices.getUserMedia(t).then((function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){n(e)}),a)}),a)}))}else a(new i(o.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}();Object.defineProperty(je,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(je,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(je,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new je}),Object.defineProperty(je,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return je.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(e){throw u(e)}))}}),Object.defineProperty(je,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return je.getDevices({video:!0}).then((function(e){return e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return Me(Me({},r),{},{toJSON:function(){return r}})}))})).catch((function(e){throw d(e)}))}}),Object.defineProperty(je,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return je.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(e){throw u(e)}))}});var Le=function(e){return{width:de[e][0],height:de[e][1]}},Ne=function(t){var r,n=Object.create({}),i={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(i=navigator.mediaDevices.getSupportedConstraints());var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.isSafari()?n.deviceId=t.deviceId:n.deviceId={exact:t.deviceId}),i.autoGainControl&&(n.autoGainControl={ideal:null==a||a}),i.echoCancellation&&(n.echoCancellation={ideal:null==o||o}),i.noiseSuppression&&(n.noiseSuppression={ideal:null==s||s}),n},Fe=function(t){if(!p(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,n=t.video;if(!Ae(t)&&"object"===D(r)&&r.source===K.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(Ae(t)&&"object"===D(r)&&r.source!==K.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!r&&!n)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var i=Object.create({});if("object"===D(r)&&r.source===K.MIC||"object"===D(r)&&r.source===K.SCREENCAST?i.audio=Ne(r):i.audio=t.audio,"object"===D(n)){var o,a=n.frameRate,c=n.deviceId,u=n.source,d=n.facingMode,l=n.displaySurface,v=n.dimension;i.video=Object.create({}),f(a)&&(i.video.frameRate=Math.min(n.frameRate,30)),v&&(o=Le(v)),o&&o.width&&o.height&&(u===z.SCREENCAST||e.isFirefox()?(i.video.width=o.width,i.video.height=o.height):(i.video.width={ideal:o.width,max:o.width},i.video.height={ideal:o.height,max:o.height})),s(c)&&c&&(i.video.deviceId={exact:c}),u===z.SCREENCAST&&(e.isFirefox()&&(i.video.mediaSource="screen"),l&&["browser","window","monitor"].includes(l)&&(i.video.displaySurface=l)),d&&["user","environment"].includes(d)&&(i.video.facingMode=d)}else i.video=n;return je.getMedias(t,i)};function Ge(){return Ge="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=F(e)););return e}(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},Ge.apply(null,arguments)}var Ue,Ve,Be=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map((function(e){return function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t}(e)}));return t.trackInfos=r,t},qe=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},He=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},Ye=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},We=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Je=new Map,Qe=function(e){return new Promise((function(t){l(t,1e3*e)}))},Ke=t().log,ze="rtc-intersecting",$e="visible",Xe="invisible",Ze=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],et=function(e){return"".concat(null==e?void 0:e.getAttribute(fe),"-").concat(null==e?void 0:e.rtcPurpose)},tt=function(){return L((function e(t,r){var n=this;C(this,e),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new h}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(v(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(ke(n.mediaElementPool),ke(n.mediaElementsInUse)).forEach((function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject;if(t.error){var i="".concat(e,": ").concat(et(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=Be(r);Ke.debug(i,o),"visible"===document.visibilityState&&qe(r)&&t.load()}if(t.paused){var a=!1;if(n.hasActivated&&"video"===n.mediaKind?function(e){return e&&e.getAttribute(ze)===$e}(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(et(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(ze),", mediaStream="),c=Be(r);Ke.error(s,c),qe(r)&&t.load(),t.paused&&t.play().catch((function(e){console.error("inPoll",e)}))}}}})),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&!0!==(null==i?void 0:i.muted)){var o="".concat(e,": ").concat(et(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=Be(r);return Ke.error(o,a),void("visible"===document.visibilityState&&qe(r)&&t.load())}n.currentTimeOfLastCheckMap.set(t,t.currentTime)}}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=Be(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Ke.error(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=Be(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Ke.debug(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=Be(null==t?void 0:t.srcObject);Ke.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(ke(n.mediaElementPool),ke(n.mediaElementsInUse));if(!n.hasActivated&&(n.hasActivated=!0,e.forEach((function(e){e.load()})),n._activatedListener))try{n._activatedListener()}catch(e){Ke.error("error occurred when exec activatedListener",m(e))}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver((function(e){e.forEach((function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(ze,$e):null===(r=e.target)||void 0===r||r.setAttribute(ze,Xe)}))})));for(var i=0;i<r;i++){var o,a=this._createElement();null===(o=this.observer)||void 0===o||o.observe(a),this.addAtttribute(a),a.setAttribute(fe,"".concat(t,"-").concat(i)),this.mediaElementPool.push(a),this.allElements.add(a)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=l((function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")}),4e3,"interval")}),[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(fe,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?(this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||""):(t=document.createElement(this.mediaKind),this.addAtttribute(t)),t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter((function(t){return t!==e})),t.length!==this.mediaElementsInUse.length&&(this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(){var e,t=document.createElement(this.mediaKind);return null===(e=this.observer)||void 0===e||e.observe(t),t}},{key:"_resetMediaElement",value:function(e){Ze.forEach((function(t){e["on".concat(t)]=null})),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),rt=function(){return Ue||ot(),Ue},nt=function(){return Ve||ot(),Ve},it=e.isIOS()||e.isAndroid()?9:25,ot=function(){Ue||(Ue=new tt("audio",2)),Ve||(Ve=new tt("video",it))},at=new AudioContext,st=function(e){var t=e.getAudioTracks(),r=at.createMediaStreamDestination();return t.forEach((function(e){at.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},ct=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},ut=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},dt=rt(),lt=nt(),pt=t().log,ft=function(){return L((function e(){C(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(e,t,r){var n,a=this,s=e.getTrackId(),c=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var u,d=this.findDom(t);if(!d)throw new i(o.InvaildArgument,"wrapper dom not found");var l=r||{},p=l.mirror,f=l.fit;if((n=this.players.find((function(e){return e.container===t})))&&(null===(u=n.track)||void 0===u?void 0:u.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stop(n.track,t),void this.play(e,t,r);n?(n.element.pause(),!e.sourceMirror!=!p?n.element.style.transform="scaleX(-1)":n.element.style.transform="",f&&(n.element.style.objectFit=f),n.element.srcObject=c,n.element.load()):((n={container:t,track:e,playerConfig:r}).element=function(e,t,r){var n=nt().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n}(d,c,{mirror:!e.sourceMirror!=!p,fit:f}),this.players.push(n))}else(n=this.players.find((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})))?(n.element.pause(),n.element.srcObject=c,n.element.load()):((n={track:e}).element=function(e){var t=rt().popElement();return t.srcObject=e,t}(c),this.players.push(n));n.element.paused&&n.element.play().then((function(){n.isPlaying=!0})).catch((function(e){"NotAllowedError"===e.name?(pt.error("autoplay failed",m(e)),y.emit("autoplay-failed",a)):pt.warn("".concat(s," play has exception"),m(e))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?dt.pushElement(t.element):lt.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),vt=new ft,ht=function(){return vt};function mt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(mt=function(){return!!e})()}var yt,gt=t(),bt=gt.log,St=gt.trace,kt=ht(),Pt=function(){function e(t,r){var n,i,o,a;return C(this,e),i=this,o=F(o=e),n=N(i,mt()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:St}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t?(n.trackMediaType=t.kind,n.trackSettings=t.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.audioContext=at,n.analyser=n.audioContext.createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(g(6)),n.setMediaStreamTrack(t,r),n}return U(e,c),L(e,[{key:"isPlaying",get:function(){return kt.isPlaying(this)}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var a;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(a=this.audioContext)||void 0===a?void 0:a.createMediaStreamSource(new MediaStream([e]));else if(t){var s,c=st(t);this.sourceNode=null===(s=this.audioContext)||void 0===s?void 0:s.createMediaStreamSource(new MediaStream([c]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===z.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===K.MIC?new i(o.MicInterrupt):r.source===z.CAMERA&&new i(o.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){bt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(he,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===z.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===K.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){bt.info("stop paly track ".concat(this.getTrackId())),kt.stop(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.element,n=e.config;e.updated?kt.getPlayInfos(this).forEach((function(e){e.container?kt.findDom(e.container)?kt.play(t,e.container,e.playerConfig):kt.stop(t,e.container):kt.play(t,e.container,e.playerConfig)})):kt.play(this,r,n);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(e){bt.debug("resume audioContext failed: ".concat(m(e)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function wt(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||Se(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ot(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Tt(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Tt(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Tt(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Et(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function It(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Et(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Et(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD"}(yt||(yt={}));var Rt=ce(ce(ce(ce(ce({},yt.LLD,"ld"),yt.LD,"ld"),yt.SD,"sd"),yt.HD,"hd"),yt.FHD,"fhd"),At={high:[1228800,2764800],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},_t=function(e){return 2560===e.width&&1440===e.height},Mt=function(e,t){var r=Ct(e,t),n=("FHD"===e||"high"===e)&&_t(r),i=function(e,t){var r={high:ae.FHD,low:ae.LD,FHD:ae.FHD,HD:ae.HD,SD:ae.SD,LD:ae.LD},n=r[e]||ae.None,i=At[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(At).find((function(e){var t=wt(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[wt(a,1)[0]]}return n}(e,t);return{resolution:r,resolutionLevel:n?32:i}},Ct=function(e,t){var r=At[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&_t(i))return i;if(t[0].width*t[0].height>At.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},Dt=[49152,76800,307200,1228800,2764800],xt=[200,350,1e3,1800,2828],jt=[[256,144],[320,180],[640,360],[1280,720],[1920,1080]],Lt=[[256,192],[320,240],[640,480],[1280,960],[1920,1440]],Nt=function(e,t){var r=yt.FHD,n=e*t;return n<=Dt[yt.LLD]?r=yt.LLD:n<=Dt[yt.LD]?r=yt.LD:n<=Dt[yt.SD]?r=yt.SD:n<=Dt[yt.HD]?r=yt.HD:n<=Dt[yt.FHD]&&(r=yt.FHD),r},Ft=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!r){var n=1;30!==t&&(n=Math.sqrt(t/30));var i=e.getSettings(),o=i.width,a=i.height,s=xt[Nt(o,a)];2560===o&&1440===a&&(s=4860),r=Math.round(Math.max(n*s,50))}return r},Gt=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=Nt(i,o);if(!function(e){var t,r=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),n=(null==r?void 0:r.width)||e.trackSettings.width,i=(null==r?void 0:r.height)||e.trackSettings.height,o=Nt(n,i);return!(!we.simulcast||e.source===z.SCREENCAST||_t({width:n,height:i})||o<yt.SD)}(e))return[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,active:!0,rid:Rt[s],minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}];var c=[],u=s>=yt.HD?3:2,d=function(e){var t=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=jt[r][0],o=jt[r][1];else if(4*t==3*e)i=Lt[r][0],o=Lt[r][1];else{var s=Math.sqrt(1*jt[r][0]*jt[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]}(i,o,e,s),n=wt(t,2),c=n[0],u=n[1],d=xt[e]/xt[s];return{targetWidth:c,rid:Rt[e],targetHeight:u,minBitrate:50,maxFramerate:a,maxBitrate:Math.round(Math.max(30,r*d)),scaleResolutionDownBy:1/(u/o)}};s>yt.LD&&c.push(It({active:u>1},d(yt.LD))),s>yt.SD&&c.push(It({active:u>2},d(yt.SD))),s>yt.HD?(c.push(It({active:!1},d(yt.HD))),c.push(It({active:!0},d(yt.FHD)))):c.push(It({active:!0},d(s)));for(var l=0,p=0;p<c.length;++p)0!=p&&(c[p].minBitrate=l),l=Math.round(Math.max((c[p].maxBitrate+c[p].minBitrate)/2,c[p].maxBitrate-400));return c},Ut=function(e){if(1===e.length)return e;var t,r=e.slice(),n=Ot(r);try{for(n.s();!(t=n.n()).done;){var i=t.value;i.targetWidth/i.targetHeight!=16/9&&(i.targetHeight=i.targetWidth/(16/9))}}catch(e){n.e(e)}finally{n.f()}return r};function Vt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Bt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Vt(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Vt(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function qt(e,t,r){return t=F(t),N(e,Ht()?Reflect.construct(t,r||[],F(e).constructor):t.apply(e,r))}function Ht(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ht=function(){return!!e})()}function Yt(e,t,r,n){var i=Ge(F(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var Wt=ht(),Jt=t().log,Qt=function(){function e(t,r){var n;if(C(this,e),n=qt(this,e,[t]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t){var i,o=t.muted;if(n.muted=o,!r)r=null===(i=t.getSettings())||void 0===i?void 0:i.deviceId}return n.enabled=!0,n.deviceId=r,n}return U(e,Pt),L(e,[{key:"setMediaStreamTrack",value:function(t){var r=this;Yt(e,"setMediaStreamTrack",this)([t]),t&&(this.trackSettings=t.getSettings(),t.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(e){return Jt.info("setEnabled",e),this.isClosed?Promise.reject(new i(o.InvaildState)):(this.enabled=e,this.emit(he,e?"unmute":"mute"),e?this.updateNewTrack():(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===z.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),Promise.resolve()));var t}},{key:"close",value:function(){var e;Jt.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(he,"stop"),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.audioContext&&(this.sourceNode=null,this.analyser=null,this.audioContext=null),this.source===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===z.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return Jt.info("setMuted",e),this.isClosed?Promise.reject(new i(o.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(he,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return Jt.debug("gengrate new audioTrack"),new Promise((function(t,r){var n;Fe({audio:Bt(Bt({source:e.source},e.config),{},{deviceId:e.deviceId})}).then((function(e){n=e.getAudioTracks()[0]})).catch((function(t){try{var i=e.audioContext.createOscillator(),o=e.audioContext.createMediaStreamDestination();i.connect(o),n=o.stream.getAudioTracks()[0]}catch(e){Jt.error("gengrate new audioTrack error",u(t)),r(u(t))}})).finally((function(){n&&t(n)}))}))}},{key:"getVideoTrack",value:function(){var e=this;return Jt.debug("gengrate new videoTrack"),new Promise((function(t,r){var n;Fe({video:Bt(Bt({source:e.source},e.config),{},{deviceId:e.deviceId}),audio:!1}).then((function(e){n=e.getVideoTracks()[0],t(n)})).catch((function(e){Jt.error("gengrate new videoTrack error",d(e)),r(d(e))}))}))}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,Jt.debug("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(t=M(se.mark((function e(t){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(Jt.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof $t)||"user"!==t&&"environment"!==t){e.next=7;break}this.config.facingMode=t,e.next=10;break;case 7:if(this.deviceId!==t){e.next=9;break}return e.abrupt("return");case 9:this.deviceId=t;case 10:return e.abrupt("return",this.updateNewTrack());case 11:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(Jt.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var t}(),Kt=function(){function e(t,r,n){var i;return C(this,e),(i=qt(this,e,[t,r])).config=n,t&&(i.maxBitrate=Ft(t,n.frameRate,n.maxBitrate)),i}return U(e,Qt),L(e,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(e){var t=this;Jt.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),e);var r=e.dimension,n=e.frameRate,a=e.maxBitrate,s=e.optimizationMode,c=e.mirror;if(n&&Number.isNaN(n))return Promise.reject(new i(o.InvaildArgument,"invalid frameRate"));if(r&&!de[r])return Promise.reject(new i(o.InvaildArgument,"invalid dimension"));!c!=!this.config.mirror&&(this.emit(he,"mirror",c),this.config.mirror=c),s&&s!==this.optimizationMode&&(this.config.optimizationMode=s,this.emit(he,"optimizationMode"));var u=!1;if(r&&this.config.dimension!==r&&(this.config.dimension=r,u=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),u=!0),a&&this.maxBitrate!==a&&(u=!0),!u)return Promise.resolve();var l=Bt({frameRate:this.config.frameRate},Le(this.config.dimension)),p=this.getMediaStreamTrack();return null==p?void 0:p.applyConstraints(l).then((function(){t.maxBitrate=Ft(t.getMediaStreamTrack(),t.config.frameRate,a),t.emit(he,"republish",t)})).catch((function(e){var r=d(e);throw Jt.error("videoTrack ".concat(t.getTrackId()," setEncoderConfiguration error"),r),r}))}},{key:"getCurrentFrameData",value:function(){return Jt.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:ut(Wt.getElement(this)[0])}},{key:"play",value:function(t,r){return Jt.info("local video play"),Yt(e,"play",this)([t,r])}}])}(),zt=function(){function e(t,r){return C(this,e),qt(this,e,[t,r])}return U(e,Qt),L(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Wt.getElement(this)[0]&&(Wt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Wt.getElement(this)[0]?Wt.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:ct(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return Jt.info("local audio play"),Yt(e,"play",this)([])}}])}(),$t=function(){function e(t,r){var n;return C(this,e),(n=qt(this,e,[t,r.deviceId,r])).setSource(z.CAMERA),n}return U(e,Kt),L(e)}(),Xt=function(){function e(t,r){var n;return C(this,e),(n=qt(this,e,[t,(r||{}).deviceId])).config=r,n.setSource(K.MIC),n.analyser=n.audioContext.createAnalyser(),n}return U(e,zt),L(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Wt.getElement(this)[0]&&(Wt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Wt.getElement(this)[0]?Wt.getElement(this)[0].volume:void 0}}])}(),Zt=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,d,l,p;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,d=void 0===c||c,e.prev=2,e.next=5,Fe({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:K.MIC,AEC:o,AGC:s,ANS:d}});case 5:return l=e.sent,p=l.getAudioTracks()[0],Jt.info("MicrophoneAudioTrack created"),e.abrupt("return",new Xt(p,Object.assign({},t,{AEC:o,AGC:s,ANS:d})));case 11:throw e.prev=11,e.t0=e.catch(2),u(e.t0);case 14:case"end":return e.stop()}}),e,null,[[2,11]])})));return function(t){return e.apply(this,arguments)}}(),er=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,l;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=2,e.next=5,Fe({video:{deviceId:r,source:z.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 5:return u=e.sent,l=u.getVideoTracks()[0],Jt.info("CameraVideoTrack created"),e.abrupt("return",new $t(l,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 11:throw e.prev=11,e.t0=e.catch(2),d(e.t0);case 14:case"end":return e.stop()}}),e,null,[[2,11]])})));return function(t){return e.apply(this,arguments)}}(),tr=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,d;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.displaySurface,n=void 0===r?"monitor":r,i=t.dimension,o=void 0===i?"VD_1920x1080":i,a=t.optimizationMode,s=void 0===a?"detail":a,c=Math.min(t.frameRate||5,30),e.prev=2,e.next=5,Fe({video:{source:z.SCREENCAST,displaySurface:n,frameRate:c,dimension:o},audio:!1});case 5:return u=e.sent,(d=new Kt(u.getVideoTracks()[0],null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(z.SCREENCAST),Jt.info("ScreenVideoTrack created"),e.abrupt("return",[d]);case 12:throw e.prev=12,e.t0=e.catch(2),b(e.t0);case 15:case"end":return e.stop()}}),e,null,[[2,12]])})));return function(t){return e.apply(this,arguments)}}(),rr=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c,u,l,p,f,v,h,m,y,g,b,S,k,P,w;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,l={AEC:!0,AGC:!0,ANS:!0},f=(p=r||l).AEC,v=void 0===f||f,h=p.AGC,m=void 0===h||h,y=p.ANS,g=void 0===y||y,e.prev=4,e.next=7,Fe({video:{deviceId:i,source:z.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:K.MIC,AEC:v,AGC:m,ANS:g}});case 7:return b=e.sent,S=b.getVideoTracks()[0],k=b.getAudioTracks()[0],Jt.info("CameraVideoTrack and MicrophoneTrack created"),P=new $t(S,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),w=new Xt(k,Object.assign({},Object.assign({},r,{AEC:v,AGC:m,ANS:g}))),e.abrupt("return",[P,w]);case 16:throw e.prev=16,e.t0=e.catch(4),d(e.t0);case 19:case"end":return e.stop()}}),e,null,[[4,16]])})));return function(t,r){return e.apply(this,arguments)}}(),nr=function(){var e=M(se.mark((function e(t){var r,n,a,s,c,u,d,l;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=(r=t||{}).mediaStreamTrack,a=r.dimension,s=void 0===a?"VD_640x480":a,c=r.optimizationMode,u=void 0===c?"balanced":c,d=Math.min(t.frameRate||15,30),n instanceof MediaStreamTrack&&"video"===n.kind){e.next=4;break}throw new i(o.InvaildArgument,"missing video mediaStreamTrack");case 4:return(l=new Kt(n,null,Object.assign({},t,{frameRate:d,dimension:s,optimizationMode:u}))).setSource(z.CAMERA),e.abrupt("return",l);case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),ir=function(){var e=M(se.mark((function e(t){var r,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((r=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===r.kind){e.next=3;break}throw new i(o.InvaildArgument,"missing audio mediaStreamTrack");case 3:return(n=new zt(r)).setSource(K.MIC),e.abrupt("return",n);case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function or(e,t,r,n){var i=Ge(F(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function ar(e,t,r){return t=F(t),N(e,sr()?Reflect.construct(t,r||[],F(e).constructor):t.apply(e,r))}function sr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(sr=function(){return!!e})()}var cr,ur=t().log,dr=ht(),lr=function(){function e(t,r,n){var i;return C(this,e),i=ar(this,e,[t,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return U(e,Pt),L(e,[{key:"getUserId",value:function(){return ur.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(),pr=function(){function e(t,r,n){var i;return C(this,e),i=ar(this,e,[t,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return U(e,lr),L(e,[{key:"getMediaStreamTrack",value:function(){return we.audioSFU?st(this.sfuStream):or(e,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){ur.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){ur.info("setVolume",e),dr.getElement(this)[0]&&(dr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(ur.info("getVolume"),dr.getElement(this)[0])return dr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return ur.info("setSpeaker",e),new Promise((function(r,n){var a,s=dr.getElement(t)[0];s||n(new i(o.InvaildState,"please playout audio first")),s.setSinkId||n(new i(o.SpeakerSetNotSupported)),null===(a=s.setSinkId)||void 0===a||a.call(s,e).then((function(){t.deviceId=e,r()})).catch((function(e){n(u(e))}))}))}},{key:"getVolumeLevel",value:function(){return ct(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return ur.info("remote audio play"),or(e,"innnerPlay",this,3)([{}])}}])}(),fr=function(){function e(t,r){return C(this,e),ar(this,e,[t,r])}return U(e,lr),L(e,[{key:"play",value:function(t,r){return ur.info("remote video play"),or(e,"innnerPlay",this,3)([{element:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(ur.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&or(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return ur.info("getCurrentFrameData"),this.isPlaying?ut(dr.getElement(this)[0]):null}}])}();!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(cr||(cr={}));var vr=S({nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}}}),hr=vr.lookupType("signal_msg.Response"),mr=vr.lookupType("signal_msg.BatchNotification"),yr=vr.lookupType("signal_msg.MediaMessage"),gr=vr.lookupType("signal_msg.StreamNotification");vr.lookupType("signal_msg.ProgressNotification");var br=vr.lookupType("signal_msg.ServerFailoverNotification"),Sr=vr.lookupType("signal_msg.PublishRequest"),kr=vr.lookupType("signal_msg.SoacRequest"),Pr=vr.lookupType("signal_msg.UnpublishRequest"),wr=vr.lookupType("signal_msg.StreamControlRequest"),Or=vr.lookupType("signal_msg.SubscribeRequest"),Tr=vr.lookupType("signal_msg.SetStreamPropertiesRequest"),Er=vr.lookupType("signal_msg.UnsubscribeRequest"),Ir=vr.lookupType("signal_msg.SubscriptionControlRequest"),Rr=vr.lookupType("signal_msg.CreatePeerConnectionRequest"),Ar=vr.lookupType("signal_msg.ClosePeerConnectionRequest"),_r=vr.lookupType("signal_msg.BatchPublishRequest"),Mr=vr.lookupType("signal_msg.BatchUnpublishRequest"),Cr=vr.lookupType("signal_msg.BatchSubscribeRequest"),Dr=vr.lookupType("signal_msg.BatchUnsubscribeRequest"),xr=vr.lookupType("signal_msg.JoinGroupRequest"),jr=vr.lookupType("signal_msg.SetGroupPropertiesRequest"),Lr=vr.lookupType("signal_msg.DismissGroupRequest"),Nr=vr.lookupType("signal_msg.LeaveGroupRequest"),Fr=vr.lookupType("signal_msg.SyncDataRequest"),Gr=vr.lookupType("signal_msg.SyncDataByIdsRequest"),Ur=vr.lookupType("signal_msg.GroupChangeLog"),Vr=vr.lookupType("signal_msg.GroupListChangeLog"),Br=vr.lookupType("signal_msg.SetParticipantPropertiesRequest"),qr=vr.lookupType("signal_msg.QueryStreamsVerRequest"),Hr=vr.lookupType("signal_msg.QueryStreamsRequest");function Yr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Yr=function(){return!!e})()}var Wr=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,Yr()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=t,r.rpcId=0,r.reporter=t.reporter,r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return U(e,c),L(e,[{key:"join",value:function(e,t){return this.channel.join(e,t).then((function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}}))}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",gr.decode(t)):"serverFailover"===e?this.emit("serverFailover",br.decode(t)):"media-message"===e?this.emit("media-message",yr.decode(t)):"group"===e?this.emit("group",Ur.decode(t)):"group-list"===e&&this.emit("group-list",Vr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;mr.decode(e).notificationItem.forEach((function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)}))}},{key:"createPeerConnection",value:function(e){var t=Rr.encode(e).finish();return this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=Ar.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=Cr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=jr.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=Dr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=_r.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=Mr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=Sr.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){var t=Br.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=kr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=Pr.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=wr.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=Tr.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=Or.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=Er.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=Ir.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=qr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=Hr.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=xr.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=Nr.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=Lr.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=Fr.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=Gr.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then((function(e){return e.syncDataByIdsResponse}))}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then((function(e){return e.observeAllGroupsResponse}))}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then((function(e){return e.unobserveAllGroupsResponse}))}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(i,o){var a=r.rpcId++;r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," param====> ").concat(JSON.stringify(n||""))),r.channel.signaling.rpc(e,t,n).then((function(t){var n=hr.decode(t);n.code===cr.Result.Ok?(r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," result====> ").concat(JSON.stringify(n))),i(n)):(r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," error====> ").concat(JSON.stringify(n))),o(n))}))}))}}])}();function Jr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Jr=function(){return!!e})()}var Qr=function(){function e(){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,Jr()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t().statsConfig;return r.interval=(null==a?void 0:a.statsIntervalMs)||2e3,r.start(),r}return U(e,c),L(e,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=l((function(){e.makeReport()}),this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(v(this.timer,"interval"),this.timer=null)}}])}();function Kr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function zr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Kr(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Kr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function $r(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Xr(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Xr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Xr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Zr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Zr=function(){return!!e})()}var en={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},tn={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},rn=function(){function t(e){var r,n,i,o;C(this,t),n=this,i=F(i=t),r=N(n,Zr()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var a=e.tracks.filter((function(e){return"video"===e.trackMediaType}))[0];return r.source=null==a?void 0:a.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},tn),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},en),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return U(t,Qr),L(t,[{key:"extractVideoMetrics",value:function(t){var r=this,n=Object.assign({source:this.source,trackStats:[]},tn,this.connection.peerConnectionStats);if(n.timestamp=Date.now(),this.track){var i=this.track.getMediaStreamTrack().getSettings(),o=i.width,a=i.height,s=i.frameRate;n.captureFramesPerSecond=s===1/0?0:s||0,n.captureFrameWidth=o||0,n.captureFrameHeight=a||0}var c=new Map,u=He(n,this.lastVideoSendInfo);return t.forEach((function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var i=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(i.sendFrameWidth=t.frameWidth||0,i.sendFrameHeight=t.frameHeight||0,i.framesSent=t.framesSent||0,i.framesEncoded=t.framesEncoded||0,i.targetBitrate=t.targetBitrate||0,i.qpSum=t.qpSum||0,i.bytesSent=t.bytesSent||0,i.packetsSent=t.packetsSent||0,i.packetsSentForLost=i.packetsSent||0,i.sentTimestamp=t.timestamp||0,i.totalEncodeTime=t.totalEncodeTime||0,i.keyFramesEncoded=t.keyFramesEncoded||0,i.firCount=t.firCount||0,i.pliCount=t.pliCount||0,i.retransmittedBytesSent=t.retransmittedBytesSent||0,i.retransmittedPacketsSent=t.retransmittedPacketsSent||0,i.qualityLimitationReason=t.qualityLimitationReason||"",i.sendFramesPerSecond=t.framesPerSecond||0,i.sendFrameWidth>n.maxSendFrameWidth){if(n.maxSendFrameWidth=i.sendFrameWidth,!i.sendFramesPerSecond&&o){var a=We(i.framesSent||i.framesEncoded,o.framesSent||o.framesEncoded);i.sendFramesPerSecond=Math.round(a/u)}if(i.framesEncoded){var s=We(i.framesEncoded,null==o?void 0:o.framesEncoded);n.encodeFramesPerSecond=Math.round(s/u)}n.sendFramesPerSecond=i.sendFramesPerSecond}c.set(t.ssrc,i),n.targetBitrate=i.targetBitrate,n.totalBytesSent+=i.bytesSent,n.totalPacketsSent+=i.packetsSent,n.totalEncodedTime+=i.totalEncodeTime,n.totalFramesEncoded+=i.framesEncoded,n.totalFramesSent+=i.framesSent,n.totalQpSum+=i.qpSum,n.maxSendFrameHeight=Math.max(i.sendFrameHeight,n.maxSendFrameHeight),c.set(t.ssrc,i)}else if(/track/i.test(t.type)&&!1===t.remoteSource){if(e.isSafari()){var d=c.get(t.ssrc)||{};d.sendFrameHeight>0||(d.sendFrameWidth=t.frameWidth||0,d.sendFrameHeight=t.frameHeight||0),d.framesSent=t.framesSent||0,d.totalEncodeTime=t.totalEncodeTime||0,c.set(t.ssrc,d),n.totalFramesEncoded+=d.framesEncoded,n.totalEncodedTime+=d.totalEncodeTime,n.totalFramesSent+=d.framesSent,c.set(t.ssrc,d)}}else if(/remote-inbound-rtp/i.test(t.type)){var l=c.get(t.ssrc)||{},p=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};l.packetsLost=t.packetsLost||0,l.lostTimestamp=t.timestamp,n.totalPacketsLost+=l.packetsLost,l.packetsLost===(p.packetsLost||0)&&(l.packetsSentForLost=p.packetsSentForLost||0,l.lostTimestamp=p.lostTimestamp||0),c.set(t.ssrc,l)}})),n.trackStats=c,n}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=$r(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=wt(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=We(a.framesSent,s.framesSent),u=We(a.framesEncoded,s.framesEncoded),d=We(a.keyFramesEncoded,s.keyFramesEncoded),l=We(a.retransmittedBytesSent,s.retransmittedBytesSent),p=We(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=We(a.firCount,s.firCount),v=We(a.pliCount,s.pliCount),h=We(a.packetsSent,s.packetsSent),m=We(a.packetsSentForLost,s.packetsSentForLost),y=We(a.lostTimestamp,s.lostTimestamp),g=We(a.sentTimestamp,s.sentTimestamp),b=We(a.packetsLost,s.packetsLost),S=We(a.totalEncodeTime,s.totalEncodeTime),k=We(a.qpSum,s.qpSum),P=a.qualityLimitationReason,w=a.sendFrameWidth,O=zr(zr({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:w,qualityLimitationReason:P},a),{},{deltaQbSum:k,deltaPacketsSent:h,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:y,deltaFramesEncoded:u,deltaKeyFramesEncoded:d,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:v,deltaTimestampForSent:g,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:l,deltaRetransmittedPacketsSent:p});r.push(O)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,d=We(e.timestamp,this.lastVideoSendInfo.timestamp),l=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var v=f.deltaFramesEncoded||f.deltaFramesSent;l&&(l=0===v),s.attr_encoded_framerate_sim.push(ce({},p,Math.round(1e3*v/d))),s.attr_encode_qp_sim.push(ce({},p,Math.round((f.deltaQbSum||0)/(v||Number.EPSILON))));var h=f.deltaTimestampForLost,m=f.deltaTimestampForSent,y=f.deltaPacketsLost,g=f.deltaPacketsSentForLost;if(y&&g&&h&&m){var b=y/h/(g/m);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,k=Object.entries(s);S<k.length;S++){var P=wt(k[S],2),w=P[0],O=P[1];t[w]=O.length?JSON.stringify(O):""}var T=0,E=We(o,this.lastVideoSendInfo.totalFramesEncoded),I=We(a,this.lastVideoSendInfo.totalEncodedTime);E&&I&&(T=Math.round(1e3*I/E));var R=We(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=d,t.attr_bitrate=d>0?Math.min(Math.round(8*R*1e3/d),2e7):0,t.attr_enc_average_elapsed_ms=T,this.videoSendReport=t,l&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:d,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},en,this.connection.peerConnectionStats);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(We(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*We(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/We(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,a=this.pc;if(!a||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==a||!a.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then((function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e)}}))}}])}();function nn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return on(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?on(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function on(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function an(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(an=function(){return!!e})()}var sn={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},cn={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},un=function(){function e(t){var r,n,i,o,a;C(this,e),i=this,o=F(o=e),n=N(i,an()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=t.connection,c=t.transceiver,u=t.uid,d=t.stream,p=t.transceivers;return n.connection=s,n.pc=s.pc,n.tranceiver=c,n.tranceivers=p,n.firstReportTimer=l((function(){n.getStats().then((function(e){n.makeFirstReport(e)}))}),400,"interval"),n.source="mcu"!==u&&(null===(r=d.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},cn),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},sn),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return U(e,Qr),L(e,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},sn,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},sn,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=nn(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},cn,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(We(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=We(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=We(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=We(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,d=t.packetsReceivedForLost,l=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=We(e.timestamp,i);if(e.bytesReceived-u>=0){var v=We(e.packetsLost,a),h=We(e.packetsReceivedForLost,d),m=0;try{m=Math.round(v/h*255)}catch(e){m=0}isNaN(m)&&(m=0);var y=We(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*y/f),attr_dec_frames:y,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:We(e.framesDropped,c),attr_fir_count:We(e.firCount,r),attr_freeze_count:We(e.freezeCount,o),attr_pli_count:We(e.pliCount,n),attr_retx_bytes:We(e.retransmittedBytesReceived,l),attr_retx_packets:We(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*We(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:y,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,a=this.pc;if(!(a&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==a||!a.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var s=n.map((function(e){return e.receiver.track})).filter((function(e){return!!e}));return Promise.all(s.map((function(e){return a.getStats(e)}))).then((function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}}))}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?a.getStats(r.receiver.track).then((function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}})):void 0}},{key:"stop",value:function(){var t,r,n;(t="stop",r=this,"function"==typeof(n=Ge(F(e.prototype),t,r))?function(e){return n.apply(r,e)}:n)([]),this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();function dn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ln(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ln(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ln(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function pn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function fn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?pn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):pn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function vn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(vn=function(){return!!e})()}var hn=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,vn()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t.connection,s=t.stream,c=t.uid,u=t.resolutionInfo;return r.connection=a,r.resolutionInfo=u,r.signaling=a.signaling,r.stream=s,r.uid=c,r.reporter=a.reporter,r.connection.once("ended",(function(){r.clear()})),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=re.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return U(e,c),L(e,[{key:"handleStreamAdd",value:function(e,t){var r,n=this,i=function(){n.reporter.trace.subscribe({init:!1,capabilities:n.stream.media,remoteStreamId:n.stream.id,remoteUserId:n.uid,sessionId:n.id,elapse:Date.now()-n.startTime,resolutionInfo:n.resolutionInfo}),n.startTime=Date.now()};if(we.audioSFU&&"audio"===e.kind){var o,a=null===(o=this.transceivers)||void 0===o?void 0:o.map((function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id}));null!=a&&a.includes(e.id)&&!this._stream&&(this._stream=t,i())}else e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)&&(this._stream=new MediaStream([e]),i())}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===re.Processing)return this.clear(),this.signaling.unsubscribe({subscriptionId:this.id}).catch((function(t){e.reporter.log.warn("negative ack for unsubscribing, ".concat(t))}))}},{key:"mute",value:function(e){return this.signaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.signaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=this.stream.id;return this.resolutionInfo=e,this.signaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:t,params:e}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==re.End&&(this.reset(),this.state=re.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new un(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new un(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:-1,remoteUserId:this.uid})}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=He(r,o),s=We(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=He(n,l),f=We(n.bytesReceived,l.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(We(null==n?void 0:n.framesDecoded,l.framesDecoded)/p),receiveFrameRate:Math.round(We(null==n?void 0:n.framesReceived,l.framesReceived)/p),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},h=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),m=(null===(d=this.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.source)===z.CAMERA&&f>5e3&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&m?h&&!we.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=m),this.videoStatsMap.set(t,v)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(fn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(fn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-first-packet",(function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("audio-first-frame",(function(){e.emit("audio-first-frame")}))):(this.monitor.on("video-first-packet",(function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("video-recv-stream",(function(t){e.reporter.metric.videoRecvStream(fn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(),mn=function(e){var t,r={audio:[],video:[]},n=dn(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo;if(!a){var c=yn(o,s),u=c.audio,d=c.video;if(u){var l=fn(fn({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:An()}]});we.audioSFU&&(l.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:An()}}))),r.audio.push(l)}else if(d){var p,f;r.video.push(fn(fn({},d),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:An(),rtxSsrc:An()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},yn=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:t}}return a},gn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=[],o={},t.forEach((function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var u=new hn(fn(fn({},r),{},{uid:s,resolutionInfo:c,stream:n}));o[n.id]=u}})),s=new Promise((function(e,r){a=function(){var a=M(se.mark((function a(){var s;return se.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=mn(t),a.next=3,Ln(n,s,o);case 3:n.signaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:we.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=M(se.mark((function r(n){var a,s,c,u,d;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=4;break}return i.forEach((function(e){e.error=e.error||Ee(e.stream,s)})),r.abrupt("return",e(i));case 4:c=dn(a),r.prev=5,d=se.mark((function e(){var r,n,a,s,c,d;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],d=t.findIndex((function(e){return e.stream.id===s.id})),"ok"===a&&c?(c.id=n,i[d].id=n,i[d].subscription=c):"ok"!==a&&(i[d].error=Ee(c.stream,a));case 4:case"end":return e.stop()}}),e)})),c.s();case 8:if((u=c.n()).done){r.next=12;break}return r.delegateYield(d(),"t0",10);case 10:r.next=8;break;case 12:r.next=17;break;case 14:r.prev=14,r.t1=r.catch(5),c.e(r.t1);case 17:return r.prev=17,c.f(),r.finish(17);case 20:e(i);case 21:case"end":return r.stop()}}),r,null,[[5,14,17,20]])})));return function(e){return r.apply(this,arguments)}}()).catch(r);case 4:case"end":return a.stop()}}),a)})));return function(){return a.apply(this,arguments)}}()})),n.addTask(a),e.abrupt("return",s);case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),bn=function(){var e=M(se.mark((function e(t,r){var n,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,o=new Promise((function(e,r){n=function(){var n=M(se.mark((function n(){var o,a;return se.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)})).map((function(e){return e.id})),n.next=4,Nn(i,t);case 4:i.signaling.batchUnSubscribe({connectionId:i.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.state=re.End,e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",o);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function Sn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function kn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Sn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Sn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Pn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return wn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?wn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function wn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var On={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},Tn=0,En=0,In=0,Rn=new Set,An=function(){if(0==Tn||0==En)return 0;var e=Math.min(En+1,1e4);do{var t=Tn+(En&In++);if(0!=t&&!Rn.has(t))return t}while(--e>0);return 0},_n=function(t,r){var n,i;if((null===(n=t.rids)||void 0===n?void 0:n.length)>1)return e.isFirefox()&&(r=jn(r)),r.rids=null===(i=t.rids)||void 0===i?void 0:i.map((function(e){return{direction:"recv",id:e.id}})),r.simulcast={dir1:"recv",list1:t.simulcast.list1},r},Mn=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=4,o.createOffer();case 4:return a=e.sent,e.next=7,o.setLocalDescription(a);case 7:return r.localSDP=R.parse(a.sdp),s=r.localSDP.media.find((function(e){return e.mid==n.mid})),c=i.media.find((function(e){return e.mid==n.mid})),_n(s,c),e.next=13,o.setRemoteDescription({type:"answer",sdp:R.write(i)});case 13:r.remoteSDP=i;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),Cn=function(){var t=M(se.mark((function t(r,n){var i,o,a,s,c,u,d,l,p,f;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=r.pc,o=r.idToTransceiverMap,a=r.remoteSDP,s=new MediaStream(n.map((function(e){return e.getMediaStreamTrack()}))),c=n.map((function(e){var t={direction:"sendonly"};if(e instanceof Kt){var n=Gt(e).filter((function(e){return e.active}));t.sendEncodings=n.map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:1===n.length}}))}var i=r.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Kt&&i.sender.setParameters){var a=e.optimizationMode,s=i.sender.getParameters();s.degradationPreference=On[a]||"balanced",i.sender.setParameters(s)}return o.set(e.getTrackId(),i),i})),t.next=5,i.createOffer();case 5:return u=t.sent,d=R.parse(u.sdp),t.next=9,i.setLocalDescription(u);case 9:r.localSDP=d,a.groups[0].mids=r.localSDP.groups[0].mids,l=Pn(c),t.prev=12,f=se.mark((function t(){var r,n,i,o;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=p.value,n=a.media.find((function(e){return e.type===r.sender.track.kind})),e.isFirefox()&&"video"===n.type&&(delete n.rids,delete n.simulcast),i=kn(kn({},n),{},{ext:ke(n.ext),mid:r.mid}),o=d.media.find((function(e){return e.mid==r.mid})),_n(o,i),a.media.push(i);case 7:case"end":return t.stop()}}),t)})),l.s();case 15:if((p=l.n()).done){t.next=19;break}return t.delegateYield(f(),"t0",17);case 17:t.next=15;break;case 19:t.next=24;break;case 21:t.prev=21,t.t1=t.catch(12),l.e(t.t1);case 24:return t.prev=24,l.f(),t.finish(24);case 27:return t.next=29,i.setRemoteDescription({type:"answer",sdp:R.write(a)});case 29:return r.remoteSDP=a,t.abrupt("return",{localSDP:r.localSDP,stream:s});case 31:case"end":return t.stop()}}),t,null,[[12,21,24,27]])})));return function(e,r){return t.apply(this,arguments)}}(),Dn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map((function(e){return e.transceiver})).forEach((function(e){if(e){n.removeTrack(e.sender);var t=i.media.find((function(t){return t.mid==(null==e?void 0:e.mid)}));e.direction="inactive",t.direction="inactive"}})),e.next=5,n.createOffer();case 5:return o=e.sent,a=R.parse(o.sdp),e.next=9,n.setLocalDescription(o);case 9:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=14,n.setRemoteDescription({type:"answer",sdp:R.write(i)});case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),xn=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;!function(e){e.ssrc&&Rn.add(e.ssrc),e.rtxSsrc&&Rn.add(e.rtxSsrc)}(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter((function(e){return void 0!==e})).forEach((function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:g(),id:e})}))},jn=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some((function(e){return e.uri.includes("rtp-stream-id")}))||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},Ln=function(){var e=M(se.mark((function e(t,r,n){var i,o,a,s,c,u,d,l,p,f,v,h,m,y,g,b,S,k,P,w,O,T,E,I,A,_,M,C;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=t.pc,s=t.idToTransceiverMap,c=t.remoteSDP,u=t.idToTransceiversMap,d=c.media.find((function(e){return"video"===e.type})),l=c.media.find((function(e){return"audio"===e.type})),p=null===(i=d.ssrcs)||void 0===i?void 0:i.find((function(e){return"msid"===e.attribute})).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(v=null===(f=r.audio)||void 0===f?void 0:f[0],h=v.from,we.audioSFU){if(u.get(h)){m=Pn(u.get(h));try{for(m.s();!(y=m.n()).done;)y.value.direction="recvonly"}catch(e){m.e(e)}finally{m.f()}g=c.media.filter((function(e){return"audio"===e.type})),b=Pn(g);try{for(b.s();!(S=b.n()).done;)S.value.direction="sendonly"}catch(e){b.e(e)}finally{b.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})})),u.set(h,t.mcuAudioTranceivers);n[h].addTransceivers(u.get(h))}else s.get(h)||s.set(h,t.mcuAudioTranceiver),s.get(h).direction="recvonly",l.direction="sendonly",n[h].addTransceiver(s.get(h));k=Pn(r.video),e.prev=6,w=se.mark((function e(){var t,r,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=P.value,r=t.from,i=s.get(r)){e.next=7;break}s.set(r,a.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===i.direction){e.next=18;break}return i.direction="inactive",e.next=11,a.createOffer();case 11:return o=e.sent,e.next=14,a.setLocalDescription(o);case 14:return c.media.find((function(e){return e.mid==i.mid})).direction="inactive",e.next=18,a.setRemoteDescription({type:"answer",sdp:R.write(c)});case 18:s.get(r).direction="recvonly";case 19:n[r].addTransceiver(s.get(r));case 20:case"end":return e.stop()}}),e)})),k.s();case 9:if((P=k.n()).done){e.next=13;break}return e.delegateYield(w(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),k.e(e.t1);case 18:return e.prev=18,k.f(),e.finish(18);case 21:return e.next=23,a.createOffer();case 23:return O=e.sent,T=R.parse(O.sdp),c.groups[0].mids=T.groups[0].mids,e.next=28,a.setLocalDescription(O);case 28:t.localSDP=T,we.audioSFU&&r.audio[0]&&(E=r.audio[0],I=E.ssrcGroup,A=E.from,u.get(A).forEach((function(e,t){var r,n=null===(r=I[t])||void 0===r?void 0:r.ssrc,i=c.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=kn(kn({},l),{},{mid:e.mid}),c.media.push(i)),i.ssrcs=Fn(n,p),i.direction="sendonly"}))),_=Pn(r.video),e.prev=31,C=se.mark((function e(){var t,r,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=M.value,r=t.from,i=t.subSsrcGroup,o=s.get(r),(a=c.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})))||((a=kn({},d)).mid=o.mid,c.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,xn(i,a,p);case 8:case"end":return e.stop()}}),e)})),_.s();case 34:if((M=_.n()).done){e.next=38;break}return e.delegateYield(C(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),_.e(e.t3);case 43:return e.prev=43,_.f(),e.finish(43);case 46:return t.remoteSDP=c,e.next=49,a.setRemoteDescription({type:"answer",sdp:R.write(c)});case 49:case"end":return e.stop()}}),e,null,[[6,15,18,21],[31,40,43,46]])})));return function(t,r,n){return e.apply(this,arguments)}}(),Nn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c,u,d,l,p,f,v;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=Pn(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,d=c.transceivers,u?o.push(u):d&&o.push.apply(o,ke(d))}catch(e){a.e(e)}finally{a.f()}return o.forEach((function(e){e.direction="inactive"})),e.next=7,n.createOffer();case 7:return l=e.sent,e.next=10,n.setLocalDescription(l);case 10:t.localSDP=R.parse(l.sdp),p=se.mark((function e(){var t;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=v[f],i.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),f=0,v=o;case 13:if(!(f<v.length)){e.next=18;break}return e.delegateYield(p(),"t0",15);case 15:f++,e.next=13;break;case 18:return t.remoteSDP=i,e.next=21,n.setRemoteDescription({type:"answer",sdp:R.write(i)});case 21:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Fn=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:g(),id:e}]},Gn=function(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"all",o=r.direction,a=r.remoteSDP,s=R.parse(t);"relay"===i&&s.media.forEach((function(e){e.candidates=e.candidates.filter((function(e){return k(e.ip)}))})),n&&(s=function(e,t){var r=t.media.find((function(e){return"audio"===e.type})),n=t.media.find((function(e){return"video"===e.type}));return e.media.forEach((function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,d=t.rids,l=void 0===d?[]:d;"audio"===t.type?e.media[i]=kn(kn({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=kn(kn({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),l.length&&(e.media[i].rids=l,e.media[i].simulcast={dir1:"recv",list1:l.map((function(e){return"~".concat(e.id)})).join(";")}))})),e}(a,s));var c=s.media.find((function(e){return"video"===e.type}));if("uplink"===o&&e.isFirefox()&&we.simulcast&&(c.ext=c.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!c.ssrcs&&"downlink"===o){var u=An(),d=s.msidSemantic.token;c.ssrcs=Fn(u,d)}return r.remoteSDP=s,s},Un=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=Pn(n);try{for(u.s();!(r=u.n()).done;){var d=r.value,l=d.config,p=d.payload,f=l.split(";");c[p]={};var v,h=Pn(f);try{for(h.s();!(v=h.n()).done;){var m=wt(v.value.split("="),2),y=m[0],g=m[1];c[p][y]=g}}catch(e){h.e(e)}finally{h.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var k=n.length-1;k>=0;k--){var P=n[k].payload;s.includes(P)&&n.splice(k,1)}for(var w=o.length-1;w>=0;w--)s.includes(o[w].payload)&&o.splice(w,1);for(var O=a.length-1;O>=0;O--)s.includes(a[O].payload)&&a.splice(O,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},Vn=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return Un(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},Bn=function(e){var t=e.media.find((function(e){return"video"===e.type}));return Un(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function qn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Hn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?qn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):qn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Yn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Wn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Wn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Wn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Jn=function(){return!!e})()}var Qn=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,Jn()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t.connection,s=t.uid,c=t.tracks,u=void 0===c?[]:c;return r.tracks=u,r.connection=a,r.signaling=a.signaling,r.uid=s,r.reporter=a.reporter,r.state=re.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),u.forEach((function(e){e.on(he,r.handleTracEvent)})),r.encodings=Gt(u[0]),r.state=re.Processing,r.connection.once("ended",(function(){r.clear()})),r}return U(e,c),L(e,[{key:"stop",value:function(){var e=this;return this.state!==re.Processing?Promise.resolve():zn([this],{connection:this.connection}).catch((function(t){e.clear(),e.reporter.log.warn("negative ack for unpublish, ".concat(m(t)))}))}},{key:"mute",value:function(){if(this.tracks.length&&this.state===re.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!0,this.id),this.signaling.streamControl({streamId:this.id,operation:"pause",data:e})}}},{key:"unmute",value:function(){if(this.tracks.length&&this.state===re.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!1,this.id),this.signaling.streamControl({streamId:this.id,operation:"play",data:e})}}},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0];this.addTransceiver(this.connection.idToTransceiverMap.get(t.getTrackId())),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.signaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){n.stop().then((function(){n.connection.sessionManager.channel.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==re.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(he,e.handleTracEvent)})),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset(),this.state=re.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(!(n<this.feedbackIndex||this.state!==re.Processing)){this.feedbackIndex=n;var o,a=0===i,s=this.transceiver,c=this.connection,u=!1,d=!1,l=s.sender.getParameters(),p=e.map((function(e){return e.rid})),f=l.encodings,v=1===f.length,h=Yn(f);try{for(h.s();!(o=h.n()).done;){var m,y=o.value,g=Yn(e);try{var b=function(){var e=m.value,r=t.encodings.find((function(t){return t.rid===e.rid}));if(e.rid!==y.rid&&y.rid||y.active||a||(y.active=!0,y.scaleResolutionDownBy=r.scaleResolutionDownBy,u=!0),e.rid===y.rid&&!a){var n=Math.max(Math.min(e.bitrate,r.maxBitrate),r.minBitrate);n!==Math.round(y.maxBitrate/1e3)&&(y.maxBitrate=1e3*n,d=!0)}};for(g.s();!(m=g.n()).done;)b()}catch(e){g.e(e)}finally{g.f()}!y.active||p.includes(y.rid)&&!a||(y.active=!1,u=!0)}}catch(e){h.e(e)}finally{h.f()}v&&(f[0].active=!0),(u||d)&&s.sender.setParameters(l),u&&c.addTask((function(){return Mn(t)}))}}},{key:"updateOptionzationMode",value:function(){var e;if(this.tracks[0]instanceof Kt&&null!==(e=this.transceiver)&&void 0!==e&&null!==(e=e.sender)&&void 0!==e&&e.setParameters){var t=this.tracks[0].optimizationMode,r=this.transceiver.sender.getParameters();r.degradationPreference=On[t]||"balanced",this.transceiver.sender.setParameters(r)}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=re.Processing,this.feedbackIndex=-1,this.monitor=new rn(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;this.transceiver&&(null===(t=this.transceiver.sender.track)||void 0===t||t.stop(),this.transceiver.sender.replaceTrack(e))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=He(r,o),s=We(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===l?[]:l,f=(null===(d=this.metricsMap.get(t))||void 0===d?void 0:d.videoMetrics)||{},v=He(n,f),h=We(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*h/v};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(Hn({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(Hn({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(Hn({sessionId:e.id},t))}))}}])}(),Kn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c,u=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=u.length>2&&void 0!==u[2]?u[2]:["common"],i={},e.next=4,Cn(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,c=!1,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Kt){var u;i.video=i.video||[];var d=o.ssrcGroups,l=void 0===d?[]:d,p=Gt(e);p.length>1&&(l=p.map((function(){return{semantics:"FID",ssrcs:"".concat(An()," ").concat(An())}})),c=!0,r.simulcastEnabled=!0),r.simulcastEnabled&&!c&&(c=!0);var f=l.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),v=p[p.length-1],h=Ut(p),m={trackId:e.getTrackId(),forwardOnly:e.source===z.SCREENCAST,msid:s.id,mid:"".concat(o.mid),uplinkSsrcGroup:f,source:e.source||z.CAMERA,streamParameters:{ssrc:null==f||null===(u=f[0])||void 0===u?void 0:u.ssrc,bitrate:"".concat(v.maxBitrate),resolution:{width:v.targetWidth,height:v.targetHeight},framerate:v.maxFramerate},ssrcParameters:f.map((function(e,t){var r;return{ssrc:e.ssrc,active:h[t].active,tlayer:1,bitrate:h[t].maxBitrate,rid:(null===(r=h[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:h[t].maxBitrate,minBitrate:h[t].minBitrate,framerate:h[t].maxFramerate,resolution:{width:h[t].targetWidth,height:h[t].targetHeight}}}))};i.video.push(m)}})),e.abrupt("return",{media:i,enableSimulcast:c});case 10:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),zn=function(){var e=M(se.mark((function e(t,r){var n,i;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise((function(e,i){n=function(){var n=M(se.mark((function n(){var o,a;return se.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),n.next=4,Dn(r.connection,t);case 4:r.connection.signaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear(),e.state=re.End})),e(void 0)})).catch(i);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function $n(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return($n=function(){return!!e})()}var Xn={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},Zn=function(){function t(e){var r,n,i,o;return C(this,t),n=this,i=F(i=t),r=N(n,$n()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},Xn)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return U(t,Qr),L(t,[{key:"extractMetrics",value:function(t){var r=Object.assign({},this.connectionMetrics),n="";return t.forEach((function(t){var i;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===n)e.networkType=(null!==(i=t.networkType)&&void 0!==i?i:e.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(t.type)&&"succeeded"===t.state)n=t.localCandidateId,e.isFirefox()||(r.roundTripTime=1e3*(t.currentRoundTripTime||t.totalRoundTripTime/t.responsesReceived)),void 0!==t.availableOutgoingBitrate&&(r.availableOutgoingBitrate=t.availableOutgoingBitrate);else if(/codec/i.test(t.type)){var o,a;null!==(o=t.mimeType)&&void 0!==o&&o.includes("audio")?r.audioCodec=t.mimeType.replace("audio/",""):null!==(a=t.mimeType)&&void 0!==a&&a.includes("video")&&(r.videoCodec=t.mimeType.replace("video/",""),r.sdpFmtpLine=t.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},r),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then((function(t){return e.extractMetrics(t)}))}}])}();function ei(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ti(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ti(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ti(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ri=function(){return!!e})()}var ni={uplink:"",downlink:""},ii=function(){function t(e){var r,n,i,o;C(this,t),n=this,i=F(i=t),r=N(n,ri()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pendingTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:ne.New}),Object.defineProperty(r,"exchangeSdpTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"simulcastEnabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.reporter.log.debug("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),r.pc=null;var a=e.direction,s=e.sessionManager;return r.signaling=s.channel.signaling,r.sessionManager=s,r.reporter=s.reporter,r.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}}(),r.subSdpFmtpLines=[],r.direction=a,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(g()),r.startSinglePC().then((function(){r.state=ne.Idle,r.enquenTask.start()})),r}return U(t,c),L(t,[{key:"startSinglePC",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return"uplink"===this.direction?(this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly"})):(this.mcuAudioStream=null,this.mcuAudioTranceiver=this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.addTransceiver("video",{direction:"recvonly"})),e&&function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),d=ke(n.sessions.values());if("downlink"===c){var l=r.media.slice(2),p=d.filter((function(e){return e instanceof hn})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!we.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var v=[];u.forEach((function(e){var t={direction:e.direction},r=l.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&v.push(i))})),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var h=d.filter((function(e){return e instanceof Qn}));u.forEach((function(e){var t={direction:e.direction},r=h.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof Kt){var s=Gt(n).filter((function(e){return e.active}));t.sendEncodings=s.map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:1===s.length}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}}(this),this.exchangeSDP(e)}},{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.signaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"reset",value:function(){this.pendingTask&&(this.pendingTask=null)}},{key:"closePeerConnection",value:function(){this.pc&&(this.reporter.log.debug("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?we.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==ne.Ended&&(this.state=ne.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.reporter.log.debug("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"handleClientReoffer",value:(r=M(se.mark((function e(){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==ne.New){e.next=2;break}return e.abrupt("return",Promise.reject());case 2:return this.reporter.log.debug("connectionId:".concat(this.id,": start client reoffer")),e.prev=3,e.next=6,this.stopSinglePC(!0);case 6:this.removeAllListeners(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(3),this.reporter.log.debug("connectionId:".concat(this.id," client reoffer close failed ").concat(m(e.t0)));case 12:this.closePeerConnection();case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),"failed"===t||"closed"===t?(this.clientFailoverTimer&&v(this.clientFailoverTimer),this.clientFailoverTimer=l((function(){e.state!==ne.New&&e.emit("reoffer")}),1e4)):"connected"===t&&(this.clientFailoverTimer&&(v(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(v(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var t=this.sessionManager.channel.iceConfig,r=t.username,n=t.password,i=t.port,o=t.iceServerList,a={bundlePolicy:"max-bundle",iceTransportPolicy:o.length?"relay":"all",sdpSemantics:"unified-plan"};if(o.length){var s,c=[],u=ei(o);try{for(u.s();!(s=u.n()).done;){var d=s.value;c.push("turn:".concat(d,":").concat(i,"?transport=udp"),"turn:".concat(d,":").concat(i,"?transport=tcp"))}}catch(e){u.e(e)}finally{u.f()}e.isFirefox()&&c.splice(4,2),"relay"===ni[this.direction]&&(ni[this.direction]="all",a.iceTransportPolicy="all"),a.iceServers=[{urls:c,username:r,credential:n}]}return ni[this.direction]=a.iceTransportPolicy,this.reporter.log.debug("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.reporter.log.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=l((function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.exchangeSdpTask||e.emit("reoffer")}),4e3))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new Zn(this),this.monitor.on("metrics",(function(t){e.peerConnectionStats=t})))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then((function(e){r.peerConnectionStats=e})):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&v(this.createPeerConnectionTimer),this.clientFailoverTimer&&v(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"startTask",value:function(){var e=this;return new Promise((function(t,r){e.pendingTask={resolve:t,reject:r},e.exchangeSDP(),l((function(){var t;e.pendingTask&&e.state===ne.Processing&&(null===(t=e.pendingTask)||void 0===t||t.reject(),e.fireEndedEvent())}),15e3)}))}},{key:"exchangeSDP",value:function(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return new Promise((function(a,s){r.exchangeSdpTask={resolve:a,reject:s},r.pc.createOffer().then((function(e){var i,o,a;return t=e,n&&(t.sdp=R.write((i=r.localSDP,o=R.parse(t.sdp),a=o.media,i.media.forEach((function(e){var t=e.mid,r=e.ssrcGroups,n=void 0===r?[]:r,i=e.ssrcs,o=void 0===i?[]:i,s=e.type,c=a.findIndex((function(e){return e.mid==t&&e.type===s}));c>-1&&(a[c]=kn(kn({},a[c]),{},{ssrcGroups:n,ssrcs:o}))})),o))),r.pc.setLocalDescription(t).catch((function(e){throw r.reporter.log.error("connectionId:".concat(r.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){r.reporter.log.debug("connectionId:".concat(r.id," set local sdp success"));var a=function(t,r){var n=r.direction,i=["uplink"===n,we.downlinkForbidHighProfile],o=R.parse(t);if(i.some((function(e){return e}))&&(o=Vn(o,"64")),"downlink"===n&&!we.downlinkForbidHighProfile){var a=[];o.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&a.push(t)})),r.subSdpFmtpLines=a}if(e.isFirefox()&&(o=Bn(o)),"uplink"===n&&e.isFirefox()&&we.simulcast){var s=o.media.find((function(e){return"video"===e.type}));jn(s)}return r.localSDP=o,o}(t.sdp,r);t.sdp=R.write(a),r.offerSDP=a,t.sdp=R.write(a);var s,c={direction:"downlink"!==r.direction?"in":"out",sdpOffer:t.sdp,connectionId:r.id,isFailover:n,optionsJsonStr:JSON.stringify({supportCVO:1})};if(n){var u=R.parse(t.sdp);u.media=u.media.slice(0,2),u.groups=[{mids:"0 1",type:"BUNDLE"}],c.sdpOffer=R.write(u)}return function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.key,a=Je.get(o),s=function(){a&&(v(a),Je.delete(o),a=null)};s();var c=function(){var e=M(se.mark((function e(){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,r--,e.next=4,t();case 4:s(),e.next=14;break;case 7:if(e.prev=7,e.t0=e.catch(0),!(r<=0)){e.next=12;break}throw s(),e.t0;case 12:a=l((function(){c()}),i),Je.set(o,a);case 14:case"end":return e.stop()}}),e,null,[[0,7]])})));return function(){return e.apply(this,arguments)}}();return c()}({key:"createPeerConnection_".concat(r.direction),fn:(s=M(se.mark((function e(){var t;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===(null===(t=r.sessionManager)||void 0===t||null===(t=t.channel)||void 0===t||null===(t=t.client)||void 0===t?void 0:t.connectionState)){e.next=2;break}return e.abrupt("return");case 2:if(c.isFailover||!r.prevId){e.next=7;break}return e.next=5,r.stopSinglePC(!0);case 5:r.id="".concat(r.direction,"_").concat(g()),c.connectionId=r.id;case 7:return r.prevId=r.id,e.abrupt("return",r.signaling.createPeerConnection(c).then((function(e){var t=e.sdpAnswer,a=Gn(t,r,n,ni[r.direction]);r.pc.setRemoteDescription({sdp:R.write(a),type:"answer"}).then((function(){var e;r.reporter.log.debug("connectionId:".concat(r.id," receive answer success")),null===(e=r.exchangeSdpTask)||void 0===e||e.resolve(),r.exchangeSdpTask=void 0})).catch((function(e){var t,n;r.reporter.log.error("connectionId:".concat(r.id," Set remote description failed: ").concat(e)),null===(t=r.exchangeSdpTask)||void 0===t||t.reject(e),r.exchangeSdpTask=void 0,null===(n=r.pendingTask)||void 0===n||n.reject(new i(o.IceConnectionAnswerFail)),r.fireEndedEvent()}))})));case 9:case"end":return e.stop()}}),e)}))),function(){return s.apply(this,arguments)}),times:3,interval:2e3})})).catch((function(e){var t,n;r.reporter.log.error("connectionId:".concat(r.id," Failed to create offer or set SDP. Message: ").concat(e.message)),null===(t=r.pendingTask)||void 0===t||t.reject(new i(o.IceConnectionSetLocalDescFail)),r.fireEndedEvent(),null===(n=r.exchangeSdpTask)||void 0===n||n.reject(e),r.exchangeSdpTask=void 0}))}))}},{key:"reoffer",value:function(){var e=this;return this.state===ne.New?Promise.reject():(this.reporter.log.debug("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=ne.New,this.startSinglePC(!0).then((function(){e.state=ne.Idle,e.enquenTask.start()})))}},{key:"handleHighProfileFallback",value:function(){we.downlinkForbidHighProfile=!0,this.reporter.log.debug("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.reporter.log.debug("connectionId".concat(e.id,": start reoffer for video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}();function oi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ai(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?oi(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):oi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function si(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ci(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ci(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ci(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ui(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ui=function(){return!!e})()}var di=function(){function e(t,r){var n,i,o,a;return C(this,e),i=this,o=F(o=e),n=N(i,ui()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.channel=r,n.client=t,n.reporter=r.reporter,n.streamIdToSessionId=new Map,n.sessions=new Map,n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n.handleRepulish=n.handleRepulish.bind(n),n.handleResubscribe=n.handleResubscribe.bind(n),n}return U(e,c),L(e,[{key:"getOrCreatePeerConnection",value:function(e){var t=this;return"uplink"===e?(this.uplink||(this.uplink=new ii({direction:e,sessionManager:this}),this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){t.uplink=null}))),this.uplink):(this.downlink||(this.downlink=new ii({direction:e,sessionManager:this}),this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){t.downlink=null}))),this.downlink)}},{key:"handleRepulish",value:(p=M(se.mark((function e(){var t,r,n,i,o,a,s;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){e.next=2;break}return e.abrupt("return");case 2:r=ke(this.client.localTracks),n=si(this.sessions.values());try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Qn&&o.state===re.Processing&&(o.clear(),this.sessions.delete(o.id))}catch(e){n.e(e)}finally{n.f()}return this.client.emit("media-reconnect-start",this.client.userId),a=null===(t=this.uplink)||void 0===t?void 0:t.id,e.prev=7,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),e.next=11,null===(s=this.uplink)||void 0===s?void 0:s.handleClientReoffer();case 11:if(this.uplink=null,this.reporter.log.info("".concat(this.client.userId," republish ").concat(r.map((function(e){return e.trackMediaType})).join()," start")),!r.length){e.next=16;break}return e.next=16,this.batchPublish(r);case 16:this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),this.client.emit("media-reconnect-end",this.client.userId),e.next=26;break;case 20:e.prev=20,e.t0=e.catch(7),this.reporter.log.debug("".concat(this.client.userId," republish failed for ").concat(m(e.t0))),this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),this.client.emit("media-reconnect-end",this.client.userId),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 26:case"end":return e.stop()}}),e,this,[[7,20]])}))),function(){return p.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(d=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,d,l,p;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){e.next=2;break}return e.abrupt("return");case 2:r=[],n=si(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof hn&&o.state===re.Processing&&(r.push({stream:o.stream,uid:o.uid,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",a),this.reporter.log.info("resubscribe ".concat(a," start")),e.prev=8,e.next=11,this.batchUnscribe(r);case 11:return e.next=13,this.batchSubscribe(r);case 13:s=e.sent,c=si(s);try{for(c.s();!(u=c.n()).done;)d=u.value,l=d.subscription,p=d.error,l&&!p&&this.handleSubscribeReoffer(l)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=23;break;case 19:e.prev=19,e.t0=e.catch(8),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(m(e.t0))),this.client.emit("media-reconnect-end",a);case 23:case"end":return e.stop()}}),e,this,[[8,19]])}))),function(e){return d.apply(this,arguments)})},{key:"handleResubscribe",value:(u=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f,v,h,y,g=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=g.length>0&&void 0!==g[0]&&g[0],"disconnected"!==this.channel.internalChannel.connectionState){e.next=3;break}return e.abrupt("return");case 3:n=r?"server":"client",i=[],o=si(this.sessions.values());try{for(o.s();!(a=o.n()).done;)(s=a.value)instanceof hn&&s.state===re.Processing&&(i.push({stream:s.stream,uid:s.uid}),this.removeSession(s.id))}catch(e){o.e(e)}finally{o.f()}return c=i.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",c),this.reporter.log.info("resubscribe ".concat(c," start")),u=null===(t=this.downlink)||void 0===t?void 0:t.id,e.prev=11,this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferStart")),e.next=15,null===(d=this.downlink)||void 0===d?void 0:d.handleClientReoffer();case 15:if(this.downlink=null,!i.length){e.next=22;break}return e.next=19,this.batchSubscribe(i);case 19:l=e.sent,p=si(l);try{for(p.s();!(f=p.n()).done;)v=f.value,h=v.subscription,y=v.error,h&&!y&&this.handleSubscribeReoffer(h)}catch(e){p.e(e)}finally{p.f()}case 22:this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferSuccess")),this.reporter.log.debug("".concat(this.client.userId," resubscribe ").concat(c," success")),this.client.emit("media-reconnect-end",c),e.next=33;break;case 27:e.prev=27,e.t0=e.catch(11),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(m(e.t0))),this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferFailed")),this.client.emit("media-reconnect-end",c),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 33:case"end":return e.stop()}}),e,this,[[11,27]])}))),function(){return u.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return this.sessions.get(this.streamIdToSessionId.get(e))}},{key:"handleSubscribeReoffer",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===z.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.reporter.log.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.channel.remoteAudioTrack){var c,u;if(we.audioSFU)null===(c=(u=this.channel.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.channel.remoteAudioTrack.replaceTrack(o)}else{var d=this.channel.userManager.remoteUsers.find((function(e){return e.userId===r}));a&&null!=d&&d.auxiliaryTrack&&i?d.auxiliaryTrack.replaceTrack(a):a&&null!=d&&d.videoTrack&&!i&&d.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.reporter.log.debug("serverFailover ".concat(JSON.stringify(e)));var r,n=e.actions,i=si(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,d=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then((function(){t.reporter.log.info("".concat(u," republish ").concat(d.map((function(e){return e.trackMediaType})).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)})).catch((function(e){t.reporter.log.debug("".concat(t.client.userId," republish failed for ").concat(m(e))),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.channel.signaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")}))}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?X.BAD:e>30||t>450?X.POOR:e>20||t>300?X.NORMAL:e>10||t>200?X.GOOD:e>=0||t>=0?X.GREAT:X.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(s=M(se.mark((function e(){var t,r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=ke(this.sessions.values())).length){e.next=4;break}return this.emit("network-quality",X.UNKNOWN,X.UNKNOWN),e.abrupt("return");case 4:if(0!==t.filter((function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)})).length){e.next=8;break}return this.emit("network-quality",X.DISCONNECTED,X.DISCONNECTED),e.abrupt("return");case 8:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then((function(e){var t=wt(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,d=0,l=0,p=0;if(n){var f=n.camera,v=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,l=Math.max(l,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,l=Math.max(l,v.rtt||0))}for(var h in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,l=Math.max(l,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,d+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[h],y=m.camera,g=m.auxiliary;y&&(u+=y.receivePacketsLost,d+=y.receivePackets,p=Math.max(p,y.rtt||0)),g&&(u+=g.receivePacketsLost,d+=g.receivePackets,p=Math.max(p,g.rtt||0))}var b=-1,S=-1,k={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:d};if(s){var P,w,O=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(O<0&&(O=c),k.totalUplinkPacketsSentForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalUplinkPacketsSentForLost)||0,0!==O){var T;k.totalUplinkPacketsSentForLost=s;var E=s-((null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0);E<0&&(E=s),b=O/E}}if(d){var I,R,A,_,M=u-((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0);M<0&&(M=u),k.totalDownlinkPacketsRecvForLost=(null===(R=r.lastChannelNetworkQuality)||void 0===R?void 0:R.totalDownlinkPacketsRecvForLost)||0,null===(A=r.lastChannelNetworkQuality)||void 0===A||A.totalDownlinkPacketsRecvForLost,M&&(u!==((null===(_=r.lastChannelNetworkQuality)||void 0===_?void 0:_.totalDownlinkPacketsLost)||0)&&(k.totalDownlinkPacketsRecvForLost=d),S=M/d)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),l),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=k}));case 9:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e))}},{key:"batchPublish",value:function(e,t){var r=this,n=Date.now();return function(e){var t,r=e.tracks,n=e.connection,i=e.labels,o=r.map((function(t){return{publication:new Qn(Hn(Hn({},e),{},{tracks:[t]})),track:t}})),a=new Promise((function(e,a){t=function(){var t=M(se.mark((function t(){var s,c,u,d;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Kn(r,n,i);case 2:return s=t.sent,c=s.media,u=s.enableSimulcast,d={connectionId:n.id,media:c,simulcast:u,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.signaling.batchPublish(d).then(function(){var t=M(se.mark((function t(r){var n,i,a,s,c;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=4;break}return o.forEach((function(e){e.error=Ie(e.track,i)})),t.abrupt("return",e(o));case 4:a=Yn(n),t.prev=5,c=se.mark((function e(){var t,r,n,i,a,c,u;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,a=o.findIndex((function(e){return e.track.getTrackId()===n.id})),c=o[a]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(o[a].error=Ie(o[a].track,i));case 4:case"end":return e.stop()}}),e)})),a.s();case 8:if((s=a.n()).done){t.next=12;break}return t.delegateYield(c(),"t0",10);case 10:t.next=8;break;case 12:t.next=17;break;case 14:t.prev=14,t.t1=t.catch(5),a.e(t.t1);case 17:return t.prev=17,a.f(),t.finish(17);case 20:e(o);case 21:case"end":return t.stop()}}),t,null,[[5,14,17,20]])})));return function(e){return t.apply(this,arguments)}}()).catch((function(e){a(e)})));case 7:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),a}({uid:this.client.userId,tracks:e,connection:this.getOrCreatePeerConnection("uplink"),labels:t}).then((function(e){var t,i=si(e);try{var o=function(){var e=t.value,i=e.error,o=e.publication,a=e.track;i?r.reporter.trace.publish(!1,a,"",Date.now()-n):(r.addSession(a.getTrackId(),o),r.reporter.trace.publish(!0,a,o.id,Date.now()-n),r.reporter.trace.publish(!1,a,o.id,Date.now()-n),o.on("ended",(function(){r.removeSession(o.id)})))};for(i.s();!(t=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}))}},{key:"batchUnPublish",value:function(e){var t=this;return e.length?zn(e,{connection:this.getOrCreatePeerConnection("uplink")}).then((function(){var r,n=si(e);try{for(n.s();!(r=n.n()).done;){var i,o,a,s=r.value;t.streamIdToSessionId.delete(null===(i=s.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=(a=i).getTrackId)||void 0===o?void 0:o.call(a)),t.removeSession(s.id)}}catch(e){n.e(e)}finally{n.f()}})):Promise.resolve()}},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,i=function(e){return gn(e,{connection:t.getOrCreatePeerConnection("downlink")}).then(function(){var r=M(se.mark((function r(o){var a,s,c,u;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:for(a=new Map,s=[],c=0;c<o.length;c++)"RoomBusy"===(null===(u=o[c].error)||void 0===u?void 0:u.message)&&(s.push(e[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){r.next=12;break}return n++,r.next=7,Qe(1);case 7:if("connected"!==t.client.connectionState){r.next=12;break}return r.next=10,i(s);case 10:r.sent.forEach((function(e,t){var r=a.get(t);o[r]=e}));case 12:return r.abrupt("return",o);case 13:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}())};return i(e).then((function(e){var n,i=si(e);try{var o=function(){var e=n.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;o&&(t.reporter.trace.subscribe({init:!0,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:a,resolutionInfo:u}),"mcu"===o.uid&&t.reporter.trace.subscribe({init:!1,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:o.id,resolutionInfo:u}),t.addSession(s.id,o),o.on("ended",(function(){t.removeSession(a)}))),i&&t.reporter.trace.subscribe({init:!1,capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:"",resolutionInfo:u})};for(i.s();!(n=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return e}))}},{key:"batchUnscribe",value:(a=M(se.mark((function e(t){var r,n,i,o=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,a=e.stream,s=e.session;r[t]={},o?r[t].error=o:(i[null==a?void 0:a.id]=t,n.push(s))})),e.abrupt("return",bn(n,{connection:this.getOrCreatePeerConnection("downlink")}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];o.removeSession(i.id)}return r})));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach((function(e){r.removeSession(e.id)})),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(v(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.channel.signaling.off("media-message",this.handleMediaMessage),this.channel.signaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:function(){this.startNetworkQualityTimer(),this.uplink=this.getOrCreatePeerConnection("uplink"),this.downlink=this.getOrCreatePeerConnection("downlink"),this.channel.signaling.on("media-message",this.handleMediaMessage),this.channel.signaling.on("serverFailover",this.handleServerFailover)}},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=l((function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",X.DISCONNECTED,X.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",X.BAD,X.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",X.UNKNOWN,X.UNKNOWN)}),2e3,"interval")}},{key:"getLocalAudioStats",value:(o=M(se.mark((function e(){var t,r,n,i=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=ke(this.sessions.values()).filter((function(e){var t,r;return e instanceof Qn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)})},{key:"getLocalVideoStats",value:(i=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f,v,h=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=h.length>0&&void 0!==h[0]?h[0]:"network",i=ke(this.sessions.values()).filter((function(e){var t;return e instanceof Qn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType})),e.next=4,Promise.all(i.map((function(e){return e.getMetrics(n)})));case 4:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter((function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")})).map((function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex((function(e){return e.includes("profile-level-id")}));return r[n].split("=")[1]})))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find((function(e){return"video"===e.type})),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find((function(e){return"video"===e.type})),c={uplinkProfile:ke(new Set(o(a))),downlinkProfile:ke(new Set(o(s)))},u=si(i),e.prev=9,u.s();case 11:if((d=u.n()).done){e.next=21;break}if(l=d.value,p=l.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=l.tracks,v=f[0].source===z.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return i.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(n=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=ke(this.sessions.values()).filter((function(e){var t;return e instanceof hn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video})),e.next=4,Promise.all(r.map((function(e){return e.getMetrics(t)})));case 4:n={},i=si(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,d=s.stream,l=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=d.media.video)||void 0===a?void 0:a.source)===z.SCREENCAST?"auxiliary":"camera",n[u]=ai(ai({},n[u]||{}),{},ce({},p,l));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return n.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(r=M(se.mark((function e(){var t,r,n,i=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=ke(this.sessions.values()).filter((function(e){var t;return e instanceof hn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"handleMediaMessage",value:(t=M(se.mark((function e(t){var r,n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.reporter.log.debug("remote feedback: ".concat(t.payload)),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=4;break}return e.abrupt("return");case 4:n=ke(this.sessions.values()).filter((function(e){return e instanceof Qn&&e.state===re.Processing&&e.tracks[0].source===z.CAMERA})),i=si(n),e.prev=6,a=se.mark((function e(){var t,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter((function(e){return e.mid==t.transceiver.mid}))).length&&t.applyOptions(n);case 3:case"end":return e.stop()}}),e)})),i.s();case 9:if((o=i.n()).done){e.next=13;break}return e.delegateYield(a(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),i.e(e.t1);case 18:return e.prev=18,i.f(),e.finish(18);case 21:case"end":return e.stop()}}),e,this,[[6,15,18,21]])}))),function(e){return t.apply(this,arguments)})}]);var t,r,n,i,o,a,s,u,d,p}();function li(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return pi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?pi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function pi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function fi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(fi=function(){return!!e})()}var vi={name:"name"},hi=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,fi()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=t,r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return U(e,c),L(e,[{key:"joinedIds",get:function(){var e=this.channel.userManager.currentPid,t=new Set;return this.groups.forEach((function(r){var n=r.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.channel.userManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.channel.signaling.on("group-list",this.handleGroupListEvents),this.channel.signaling.on("group",this.handleGroupEvents),this.channel.signaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.channel.signaling.off("group",this.handleGroupEvents),this.channel.signaling.off("group-list",this.handleGroupListEvents),this.channel.signaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,a=e.userData;if(this.joinedIds.has(n))throw new i(o.InvaildArgument,"you were in group already");return this.channel.signaling.joinGroup({groupId:n,userData:a,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new i(o.InvaildArgument,"you are not in the group");return this.channel.signaling.leaveGroup({groupId:t,reasonCode:cr.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new i(o.InvaildArgument,"group not existed");return this.channel.signaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find((function(t){return t.pid===e.pid}))&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex((function(t){return t.pid===e.pid}));i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.channel.signaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.channel.signaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.channel.signaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.channel.reporter.log.debug("groupList ".concat(JSON.stringify(e))),r!==this.listVer+1&&!t||n!==cr.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===cr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===cr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.channel.reporter.log.debug("group ".concat(JSON.stringify(e)));var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==cr.OptType.OPT_TYPE_ADD||u){if(s===cr.OptType.OPT_TYPE_REMOVE&&u){var d,l=null==u||null===(d=u.audioInfo)||void 0===d||null===(d=d.audio)||void 0===d?void 0:d.id;this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),l)}else if(s===cr.OptType.OPT_TYPE_UPDATE){var p=c.updateAction,f=c.participants;if(u&&(u.ver+1===o||r)){if(p===cr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var v,h=u.participants.map((function(e){return e.pid})),m=li(f);try{for(m.s();!(v=m.n()).done;){var y=v.value;h.includes(y.pid)||(u.participants.push(y),this.emit("group","user-join",i,{userId:y.uid,userData:y.userData}))}}catch(e){m.e(e)}finally{m.f()}}else if(p===cr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=f.map((function(e){return e.pid})),b=ke(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),b.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(p===cr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.channel.reporter.log.debug("group ".concat(i," audioStream lost"));else if(p===cr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.channel.reporter.log.debug("group ".concat(i," audioStream recover"));else if(p===cr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach((function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach((function(t){t.key===e.key&&(t.value=e.value,r=!1)})),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(vi[e.key]),value:e.value})}));else if(p===cr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var S,k=c.properties.map((function(e){return e.key}));u.properties=null===(S=u.properties)||void 0===S?void 0:S.filter((function(e){var t=e.key;return!k.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(vi[e.key])})}))}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.channel.signaling.syncData({type:cr.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],d=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),l=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==d[e.key]})),v=c.filter((function(e){return!d.has(e.key)})),h=a.filter((function(e){return!l.includes(e.pid)})),m=u.filter((function(e){return!p.includes(e.pid)}));h.length&&t.handleGroupEvents({id:e,type:cr.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:cr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:h}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:cr.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:cr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:cr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:cr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:cr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:cr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:cr.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.channel.signaling.syncDataByIds({type:cr.DataType.DATA_TYPE_GROUP,ids:e.map((function(e){return{id:e}}))}).then((function(e){e.fullSync.groupData.groupInfos.forEach((function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)}))}))}},{key:"syncGroupList",value:function(){var e=this;this.channel.signaling.syncData({type:cr.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then((function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter((function(t){return!e.groupIds.has(t)})),s=ke(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:cr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:cr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}();function mi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(mi=function(){return!!e})()}var yi=function(){function e(t,r){var n,i,o,a;C(this,e),i=this,o=F(o=e),n=N(i,mi()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=t.user;return n.userId=s,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.channel=r,n.joinedTime=Date.now(),n.update(t),n}return U(e,c),L(e,[{key:"relatedStreams",get:function(){var e=this;return ke(this.channel.streamManager.streams.values()).filter((function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id}))}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some((function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===z.SCREENCAST}))}},{key:"hasVideo",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===z.CAMERA}))}},{key:"hasAudio",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===K.MIC}))}},{key:"audioMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===K.MIC}))}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===z.SCREENCAST}))}},{key:"videoMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===z.CAMERA}))}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==P.Web&&e){var r=e.split("");r[oe.UPLINK]=Ye(r[oe.UPLINK]),r[oe.DOWNLINK]=Ye(r[oe.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[ve])&&(this.properties[ve]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[ve])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=Re(e.mediaStream,"video",this.userId,r);return r||i.once("first-frame-decoded",(function(){e.handleVideoFirstFrame()})),t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}();function gi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return bi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?bi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function bi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Si(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Si=function(){return!!e})()}var ki=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,Si()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.users=new Map,r.channel=t,r.reporter=t.reporter,r.handleEvent=r.handleEvent.bind(r),r}return U(e,c),L(e,[{key:"remoteUsers",get:function(){var e=this;return w(ke(this.users.values()).sort((function(e,t){return e.joinedTime-t.joinedTime})),"userId").filter((function(t){return t.userId&&t.id!==e.currentPid}))}},{key:"init",value:function(e,t){var r,n=gi(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new yi(i,this.channel);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentPid=t,this.channel.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentPid="",this.currentUid="",this.users.clear(),this.channel.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t){if(this.reporter.log.debug("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var r=new yi(t,this.channel);this.users.set(t.user,r),this.emit("user","join",r)}else if("leave"===e){var n=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",n)}else if("update"===e){var i=this.users.get(t.user);null==i||i.update(t)}}},{key:"setParticipantProperties",value:function(e){return this.channel.signaling.setParticipantProperties({participantId:this.currentPid,roomId:this.channel.roomId,propertiesJsonStr:JSON.stringify(ce({},ve,e))})}}])}();function Pi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return wi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?wi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function wi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Oi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ti(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Oi(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Oi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ei(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ei=function(){return!!e})()}var Ii=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,Ei()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var a=t.signaling,s=t.reporter;return r.signaling=a,r.reporter=s,r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.sync=r.sync.bind(r),r}return U(e,c),L(e,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.signaling.off("stream",this.handleEvent),this.signaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find((function(e){return"admin"===e.info.owner&&"mixed"===e.type}));null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map((function(e){return[e.id,e]}))),this.totalVer=t,this.signaling.on("stream",this.handleEvent),this.signaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=ke(this.streams.values()).find((function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s}));c&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===O.SCREENCAST;((null==o?void 0:o.source)===O.CAMERA||u)&&this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u}),(null==a?void 0:a.source)!==K.MIC&&(null==a?void 0:a.source)!==K.MIXED||this.emit("stream","add",{id:r,owner:n,mediaType:"audio"})}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===O.SCREENCAST;((null==i?void 0:i.source)===O.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==K.MIC&&(null==o?void 0:o.source)!==K.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return ke(this.streams.values()).find((function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e}))}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties"]}[i];c.length&&!c.includes(a.field)||this.reporter.log.debug("streamEvent ".concat(JSON.stringify(e)));var u=this.totalVer;if(s===u+1||s==pe||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var d=a.field,l=a.streamStatus,p=a.activeStream,f=a.extraValue,v=a.streamVer,h=a.propertiesJsonStr,m=this.streams.get(n);if(m){v!==pe&&(m.version=v);var y=m.media,g=y.audio,b=y.video,S=m.info.owner;if("audio.status"===d||"video.status"===d){var k;"audio.status"===d?(k="audio",g.status=l):"video.status"===d&&(k="video",b.status=l),this.reporter.trace.streamsEvent(n,"".concat(k," ").concat(l));var P="active"===l?"unmute":"mute";this.emit("stream","update",{owner:S,id:n,updateStatus:"".concat(P,"-").concat(k)})}else if("activeInput"===d){var w=[p].concat(f||[]).map((function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner})).filter((function(e){return!!e}));this.reporter.trace.streamsEvent(JSON.stringify(w),d),this.emit("stream","volumeActive",{owners:w})}else if("properties"==d){var T,E=JSON.parse(h);m.info.attributesJsonStr=JSON.stringify(Ti(Ti({},JSON.parse(m.info.attributesJsonStr)),E));var I=(null===(T=m.media)||void 0===T||null===(T=T.video)||void 0===T?void 0:T.source)===O.SCREENCAST;this.emit("stream","update",{owner:S,id:n,properties:E,auxiliary:I})}}}t||s<=this.totalVer&&s!==pe||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&this.sync())}},{key:"sync",value:(t=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f,v,h=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=4,this.signaling.getStreamsVer({});case 4:n=e.sent,i=n.streamVersions,o=n.totalVer,a=ke(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=Pi(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,d=u.streamId,l=u.streamVer,!d.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(d))?p&&p.version!==l&&t.push(d):(r.push(d),t.push(d));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),v=a.filter((function(e){return!f.includes(e)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=33;break}return e.abrupt("return");case 33:this.signaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=Pi(h.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,d=Pi(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;h.streams.has(l.id)?h.streams.set(l.id,l.stream):a.set(l.id,l.stream)}}catch(e){d.e(e)}finally{d.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var m=p[f];v.includes(m.id)?h.handleEvent({status:"remove",streamId:m.id,stream:m,totalVer:i},!0):r.includes(m.id)&&h.handleEvent({status:"add",streamId:m.id,stream:m,totalVer:i},!0)}a.clear(),h.totalVer=i}));case 34:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return t.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var t}();function Ri(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Ai(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ai(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Ai(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function _i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Mi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_i(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_i(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ci(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ci=function(){return!!e})()}var Di=function(){function e(t,r){var n,a,s,c;return C(this,e),a=this,s=F(s=e),n=N(a,Ci()?Reflect.construct(s,[],F(a).constructor):s.apply(a,c)),Object.defineProperty(n,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"groupManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"remoteAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"internalChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"roomId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"defaultVideoStreamType",{enumerable:!0,configurable:!0,writable:!0,value:"high"}),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscribedAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"micMixedGroups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"iceConfig",{enumerable:!0,configurable:!0,writable:!0,value:{level:0,iceServerList:[]}}),Object.defineProperty(n,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,a=e.action,s=e.uid,c=e.auxiliary,u=n.getStream(e),d=n.userManager.users.get(s),l=n.groups.some((function(e){return e.joined})),p="mcu"===s?n.remoteAudioTrack:c?null==d?void 0:d.auxiliaryTrack:null==d?void 0:d.videoTrack;return"mcu"===s&&"video"===r||s&&"mcu"!==s&&"audio"===r?t=new i(o.InvaildArgument,"only support ".concat(a," mcu audio")):"mcu"===s&&l&&"subscribe"===a?t=new i(o.SubscribeInvaild,"cannot subscribe mcu while in group"):"subscribe"===a&&p?t=new i(o.SubscribeInvaild,"duplicated subscription"):u&&("unsubscribe"!==a||p)||(n.reporter.log.warn("".concat(s," videoTrack not existed")),t=new i(o.SubscribeStreamNotExisted)),{uid:s,user:d,error:t,stream:u,session:"unsubscribe"===a?n.sessionManager.getSessionByStreamId(u.id):null,resolutionInfo:"video"===r?Mt(n.defaultVideoStreamType,Te(u)):null}}}),Object.defineProperty(n,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,o=t.streams,a=t.streamsVer,s=t.groupList,c=t.groupListVer;n.streamManager.init(o,a),we.grouptalk&&n.groupManager.init(s,c),n.userManager.init(i,r),n.streamManager.on("stream",n.handleStreamEvent),n.userManager.on("user",n.handleUserEvent),n.groupManager.on("group",n.handleGroupEvent)}}),n.reporter=r,n.internalChannel=new A({reporter:r,gslb:we.gslb[0],sdkVersion:le}),n.signaling=new Wr(n.internalChannel),n.client=t,n.micMixedGroups=new Set,n.groupManager=new hi(n),n.userManager=new ki(n),n.streamManager=new Ii(n),n.sessionManager=new di(t,n),n.subscribedAudioStream="",n.handleStreamEvent=n.handleStreamEvent.bind(n),n.handleUserEvent=n.handleUserEvent.bind(n),n.handleGroupEvent=n.handleGroupEvent.bind(n),n}return U(e,c),L(e,[{key:"localTracks",get:function(){return ke(this.sessionManager.sessions.values()).filter((function(e){return e.state===re.Processing&&e instanceof Qn})).map((function(e){return e.tracks[0]}))}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map((function(t){return Mi(Mi({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})}))}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=this.internalChannel.userManager.participants,d=u.get(n),l=this.userManager.users.get(null==d?void 0:d.user),p=n===this.userManager.currentPid;if("add"===e&&!p&&l)this.client.emit("user-published",l,i,o);else if("remove"===e&&l&&!p)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&l.auxiliaryTrack&&(l.auxiliaryTrack.stop(),l.auxiliaryTrack=null),!o&&l.videoTrack&&(l.videoTrack.stop(),l.videoTrack=null)),this.client.emit("user-unpublished",l,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==l?void 0:l.userId)||this.userManager.currentUid,s);else if(null!=(null==c?void 0:c.mirror)){var f=o?l.auxiliaryTrack:l.videoTrack;null==f||f.setSourceMirror(c.mirror)}}else if("volumeActive"===e){var v=a.map((function(e){return u.get(e)})).map((function(e){return null==e?void 0:e.user})).filter((function(e){return!!e}));this.client.emit("volume-indicator",v)}}},{key:"handleGroupEvent",value:function(e,t,r){if("add"===e)this.client.emit("group-add",t);else if("remove"===e)this.micMixedGroups.delete(t.id),r===this.subscribedAudioStream&&(this.remoteAudioTrack.stop(),this.remoteAudioTrack=null,this.updateSubscribedAudioStream(!1,r)),this.client.emit("group-remove",t);else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var n=r.key,i=r.value;this.client.emit("group-info-updated",t,n,i)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e&&this.client.emit("user-left",t)}},{key:"getStream",value:function(e){var t,r=e.groupId,n=e.uid,i=e.auxiliary;if(r){var o,a=this.groupManager.groups.get(r);return null==a||null===(o=a.audioInfo)||void 0===o?void 0:o.audio}var s="mcu"===n?ke(this.streamManager.streams.values()):null===(t=this.userManager.users.get(n))||void 0===t?void 0:t.relatedStreams;return"mcu"===n?s.find((function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r})):s.find((function(e){var t=e.media.video;return(null==t?void 0:t.source)===(i?O.SCREENCAST:O.CAMERA)}))}},{key:"join",value:(s=M(se.mark((function e(t){var r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.signaling.join(t,we.gslb[0]).then((function(e){var t,n,i,o=e.joinResponse,a=e.iceConfig;return r.roomId=o.room.id,t=o.room.ssrcMask,n=o.room.ssrcClientSequence,i=Math.log2(t+1),n>2147483647>>i||(En=t,Tn=(n<<i|2147483648)>>>0),r.reporter.updateCommonInfo({roomId:r.roomId,participantId:o.id}),a&&a.uis&&r.setIceConfig(a.uis),r.sessionManager.start(),r.handleJoinResponse(o),o})));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter((function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)})),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.userManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stop(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.userManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.signaling.leave()}},{key:"publish",value:(a=M(se.mark((function e(t){var r,n,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some((function(e){return e.joined}))?o.push.apply(o,ke(ke(r).map((function(e){var t;return null===(t=n.groups.get(e))||void 0===t||null===(t=t.audioInfo)||void 0===t?void 0:t.label})).filter((function(e){return!!e})))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"unpublish",value:function(e){var t=this,r=new Set(e.map((function(e){return e.getTrackId()}))),n=ke(this.sessionManager.sessions.values()).filter((function(e){var t;return e instanceof Qn&&r.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())}));return n.forEach((function(e){t.reporter.trace.unpublish(e.id)})),this.sessionManager.batchUnPublish(n)}},{key:"getRemoteTrack",value:function(e,t){var r=this;if(!t.mediaStream)return null;var n=this.userManager.users.get(e.uid);if("audio"===e.mediaType){var i=this.remoteAudioTrack;return this.remoteAudioTrack=Re(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",(function(){r.remoteAudioTrack.emit("first-frame-decoded")})),this.remoteAudioTrack}return n.getRemoteVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(n=M(se.mark((function e(t){var r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.sessionManager.batchSubscribe(t.map(this.handleSubscribeParam)).then(function(){var e=M(se.mark((function e(n){var i;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=[],t.forEach((function(e,t){var o=e.auxiliary,a=e.uid,s=n[t],c=s.error,u=s.subscription;i.push({uid:a,auxiliary:o,error:c,track:r.getRemoteTrack(e,u)})})),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){var t,r=this,n=[],i=Ri(e);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.handleSubscribeParam(Mi(Mi({},o),{},{action:"unsubscribe"})),s=a.session,c=a.stream,u=a.user,d=a.uid;this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:d}),c&&n.push(Mi({stream:c,user:u,session:s},o))}}catch(e){i.e(e)}finally{i.f()}return n.length?this.sessionManager.batchUnscribe(n).then((function(e){for(var t=0,i=n;t<i.length;t++){var o,a=i[t],s=a.mediaType,c=a.user,u=a.auxiliary;if("audio"===s)r.updateSubscribedAudioStream(!1,""),null===(o=r.remoteAudioTrack)||void 0===o||o.stop(),r.remoteAudioTrack=null;else if(u){var d;null===(d=c.auxiliaryTrack)||void 0===d||d.stop(),c.auxiliaryTrack=null}else{var l;null===(l=c.videoTrack)||void 0===l||l.stop(),c.videoTrack=null}}return e})):Promise.resolve()}},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new i(o.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream)throw new i(o.InvaildState,"you were subscribed group or channel already");return this.sessionManager.batchSubscribe([{stream:r,uid:e}]).then((function(n){return t.updateSubscribedAudioStream(!0,r.id),t.remoteAudioTrack=Re(n[0].subscription.mediaStream,"audio",e,t.remoteAudioTrack),t.remoteAudioTrack}))}},{key:"unsubscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new i(o.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream!==r.id)throw new i(o.InvaildState,"you were not subscribed the group");return this.sessionManager.batchUnscribe([{stream:r,session:this.sessionManager.getSessionByStreamId(r.id)}]).then((function(){r.id===t.subscribedAudioStream&&(t.updateSubscribedAudioStream(!1,""),t.remoteAudioTrack.stop(),t.remoteAudioTrack=null)}))}},{key:"setRemoteStreamType",value:function(e,t,r){this.reporter.log.info("setRemoteStreamType",e,t,r);var n=this.getStream({uid:e,mediaType:"video",auxiliary:r}),i=this.sessionManager.getSessionByStreamId(n.id),o=Mt(t,Te(n));return i.applyOptions(o)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then((function(e){var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)}))}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then((function(){t.micMixedGroups.delete(r)}))}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then((function(){t.micMixedGroups.delete(e)}))}},{key:"mixGroupAudio",value:function(e,t,r){return this.signaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(r=M(se.mark((function e(t,r){var n,i,o,a=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=!(a.length>2&&void 0!==a[2])||a[2],i=[],null!=r&&i.push(this.groupManager.groups.get(r).audioInfo.label),!this.localTracks.includes(t)){e.next=18;break}if(o=this.streamManager.getStreamByTrackId(t.getTrackId()),null==r){e.next=14;break}return e.next=8,this.mixGroupAudio(o.id,i[0],"mix");case 8:if(this.micMixedGroups.add(r),!n){e.next=12;break}return e.next=12,this.mixGroupAudio(o.id,"common","unmix");case 12:e.next=16;break;case 14:return e.next=16,this.mixGroupAudio(o.id,"common","mix");case 16:e.next=22;break;case 18:return n||i.push("common"),e.next=21,this.sessionManager.batchPublish([t],i);case 21:this.micMixedGroups.add(r);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"unpublishFromGroup",value:(t=M(se.mark((function e(t,r){var n,i,o,a=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]&&a[2],i=this.groupManager.groups.get(r).audioInfo.label,o=this.streamManager.getStreamByTrackId(t.getTrackId()),e.next=5,this.mixGroupAudio(o.id,i,"unmix");case 5:if(this.micMixedGroups.delete(r),!n){e.next=9;break}return e.next=9,this.mixGroupAudio(o.id,"common","mix");case 9:case"end":return e.stop()}}),e,this)}))),function(e,r){return t.apply(this,arguments)})}]);var t,r,n,a,s}();function xi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(xi=function(){return!!e})()}var ji={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},Li=function(){function e(t){var r,n,i,o,a;return C(this,e),n=this,i=F(i=e),r=N(n,xi()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"audioDeviceBufferReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioDeviceBufferInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"makeReport",{enumerable:!0,configurable:!0,writable:!0,value:(a=M(se.mark((function e(){var t,n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,r.client.getLocalAudioStats();case 2:return t=e.sent,n=t.audioLevel,e.next=6,r.client.getRemoteAudioStats();case 6:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:We(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 11:case"end":return e.stop()}}),e)}))),function(){return a.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},ji),r.client=t,r}return U(e,Qr),L(e)}();function Ni(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Fi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ni(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ni(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Gi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Ui(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ui(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Ui(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Vi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Vi=function(){return!!e})()}var Bi=function(){function t(){var e,r,n,i;return C(this,t),r=this,n=F(n=t),e=N(r,Vi()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(e,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"id",{enumerable:!0,configurable:!0,writable:!0,value:g(6)}),Object.defineProperty(e,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:E(e.id)}),Object.defineProperty(e,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(e,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),e.channel=new Di(e,e.reporter),e.handleVisibilitychange=e.handleVisibilitychange.bind(e),e.handleNetworkQuality=e.handleNetworkQuality.bind(e),e.handleConnectionChangeEvent=e.handleConnectionChangeEvent.bind(e),e.handlePageUnload=e.handlePageUnload.bind(e),e.init(),e}return U(t,c),L(t,[{key:"remoteUsers",get:function(){return this.channel.userManager.remoteUsers}},{key:"groups",get:function(){return this.channel.groups}},{key:"userId",get:function(){var e;return(null===(e=this.channel.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.channel.localTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.channel.internalChannel)||void 0===e?void 0:e.connectionState)||"disconnected"}},{key:"init",value:function(){this.syncStatTimer&&(v(this.syncStatTimer,"interval"),this.syncStatTimer=null),this.currentClientState="",this.channelName="",this.channel.clear(),this.removeEventListeners(),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.clientStatSync=[0,0,0,0,0,0]}},{key:"join",value:function(e){var t=this;return this.addEventListeners(),this.channel.join(e).then((function(r){var n;return t.channelName=e.channel,t.monitor=new Li(t),t.monitor.on("audio-device-buffer",(function(e){t.reporter.metric.audioDeviceBuffer(e)})),t.syncStatTimer=l((function(){t.sendClientStatToRemote()}),2e3,"interval"),{remoteUsers:t.remoteUsers,timeLeft:null===(n=r.room)||void 0===n?void 0:n.timeLeft}})).catch((function(e){throw t.init(),e}))}},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.reporter.log.info("setRemoteDefaultVideoStreamType",e),this.channel.defaultVideoStreamType=e}},{key:"leave",value:function(){this.reporter.log.info("leave"),this.channel.leave(),this.init()}},{key:"publish",value:function(e){var t=this;if(this.reporter.log.info("publish",(Array.isArray(e)?e:[e]).map((function(e){return e.trackMediaType}))),"connected"!==this.connectionState)return Promise.reject(new i(o.PublishNotJoinChannel));var r,n=(Array.isArray(e)?e:[e]).filter((function(e){return e instanceof Qt&&!t.localTracks.includes(e)})),a=n.concat(this.localTracks),s=ce(ce(ce(ce({},z.CAMERA,0),z.SCREENCAST,0),K.MIC,0),K.MIXED,0),c=Gi(a);try{for(c.s();!(r=c.n()).done;){var u=r.value;if(s[u.source]++,s[u.source]>=2)throw new i(o.QuotaLimitExceed,"".concat(u.source," published already"))}}catch(e){c.e(e)}finally{c.f()}if(!n.length)throw new i(o.PublishNoStream);return this.channel.publish(n)}},{key:"unpublish",value:function(e){var t=Array.isArray(e)?e:[e];return e||(t=this.localTracks),this.reporter.log.info("unpublish",t.map((function(e){return e.trackMediaType}))),this.channel.unpublish(t)}},{key:"subscribe",value:(n=M(se.mark((function e(t,r,n){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.reporter.log.info("subscribe",t,r),"connected"===this.connectionState){e.next=3;break}throw new i(o.SubscribeNotJoinChannel);case 3:return e.abrupt("return",this.channel.batchSubscribe([{uid:t,mediaType:r,action:"subscribe",auxiliary:n}]).then((function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n})));case 4:case"end":return e.stop()}}),e,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){if(Array.isArray(e)&&e.length){if(this.reporter.log.info("batchSubscribe",e),"connected"!==this.connectionState)throw new i(o.SubscribeNotJoinChannel);return this.channel.batchSubscribe(e.map((function(e){return Fi(Fi({},e),{},{action:"subscribe"})})))}}},{key:"unsubscribe",value:(r=M(se.mark((function e(t,r,n){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("unsubscribe",t,r),e.abrupt("return",this.channel.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r,action:"unsubscribe"}]).then((function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){if(Array.isArray(e)&&e.length)return this.reporter.log.info("batchUnsubscribe",e),"connected"!==this.connectionState?Promise.reject(new i(o.SubscribeNotJoinChannel)):this.channel.batchUnsubscribe(e.map((function(e){return Fi(Fi({},e),{},{action:"unsubscribe"})})))}},{key:"getLocalAudioStats",value:function(){return this.channel.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.channel.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:function(e,t,r){var n=this;this.reporter.log.info("setRemoteVideoStreamType",e,t);var i=this.remoteUsers.find((function(t){return t.userId===e}));return null!=i&&i.relatedStreams?this.channel.setRemoteStreamType(e,t,r).then((function(){n.emit("stream-type-changed",e,t,r)})):(this.reporter.log.warn("".concat(e," videoTrack not existed")),Promise.reject("viedoTrack doesnt exiested"))}},{key:"getRemoteVideoStats",value:function(){return this.channel.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.channel.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach((function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[ve])||void 0===r?void 0:r[oe.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[ve])||void 0===n?void 0:n[oe.UPLINK])||0)}})),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.reporter.log.debug("connectionStateChange from ".concat(t," to ").concat(e," ").concat(r||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var e=this,t=this.clientStatSync.join("");if(t!==this.currentClientState){var r=Ye(null,t[oe.UPLINK]),n=Ye(null,this.currentClientState[oe.UPLINK]),i=Ye(null,t[oe.DOWNLINK]),o=Ye(null,this.currentClientState[oe.DOWNLINK]);r===n&&i===o||this.channel.userManager.setParticipantProperties(t).catch((function(t){e.reporter.log.debug("setParticipantProperties error ".concat(m(t)))})),this.currentClientState=t}}},{key:"handleVisibilitychange",value:function(){var t="visible"!==document.visibilityState,r=t?T.APP_BACKGROUND:T.APP_FOREGROUND;(e.isAndroid()||e.isIOS())&&(this.reporter.sender.sendEvent(r),this.clientStatSync[oe.BACKGROUND_MODE]=Number(t))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[oe.UPLINK]=e,this.clientStatSync[oe.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.reporter.log.info("leave for ".concat(e.type)),this.leave())}},{key:"addEventListeners",value:function(){window.addEventListener(e.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.addEventListener("visibilitychange",this.handleVisibilitychange),this.channel.sessionManager.on("network-quality",this.handleNetworkQuality),this.channel.signaling.on("connection-state-change",this.handleConnectionChangeEvent)}},{key:"removeEventListeners",value:function(){window.removeEventListener(e.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.removeEventListener("visibilitychange",this.handleVisibilitychange),this.channel.sessionManager.off("network-quality",this.handleNetworkQuality),this.channel.signaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(e){var t=e.userData,r=e.groupId,n=new TextEncoder;if(!r||n.encode(r).length>64)throw new i(o.InvaildArgument,"join group with invalid groupId");if(t){var a=new TextEncoder;if("string"!=typeof t||a.encode(t).length>64)throw new i(o.InvaildArgument,"join group with invalid userData")}return this.channel.joinGroup(e)}},{key:"leaveGroup",value:function(e){return this.channel.leaveGroup({groupId:e,publishAudioToChannel:!1})}},{key:"setGroupName",value:function(e,t){var r=new TextEncoder;if(!t||r.encode(t).length>64)throw new i(o.InvaildArgument,"update group with invalid name");return this.channel.setGroupProperties(e,{key:"name",value:t})}},{key:"subscribeGroup",value:function(e){return this.channel.subscribeGroup(e)}},{key:"unsubscribeGroup",value:function(e){return this.channel.unsubscribeGroup(e)}},{key:"mixAudioToGroup",value:function(e,t,r){if("audio"!==e.trackMediaType)throw new i(o.InvaildArgument,"only support publish audio to group");if("connected"!==this.connectionState)throw new i(o.PublishNotJoinChannel);if(t){if(this.reporter.log.info("mix audio track:".concat(e.getTrackId()," to group ").concat(r)),null==r&&this.channel.micMixedGroups.size)throw new i(o.InvaildState,"cannot mix audio to channel while mixing to others group");return this.channel.publishToGroup(e,r,!0)}if(this.reporter.log.info("unmix audio track:".concat(e.getTrackId()," from group ").concat(r)),!this.channel.micMixedGroups.has(r))throw new i(o.InvaildState,"cannot unmix audio from the unmixed group");return this.channel.unpublishFromGroup(e,r)}},{key:"dismissGroup",value:function(e){return this.channel.dismissGroup(e)}},{key:"register",value:function(e){e.attach(this.channel.internalChannel,this.channel)}},{key:"ungister",value:function(e){e.detach(this.channel.internalChannel)}}]);var r,n}(),qi={height:360,width:640};function Hi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Hi=function(){return!!e})()}ot();var Yi=t().log,Wi=new(function(){function e(){var t,r,n,i;if(C(this,e),r=this,n=F(n=e),t=N(r,Hi()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t.VERSION=le,!ye.checkSupported())return N(t);var o=je.getInstance();return o.on("camera-changed",(function(e){t.emit("camera-changed",e)})),o.on("microphone-changed",(function(e){t.emit("microphone-changed",e)})),o.on("playback-device-changed",(function(e){t.emit("playback-device-changed",e)})),y.on("autoplay-failed",(function(e){t.emit("autoplay-failed",e)})),t}return U(e,c),L(e,[{key:"createClient",value:function(){return Yi.info("createClient"),new Bi}},{key:"checkSystemRequirements",value:function(){return Yi.info("checkSystemRequirements"),ye.checkSupported()}},{key:"getSupportedCodec",value:function(){return Yi.info("getSupportedCodec"),ye.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return Yi.info("createCameraVideoTrack",e),er(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return Yi.info("createMicrophoneAudioTrack",e),Zt(e)}},{key:"createCustomVideoTrack",value:function(e){return Yi.info("createCustomVideoTrack",e),nr(e)}},{key:"createCustomAudioTrack",value:function(e){return Yi.info("createCustomAudioTrack",e),ir(e)}},{key:"createScreenVideoTrack",value:function(e){return Yi.info("createScreenVideoTrack",e),tr(e)}},{key:"createMicrophoneAndCameraTracks",value:(t=M(se.mark((function e(t,r){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Yi.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",rr(t,r));case 2:case"end":return e.stop()}}),e)}))),function(e,r){return t.apply(this,arguments)})},{key:"getCameras",value:function(){return Yi.info("getCameras"),je.getCameras()}},{key:"getDevices",value:function(){return Yi.info("getDevices"),je.getDevices()}},{key:"getPlaybackDevices",value:function(){return Yi.info("getPlaybackDevices"),je.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return Yi.info("getMicrophones"),je.getMicrophones()}},{key:"setLogLevel",value:function(e){I(e),Yi.info("setLogLevel",e)}},{key:"setClientConfig",value:function(e){Yi.info("setClientConfig",e),we.setClientConfig(e)}}]);var t}());export{K as AudioSourceInfo,ue as AudioSourceState,qi as FALLBACK_SUB_VIDEO_PROFILE,z as VideoSourceInfo,Wi as default};
|
|
1
|
+
import"webrtc-adapter";import{Environment as e,getReporter as t,SystemType as r,BrowserType as n,DingRTCError as i,ErrorCode as o,setGslb as a,isString as s,EventEmitter as c,parseAudioDeviceError as u,parseVideoDeviceError as l,addTimer as d,isObject as p,isNumber as f,removeTimer as v,Debouncer as h,tryJsonStringify as m,EventBus as y,createUuid as g,parseScreenShareError as b,getProtobufRoot as S,isPrivateIP as k,SdkType as P,uniqBy as w,VideoSourceInfo as O,TraceEvent as T,registerReporter as E,setLogLevel as I}from"@dingrtc/shared";export{ErrorCodeAndMsgMap}from"@dingrtc/shared";import R from"sdp-transform";import{DingRTCChannel as A}from"@dingrtc/channel";function _(e,t,r,n,i,o,a){try{var s=e[o](a),c=s.value}catch(e){return void r(e)}s.done?t(c):Promise.resolve(c).then(n,i)}function M(e){return function(){var t=this,r=arguments;return new Promise((function(n,i){var o=e.apply(t,r);function a(e){_(o,n,i,a,s,"next",e)}function s(e){_(o,n,i,a,s,"throw",e)}a(void 0)}))}}function C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function D(e){return D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},D(e)}function x(e){var t=function(e,t){if("object"!=D(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=D(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==D(t)?t:t+""}function j(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,x(n.key),n)}}function L(e,t,r){return t&&j(e.prototype,t),r&&j(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function N(e,t){if(t&&("object"==D(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function F(e){return F=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},F(e)}function G(e,t){return G=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},G(e,t)}function U(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&G(e,t)}function V(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var B={exports:{}},q={exports:{}};!function(e){function t(r){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(q);var H=q.exports;!function(e){var t=H.default;function r(){e.exports=r=function(){return i},e.exports.__esModule=!0,e.exports.default=e.exports;var n,i={},o=Object.prototype,a=o.hasOwnProperty,s=Object.defineProperty||function(e,t,r){e[t]=r.value},c="function"==typeof Symbol?Symbol:{},u=c.iterator||"@@iterator",l=c.asyncIterator||"@@asyncIterator",d=c.toStringTag||"@@toStringTag";function p(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{p({},"")}catch(n){p=function(e,t,r){return e[t]=r}}function f(e,t,r,n){var i=t&&t.prototype instanceof S?t:S,o=Object.create(i.prototype),a=new D(n||[]);return s(o,"_invoke",{value:A(e,r,a)}),o}function v(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}i.wrap=f;var h="suspendedStart",m="suspendedYield",y="executing",g="completed",b={};function S(){}function k(){}function P(){}var w={};p(w,u,(function(){return this}));var O=Object.getPrototypeOf,T=O&&O(O(x([])));T&&T!==o&&a.call(T,u)&&(w=T);var E=P.prototype=S.prototype=Object.create(w);function I(e){["next","throw","return"].forEach((function(t){p(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,r){function n(i,o,s,c){var u=v(e[i],e,o);if("throw"!==u.type){var l=u.arg,d=l.value;return d&&"object"==t(d)&&a.call(d,"__await")?r.resolve(d.__await).then((function(e){n("next",e,s,c)}),(function(e){n("throw",e,s,c)})):r.resolve(d).then((function(e){l.value=e,s(l)}),(function(e){return n("throw",e,s,c)}))}c(u.arg)}var i;s(this,"_invoke",{value:function(e,t){function o(){return new r((function(r,i){n(e,t,r,i)}))}return i=i?i.then(o,o):o()}})}function A(e,t,r){var i=h;return function(o,a){if(i===y)throw Error("Generator is already running");if(i===g){if("throw"===o)throw a;return{value:n,done:!0}}for(r.method=o,r.arg=a;;){var s=r.delegate;if(s){var c=_(s,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===h)throw i=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=y;var u=v(e,t,r);if("normal"===u.type){if(i=r.done?g:m,u.arg===b)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=g,r.method="throw",r.arg=u.arg)}}}function _(e,t){var r=t.method,i=e.iterator[r];if(i===n)return t.delegate=null,"throw"===r&&e.iterator.return&&(t.method="return",t.arg=n,_(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),b;var o=v(i,e.iterator,t.arg);if("throw"===o.type)return t.method="throw",t.arg=o.arg,t.delegate=null,b;var a=o.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=n),t.delegate=null,b):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,b)}function M(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function D(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(M,this),this.reset(!0)}function x(e){if(e||""===e){var r=e[u];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,o=function t(){for(;++i<e.length;)if(a.call(e,i))return t.value=e[i],t.done=!1,t;return t.value=n,t.done=!0,t};return o.next=o}}throw new TypeError(t(e)+" is not iterable")}return k.prototype=P,s(E,"constructor",{value:P,configurable:!0}),s(P,"constructor",{value:k,configurable:!0}),k.displayName=p(P,d,"GeneratorFunction"),i.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===k||"GeneratorFunction"===(t.displayName||t.name))},i.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,P):(e.__proto__=P,p(e,d,"GeneratorFunction")),e.prototype=Object.create(E),e},i.awrap=function(e){return{__await:e}},I(R.prototype),p(R.prototype,l,(function(){return this})),i.AsyncIterator=R,i.async=function(e,t,r,n,o){void 0===o&&(o=Promise);var a=new R(f(e,t,r,n),o);return i.isGeneratorFunction(t)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},I(E),p(E,d,"Generator"),p(E,u,(function(){return this})),p(E,"toString",(function(){return"[object Generator]"})),i.keys=function(e){var t=Object(e),r=[];for(var n in t)r.push(n);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},i.values=x,D.prototype={constructor:D,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(C),!e)for(var t in this)"t"===t.charAt(0)&&a.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=n)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function r(r,i){return s.type="throw",s.arg=e,t.next=r,i&&(t.method="next",t.arg=n),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var c=a.call(o,"catchLoc"),u=a.call(o,"finallyLoc");if(c&&u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&a.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),C(r),b}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var i=n.arg;C(r)}return i}}throw Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:x(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=n),b}},i}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(B);var Y=(0,B.exports)(),Q=Y;try{regeneratorRuntime=Y}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=Y:Function("r","regeneratorRuntime = r")(Y)}var J,W,K,z,$,X,Z,ee,te,re,ne,ie,oe,ae,se=V(Q);function ce(e,t,r){return(t=x(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}!function(e){e.PCMU="pcmu",e.PCMA="pcma",e.OPUS="opus",e.G722="g722",e.ISAC="iSAC",e.ILBC="iLBC",e.AAC="aac",e.AC3="ac3",e.NELLYMOSER="nellymoser"}(J||(J={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(W||(W={})),function(e){e.MIC="mic",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(K||(K={})),function(e){e.CAMERA="camera",e.SCREENCAST="screen-cast",e.MIXED="mixed"}(z||(z={})),function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}($||($={})),function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.GREAT=1]="GREAT",e[e.GOOD=2]="GOOD",e[e.NORMAL=3]="NORMAL",e[e.POOR=4]="POOR",e[e.BAD=5]="BAD",e[e.DISCONNECTED=6]="DISCONNECTED"}(X||(X={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(Z||(Z={})),function(e){e[e.Windows=1]="Windows",e[e.Android=2]="Android",e[e.Mac=3]="Mac",e[e.iOS=4]="iOS",e[e.Linux=5]="Linux",e[e.Others=6]="Others"}(ee||(ee={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(te||(te={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(re||(re={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(ne||(ne={})),function(e){e.QuotaLimit="task exceed limit",e.PCNotExisted="connection does NOT exist",e.RoomClosed="room_already_closed:30107",e.RoomNotExisted="room does not exist",e.RoomBusy="RoomBusy",e.RoomNotJoined="participant has not joined",e.FailOver="Session has been aborted"}(ie||(ie={})),function(e){e[e.MIC_OPEN=0]="MIC_OPEN",e[e.MIC_INTERRUPTED=1]="MIC_INTERRUPTED",e[e.CAMERA_OPEN=2]="CAMERA_OPEN",e[e.BACKGROUND_MODE=3]="BACKGROUND_MODE",e[e.DOWNLINK=4]="DOWNLINK",e[e.UPLINK=5]="UPLINK"}(oe||(oe={})),function(e){e[e.None=0]="None",e[e.LD=2]="LD",e[e.SD=4]="SD",e[e.HD=8]="HD",e[e.FHD=16]="FHD",e[e.QHD=32]="QHD",e[e.UHD=64]="UHD"}(ae||(ae={}));var ue,le={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};!function(e){e.Playing="playing",e.Paused="paused",e.Stopped="stopped"}(ue||(ue={}));var de="3.7.1",pe=-999,fe="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.browserType,e.browserVersion,e.system,e.systemVersion;var ve="onertc_state_sync",he="onertc_internal_track_event",me=t().log,ye=new(function(){return L((function t(){C(this,t),Object.defineProperty(this,"system",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"browserVersion",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.system=e.system,this.browser=e.browserType,this.browserVersion=e.browserVersion}),[{key:"getSupportedCodec",value:(t=M(se.mark((function e(){var t,r,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t={audio:[],video:[]},e.prev=1,(r=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),r.addTransceiver("audio",{direction:"recvonly"}),e.next=7,r.createOffer();case 7:if(n=e.sent.sdp){e.next=10;break}return e.abrupt("return",t);case 10:return r.close(),r=null,n.match(/ VP8/i)&&t.video.push("VP8"),n.match(/ VP9/i)&&t.video.push("VP9"),n.match(/ AV1/i)&&t.video.push("AV1"),n.match(/ H264/i)&&t.video.push("H264"),n.match(/ H265/i)&&t.video.push("H265"),n.match(/ opus/i)&&t.audio.push("OPUS"),n.match(/ PCMU/i)&&t.audio.push("PCMU"),n.match(/ PCMA/i)&&t.audio.push("PCMA"),n.match(/ G722/i)&&t.audio.push("G722"),e.abrupt("return",t);case 24:throw e.prev=24,e.t0=e.catch(1),me.error("get supportedCodecs failed"),new i(o.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 28:case"end":return e.stop()}}),e,null,[[1,24]])}))),function(){return t.apply(this,arguments)})},{key:"checkSupported",value:function(){var t=!1;try{var r=window.RTCPeerConnection,n=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,i=window.WebSocket;t=!!(r&&n&&i)}catch(e){return!1}var o=!1;o=e.isChrome()||e.isFirefox()?parseInt(e.browserVersion,10)>=69:e.isOpera()?parseInt(e.browserVersion,10)>=45:e.isSafari()?parseInt(e.browserVersion,10)>=11:(e.isWeixin()||e.isQQBrowser(),!0);var a=t&&o;return me.debug("checkSystemRequirements, api:",t,"browser",o),a}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(r.ANDROID)&&this.system!==r.IOS&&(!(this.browser===n.SAFARI&&parseInt(this.browserVersion)<13)&&(!(this.browser===n.FIREFOX&&parseInt(this.browserVersion)<66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var t}()),ge=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},n=r.setParameters,i=r.getParameters;return!(!n||!i)&&(!e.isFirefox()&&(e.isSafari()?parseInt(e.browserVersion)>=14:e.isChrome()?parseInt(e.browserVersion)>=81:!e.isAndroid()))};function be(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Se(e,t){if(e){if("string"==typeof e)return be(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?be(e,t):void 0}}function ke(e){return function(e){if(Array.isArray(e))return be(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Se(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Pe(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Pe=function(){return!!e})()}var we=function(){function e(){var t,r,n,i;return C(this,e),r=this,n=F(n=e),t=N(r,Pe()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:ge()}),Object.defineProperty(t,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(t,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(t,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(t,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),t}return U(e,c),L(e,[{key:"setClientConfig",value:function(e){var t=e||{},r=t.gslb,n=t.simulcast,i=t.audioSFU,o=t.republish,c=t.disableTransportCC;"string"==typeof r&&(this.gslb=[r],a(r)),Array.isArray(r)&&s(r[0])&&(this.gslb=r,a(r[0])),null!=n&&ge()&&(this.simulcast=Boolean(n)),null!=i&&(this.audioSFU=Boolean(i)),null!=c&&(this.disableTransportCC=Boolean(c)),null!=o&&(this.republish=Boolean(o))}}])}(),Oe=new we,Te=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},Ee=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,ke(i.parameters.resolution)),n.sort(Te),n},Ie=function(e,t){var r,n=e.media,a=n.audio,s=n.video;if(t===ie.QuotaLimit)return r=new i(o.QuotaLimitExceed);if(a)r=new i(o.SubscribeAudioStreamFailed,t);else if(s){var c=s.source;c===z.CAMERA?r=new i(o.SubscribeVideoStreamFailed,t):c===z.SCREENCAST&&(r=new i(o.SubscribeScreenShareFailed,t))}return r},Re=function(e,t){var r,n=e.trackMediaType;if(t===ie.QuotaLimit)return r=new i(o.QuotaLimitExceed);if("audio"===n)r=new i(o.PublishAudioStreamFailed,t);else{var a=e.source;a===z.CAMERA?r=new i(o.PublishVideoStreamFailed,t):a===z.SCREENCAST&&(r=new i(o.PublishScreenShareFailed,t))}return r},Ae=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?Oe.audioSFU?n?n.replaceStream(e):i=new mr(null,r,e):n?n.replaceTrack(a[0]):i=new mr(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new yr(o[0],r)),i},_e=function(e){return"object"===D(e.video)&&e.video.source===z.SCREENCAST};function Me(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ce(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Me(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function De(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return xe(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?xe(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function xe(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function je(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(je=function(){return!!e})()}var Le=function(){function e(){var t,r,n,i,o;return C(this,e),r=this,n=F(n=e),t=N(r,je()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(t,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(o=M(se.mark((function r(){var n;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!t.checking){r.next=2;break}return r.abrupt("return");case 2:return t.checking=!0,r.next=5,e.getDevices();case 5:n=r.sent,t.compareDevices(n,"audiooutput"),t.compareDevices(n,"videoinput"),t.compareDevices(n,"audioinput"),t.deviceList=n,t.checking=!1;case 11:case"end":return r.stop()}}),r)}))),function(){return o.apply(this,arguments)})}),Object.defineProperty(t,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(e,r){var n,i=e.filter((function(e){return e.kind===r})),o=t.deviceList.filter((function(e){return e.kind===r})),a=i.map((function(e){return e.deviceId})),s=o.map((function(e){return e.deviceId})),c=i.filter((function(e){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),l={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},d=De(c);try{for(d.s();!(n=d.n()).done;){var p=n.value;t.emit(l[r],{device:p,state:"active"})}}catch(e){d.e(e)}finally{d.f()}var f,v=De(u);try{for(v.s();!(f=v.n()).done;){var h=f.value;t.emit(l[r],{device:h,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),e._instance?N(t,e._instance):(t.deviceList=[],ye.checkSupported()?(e.getDevices({audio:!0,video:!0},!0).then((function(e){t.deviceList=e,t.addEventListeners()})),t):N(t))}return U(e,c),L(e,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):d(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return e._instance}},{key:"getMedias",value:function(e,t){var r,n,i=this;return _e(e)?null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t):null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t}))}},{key:"getDevices",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(n,a){var s;if(null!==(s=navigator.mediaDevices)&&void 0!==s&&s.enumerateDevices){var c=!1;t.audio&&t.video?c=e.audioPermitted&&e.videoPermitted:t.audio?c=e.audioPermitted:t.video&&(c=e.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(i){var o=i.filter((function(e){return e.deviceId})),s=o.filter((function(e){return"videoinput"===e.kind})),u=o.filter((function(e){return"audioinput"===e.kind})),l=o.filter((function(e){return"audiooutput"===e.kind})),d=[];t.audio&&(d=d.concat(u,l)),t.video&&(d=d.concat(s)),0!==d.length||c||r?d.length?(t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),n(d)):n(d):navigator.mediaDevices.getUserMedia(t).then((function(r){t.audio&&(e.audioPermitted=!0),t.video&&(e.videoPermitted=!0),r.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){n(e)}),a)}),a),n(o)}))}else a(new i(o.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}();Object.defineProperty(Le,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(Le,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(Le,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new Le}),Object.defineProperty(Le,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Le.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(e){throw u(e)}))}}),Object.defineProperty(Le,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Le.getDevices({video:!0}).then((function(e){return e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return Ce(Ce({},r),{},{toJSON:function(){return r}})}))})).catch((function(e){throw l(e)}))}}),Object.defineProperty(Le,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Le.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(e){throw u(e)}))}});var Ne=function(e){return{width:le[e][0],height:le[e][1]}},Fe=function(t){var r,n=Object.create({}),i={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(i=navigator.mediaDevices.getSupportedConstraints(),console.log(i));var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.isSafari()?n.deviceId=t.deviceId:n.deviceId={exact:t.deviceId}),i.autoGainControl&&(n.autoGainControl={ideal:null==a||a}),i.echoCancellation&&(n.echoCancellation={ideal:null==o||o}),i.noiseSuppression&&(n.noiseSuppression={ideal:null==s||s}),n},Ge=function(t){if(!p(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,n=t.video;if(!_e(t)&&"object"===D(r)&&r.source===K.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(_e(t)&&"object"===D(r)&&r.source!==K.SCREENCAST)return Promise.reject(new TypeError("Cannot capture video from screen cast while capture audio from other source."));if(!r&&!n)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var i=Object.create({});if("object"===D(r)&&r.source===K.MIC||"object"===D(r)&&r.source===K.SCREENCAST?i.audio=Fe(r):i.audio=t.audio,"object"===D(n)){var o,a=n.frameRate,c=n.deviceId,u=n.source,l=n.facingMode,d=n.displaySurface,v=n.dimension;i.video=Object.create({}),f(a)&&(i.video.frameRate=Math.min(n.frameRate,30)),v&&(o=Ne(v)),o&&o.width&&o.height&&(u===z.SCREENCAST||e.isFirefox()?(i.video.width=o.width,i.video.height=o.height):(i.video.width={ideal:o.width,max:o.width},i.video.height={ideal:o.height,max:o.height})),s(c)&&c&&(i.video.deviceId={exact:c}),u===z.SCREENCAST&&(e.isFirefox()&&(i.video.mediaSource="screen"),d&&["browser","window","monitor"].includes(d)&&(i.video.displaySurface=d)),l&&["user","environment"].includes(l)&&(i.video.facingMode=l)}else i.video=n;return Le.getMedias(t,i)};function Ue(){return Ue="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=F(e)););return e}(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(arguments.length<3?e:r):i.value}},Ue.apply(null,arguments)}var Ve,Be,qe=void 0,He=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map((function(e){return function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t}(e)}));return t.trackInfos=r,t},Ye=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},Qe=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},Je=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},We=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Ke=new Map,ze=function(e){return new Promise((function(t){d(t,1e3*e)}))},$e=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=null,i=0;return function(){for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];var c=Date.now();c-i>=t&&r?(e.apply(qe,a),i=c):(n&&clearTimeout(n),n=setTimeout((function(){e.apply(qe,a),i=c}),t))}},Xe=t().log,Ze="rtc-intersecting",et="visible",tt="invisible",rt=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],nt=function(e){return"".concat(null==e?void 0:e.getAttribute(fe),"-").concat(null==e?void 0:e.rtcPurpose)},it=function(){return L((function e(t,r){var n=this;C(this,e),Object.defineProperty(this,"mediaElementPool",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaElementsInUse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"allElements",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"hasActivated",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"mediaKind",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaPlaybackCheckInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"debouncer",{enumerable:!0,configurable:!0,writable:!0,value:new h}),Object.defineProperty(this,"currentTimeOfLastCheckMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"observer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_activatedListener",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"destroy",{enumerable:!0,configurable:!0,writable:!0,value:function(){n.mediaElementPool.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach((function(e){return n._resetMediaElement(e)})),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(v(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(ke(n.mediaElementPool),ke(n.mediaElementsInUse)).forEach((function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject;if(t.error){var i="".concat(e,": ").concat(nt(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=He(r);Xe.debug(i,o),"visible"===document.visibilityState&&Ye(r)&&t.load()}if(t.paused){var a=!1;if(n.hasActivated&&"video"===n.mediaKind?function(e){return e&&e.getAttribute(Ze)===et}(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(nt(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(Ze),", mediaStream="),c=He(r);Xe.error(s,c),Ye(r)&&t.load(),t.paused&&t.play().catch((function(e){console.error("inPoll",e)}))}}}})),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject,i="video"===n.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&n.currentTimeOfLastCheckMap.get(t)===t.currentTime&&!0!==(null==i?void 0:i.muted)){var o="".concat(e,": ").concat(nt(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=He(r);return Xe.error(o,a),void("visible"===document.visibilityState&&Ye(r)&&t.load())}n.currentTimeOfLastCheckMap.set(t,t.currentTime)}}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(n.mediaKind," playback, mediaStream="),i=He(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Xe.error(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(n.mediaKind," playback, mediaStream="),i=He(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Xe.debug(r,i,o)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(n.mediaKind," playback, mediaStream="),i=He(null==t?void 0:t.srcObject);Xe.debug(r,i)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e=[].concat(ke(n.mediaElementPool),ke(n.mediaElementsInUse));if(!n.hasActivated&&(n.hasActivated=!0,e.forEach((function(e){e.load()})),n._activatedListener))try{n._activatedListener()}catch(e){Xe.error("error occurred when exec activatedListener",m(e))}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=t,window.IntersectionObserver&&(this.observer=new IntersectionObserver((function(e){e.forEach((function(e){var t,r;e.isIntersecting?null===(t=e.target)||void 0===t||t.setAttribute(Ze,et):null===(r=e.target)||void 0===r||r.setAttribute(Ze,tt)}))})));for(var i=0;i<r;i++){var o,a=this._createElement();null===(o=this.observer)||void 0===o||o.observe(a),this.addAtttribute(a),a.setAttribute(fe,"".concat(t,"-").concat(i)),this.mediaElementPool.push(a),this.allElements.add(a)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=d((function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")}),4e3,"interval")}),[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(fe,"toReused"),e instanceof HTMLVideoElement)e.muted=!0,e.playsInline=!0,e.controls=!1,e.setAttribute("webkit-playsinline","true"),e.setAttribute("x5-video-player-type","h5"),e.setAttribute("x5-playsinline","true");else{var t,r=e;r.volume=1,null===(t=r.setSinkId)||void 0===t||t.call(r,"")}}},{key:"popElement",value:function(e){var t;return(t=this.mediaElementPool.shift())?(this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||""):(t=document.createElement(this.mediaKind),this.addAtttribute(t)),t}},{key:"pushElement",value:function(e){if(this.allElements.has(e)){var t=this.mediaElementsInUse;this.mediaElementsInUse=this.mediaElementsInUse.filter((function(t){return t!==e})),t.length!==this.mediaElementsInUse.length&&(this.mediaElementPool.push(e),this._resetMediaElement(e))}}},{key:"isMediaElementActivated",value:function(){return this.hasActivated}},{key:"setActivateListener",value:function(e){this._activatedListener=e}},{key:"_createElement",value:function(){var e,t=document.createElement(this.mediaKind);return null===(e=this.observer)||void 0===e||e.observe(t),t}},{key:"_resetMediaElement",value:function(e){rt.forEach((function(t){e["on".concat(t)]=null})),e.removeEventListener("error",this._elementDefaultErrorHandler),e.removeEventListener("pause",this._elementDefaultPauseHandler),e.removeEventListener("play",this._elementDefaultPlayHandler),e.style.cssText="",e.className="",this.addAtttribute(e),e.srcObject=null}}])}(),ot=function(){return Ve||ct(),Ve},at=function(){return Be||ct(),Be},st=e.isIOS()||e.isAndroid()?9:25,ct=function(){Ve||(Ve=new it("audio",2)),Be||(Be=new it("video",st))},ut=new AudioContext,lt=function(e){var t=e.getAudioTracks(),r=ut.createMediaStreamDestination();return t.forEach((function(e){ut.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},dt=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},pt=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),n=e.videoHeight,i=e.videoWidth;return t.width=i,t.height=n,r.drawImage(e,0,0,i,n),t.toDataURL("image/png")},ft=ot(),vt=at(),ht=t().log,mt=function(){return L((function e(){C(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(e,t,r){var n,a=this,s=e.getTrackId(),c=e.sfuStream||new MediaStream([e.getMediaStreamTrack()]);if("video"===e.trackMediaType){var u,l=this.findDom(t);if(!l)throw new i(o.InvaildArgument,"wrapper dom not found");var d=r||{},p=d.mirror,f=d.fit;if((n=this.players.find((function(e){return e.container===t})))&&(null===(u=n.track)||void 0===u?void 0:u.getTrackId())!==(null==e?void 0:e.getTrackId()))return this.stop(n.track,t),void this.play(e,t,r);n?(n.element.pause(),!e.sourceMirror!=!p?n.element.style.transform="scaleX(-1)":n.element.style.transform="",f&&(n.element.style.objectFit=f),n.element.srcObject=c,n.element.load()):((n={container:t,track:e,playerConfig:r}).element=function(e,t,r){var n=at().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n}(l,c,{mirror:!e.sourceMirror!=!p,fit:f}),this.players.push(n))}else(n=this.players.find((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})))?(n.element.pause(),n.element.srcObject=c,n.element.load()):((n={track:e}).element=function(e){var t=ot().popElement();return t.srcObject=e,t}(c),this.players.push(n));n.element.paused&&n.element.play().then((function(){n.isPlaying=!0})).catch((function(e){"NotAllowedError"===e.name?(ht.error("autoplay failed",m(e)),y.emit("autoplay-failed",a)):ht.warn("".concat(s," play has exception"),m(e))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?ft.pushElement(t.element):vt.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),yt=new mt,gt=function(){return yt};function bt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(bt=function(){return!!e})()}var St,kt=t(),Pt=kt.log,wt=kt.trace,Ot=gt(),Tt=function(){function e(t,r){var n,i,o,a;return C(this,e),i=this,o=F(o=e),n=N(i,bt()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:wt}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t?(n.trackMediaType=t.kind,n.trackSettings=t.getSettings()):r&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.audioContext=ut,n.analyser=n.audioContext.createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(g(6)),n.setMediaStreamTrack(t,r),n}return U(e,c),L(e,[{key:"isPlaying",get:function(){return Ot.isPlaying(this)}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(e,t){var r=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),e||t){var a;if(n&&e&&(e.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),e)this.sourceNode=null===(a=this.audioContext)||void 0===a?void 0:a.createMediaStreamSource(new MediaStream([e]));else if(t){var s,c=lt(t);this.sourceNode=null===(s=this.audioContext)||void 0===s?void 0:s.createMediaStreamSource(new MediaStream([c]))}e?(this.mediaStreamTrack=e,this.mediaStreamTrack.onended=function(){r.source===z.SCREENCAST?r.logger.sendEvent("SCREEN_DEVICE_STOP"):r.source===K.MIC?new i(o.MicInterrupt):r.source===z.CAMERA&&new i(o.CameraInterrupt)}):t&&(this.sfuStream=t)}}},{key:"replaceTrack",value:function(e,t){Pt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(he,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{key:"setSource",value:function(e){e===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===z.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===K.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(e){Pt.info("stop paly track ".concat(this.getTrackId())),Ot.stop(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.element,n=e.config;e.updated?Ot.getPlayInfos(this).forEach((function(e){e.container?Ot.findDom(e.container)?Ot.play(t,e.container,e.playerConfig):Ot.stop(t,e.container):Ot.play(t,e.container,e.playerConfig)})):Ot.play(this,r,n);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(e){Pt.debug("resume audioContext failed: ".concat(m(e)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function Et(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,o,a,s=[],c=!0,u=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;c=!1}else for(;!(c=(n=o.call(r)).done)&&(s.push(n.value),s.length!==t);c=!0);}catch(e){u=!0,i=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw i}}return s}}(e,t)||Se(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function It(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Rt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?It(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):It(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(St||(St={}));var At=ce(ce(ce(ce(ce(ce({},St.LLD,"lld"),St.LD,"ld"),St.SD,"sd"),St.HD,"hd"),St.FHD,"fhd"),St.QHD,"qhd"),_t={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},Mt=function(e){return 2560===e.width&&1440===e.height},Ct=function(e,t){var r=xt(e,t),n=function(e,t){var r={high:ae.QHD,low:ae.LD,QHD:ae.QHD,FHD:ae.FHD,HD:ae.HD,SD:ae.SD,LD:ae.LD},n=r[e]||ae.None,i=_t[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(_t).find((function(e){var t=Et(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[Et(a,1)[0]]}return n}(e,t);return{resolution:r,resolutionLevel:n}},Dt=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},xt=function(e,t){var r=_t[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&Mt(i))return i;if(t[0].width*t[0].height>_t.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},jt=[49152,76800,307200,1228800,2764800,4915200],Lt=[200,350,1e3,1800,2828,5600],Nt=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],Ft=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],Gt=function(e,t){var r=St.FHD,n=e*t;return n<=jt[St.LLD]?r=St.LLD:n<=jt[St.LD]?r=St.LD:n<=jt[St.SD]?r=St.SD:n<=jt[St.HD]?r=St.HD:n<=jt[St.FHD]?r=St.FHD:n<=jt[St.QHD]&&(r=St.QHD),r},Ut=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=Nt[r][0],o=Nt[r][1];else if(4*t==3*e)i=Ft[r][0],o=Ft[r][1];else{var s=Math.sqrt(1*Nt[r][0]*Nt[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},Vt=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=Lt[Gt(e,t)];n=Math.round(Math.max(i*o,50))}return n},Bt=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=Gt(t,r),s=[],c=a>=St.HD?3:2,u=function(e){var o=Et(Ut(t,r,e,a),2),s=o[0],c=o[1],u=Lt[e]/Lt[a],l=1/(c/r);return{targetWidth:s,rid:At[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:l}};a>St.LLD&&s.push(Rt({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,St.LLD)===o},u(St.LLD))),a>St.LD&&s.push(Rt({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,St.LD)===o},u(St.LD))),a>St.SD&&s.push(Rt({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,St.SD)===o},u(St.SD))),a===St.FHD?(s.push(Rt({activeForBitrateMap:!1,activeForRealuse:!1},u(St.HD))),s.push(Rt({activeForBitrateMap:!0,activeForRealuse:Oe.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(St.FHD)))):s.push(Rt({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var l=0,d=0;d<s.length;++d)0!=d&&(s[d].minBitrate=l),l=Math.round(Math.max((s[d].maxBitrate+s[d].minBitrate)/2,s[d].maxBitrate-400));return s.shift(),s},qt=function(e,t){var r=Gt(e,t),n=Math.pow(2,r);return console.log(n,r),n},Ht=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!Oe.simulcast||e.source===z.SCREENCAST||Mt({width:i,height:o}),c={resolutionLevel:qt(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:Oe.republish?c.encodings=Bt({width:1920,height:1080,frameRate:30,maxBitrate:Vt(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=Bt({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function Yt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Qt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Yt(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Yt(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Jt(e,t,r){return t=F(t),N(e,Wt()?Reflect.construct(t,r||[],F(e).constructor):t.apply(e,r))}function Wt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Wt=function(){return!!e})()}function Kt(e,t,r,n){var i=Ue(F(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var zt=gt(),$t=t().log,Xt=function(){function e(t,r){var n;if(C(this,e),n=Jt(this,e,[t]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),t){var i=t.muted;n.muted=i}return n.enabled=!0,n.deviceId=r,n}return U(e,Tt),L(e,[{key:"setMediaStreamTrack",value:function(t){var r=this;Kt(e,"setMediaStreamTrack",this)([t]),t&&(this.trackSettings=t.getSettings(),t.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(e){return $t.info("setEnabled",e),this.isClosed?Promise.reject(new i(o.InvaildState)):(this.enabled=e,this.emit(he,e?"unmute":"mute"),e?this.updateNewTrack():(null===(t=this.mediaStreamTrack)||void 0===t||t.stop(),this.setMediaStreamTrack(null),this.source===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===z.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),Promise.resolve()));var t}},{key:"close",value:function(){var e;$t.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(he,"stop"),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.audioContext&&(this.sourceNode=null,this.analyser=null,this.audioContext=null),this.source===z.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===z.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(e){return $t.info("setMuted",e),this.isClosed?Promise.reject(new i(o.InvaildState)):(this.muted=e,this.mediaStreamTrack.enabled=!e,this.emit(he,e?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var e=this;return $t.debug("gengrate new audioTrack"),new Promise((function(t,r){var n;Ge({audio:Qt(Qt({source:e.source},e.config),{},{deviceId:e.deviceId})}).then((function(e){n=e.getAudioTracks()[0]})).catch((function(t){try{var i=e.audioContext.createOscillator(),o=e.audioContext.createMediaStreamDestination();i.connect(o),n=o.stream.getAudioTracks()[0]}catch(e){$t.error("gengrate new audioTrack error",u(t)),r(u(t))}})).finally((function(){n&&t(n)}))}))}},{key:"getVideoTrack",value:function(){var e=this;return $t.debug("gengrate new videoTrack"),new Promise((function(t,r){var n;Ge({video:Qt(Qt({source:e.source},e.config),{},{deviceId:e.deviceId}),audio:!1}).then((function(e){n=e.getVideoTracks()[0],t(n)})).catch((function(e){$t.error("gengrate new videoTrack error",l(e)),r(l(e))}))}))}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,$t.debug("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(t=M(se.mark((function e(t){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if($t.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof tr)||"user"!==t&&"environment"!==t){e.next=7;break}this.config.facingMode=t,e.next=10;break;case 7:if(this.deviceId!==t){e.next=9;break}return e.abrupt("return");case 9:this.deviceId=t;case 10:return e.abrupt("return",this.updateNewTrack());case 11:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if($t.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var t}(),Zt=function(){function e(t,r,n){var i;if(C(this,e),(i=Jt(this,e,[t,r])).config=n,t){var o=t.getSettings(),a=o.width,s=o.height;i.maxBitrate=Vt(a,s,n.frameRate,n.maxBitrate)}return i}return U(e,Xt),L(e,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(e){var t=this;$t.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),e);var r=e.dimension,n=e.frameRate,a=e.maxBitrate,s=e.optimizationMode,c=e.mirror;if(n&&Number.isNaN(n))return Promise.reject(new i(o.InvaildArgument,"invalid frameRate"));if(r&&!le[r])return Promise.reject(new i(o.InvaildArgument,"invalid dimension"));!c!=!this.config.mirror&&(this.emit(he,"mirror",c),this.config.mirror=c),s&&s!==this.optimizationMode&&(this.config.optimizationMode=s,this.emit(he,"optimizationMode"));var u=!1;if(r&&this.config.dimension!==r&&(this.config.dimension=r,u=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),u=!0),a&&this.maxBitrate!==a&&(u=!0),!u)return Promise.resolve();var d=Qt({frameRate:this.config.frameRate},Ne(this.config.dimension)),p=this.getMediaStreamTrack();return null==p?void 0:p.applyConstraints(d).then((function(){var e,r=null===(e=t.getMediaStreamTrack())||void 0===e?void 0:e.getSettings(),n=r.width,i=r.height;t.maxBitrate=Vt(n,i,t.config.frameRate,a),console.log(n,i,d,t.maxBitrate),t.emit(he,"republish",t)})).catch((function(e){var r=l(e);throw $t.error("videoTrack ".concat(t.getTrackId()," setEncoderConfiguration error"),r),r}))}},{key:"getCurrentFrameData",value:function(){return $t.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:pt(zt.getElement(this)[0])}},{key:"play",value:function(t,r){return $t.info("local video play"),Kt(e,"play",this)([t,r])}}])}(),er=function(){function e(t,r){return C(this,e),Jt(this,e,[t,r])}return U(e,Xt),L(e,[{key:"setVolume",value:function(e){$t.info("setVolume",e),this.isClosed||zt.getElement(this)[0]&&(zt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if($t.info("getVolume"),!this.isClosed)return zt.getElement(this)[0]?zt.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:dt(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return $t.info("local audio play"),Kt(e,"play",this)([])}}])}(),tr=function(){function e(t,r){var n;return C(this,e),(n=Jt(this,e,[t,r.deviceId,r])).setSource(z.CAMERA),n}return U(e,Zt),L(e)}(),rr=function(){function e(t,r){var n;return C(this,e),(n=Jt(this,e,[t,(r||{}).deviceId])).config=r,n.setSource(K.MIC),n.analyser=n.audioContext.createAnalyser(),n}return U(e,er),L(e,[{key:"setVolume",value:function(e){$t.info("setVolume",e),this.isClosed||zt.getElement(this)[0]&&(zt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if($t.info("getVolume"),!this.isClosed)return zt.getElement(this)[0]?zt.getElement(this)[0].volume:void 0}}])}(),nr=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,l,d,p;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={AEC:!0,AGC:!0,ANS:!0},i=(n=t||r).AEC,o=void 0===i||i,a=n.AGC,s=void 0===a||a,c=n.ANS,l=void 0===c||c,e.prev=2,e.next=5,Ge({video:!1,audio:{deviceId:null==t?void 0:t.deviceId,source:K.MIC,AEC:o,AGC:s,ANS:l}});case 5:return d=e.sent,p=d.getAudioTracks()[0],$t.info("MicrophoneAudioTrack created"),e.abrupt("return",new rr(p,Object.assign({},t,{AEC:o,AGC:s,ANS:l})));case 11:throw e.prev=11,e.t0=e.catch(2),u(e.t0);case 14:case"end":return e.stop()}}),e,null,[[2,11]])})));return function(t){return e.apply(this,arguments)}}(),ir=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,d;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.deviceId,n=t.facingMode,i=t.dimension,o=void 0===i?"VD_640x480":i,a=t.optimizationMode,s=void 0===a?"balanced":a,c=Math.min(30,t.frameRate||15),e.prev=2,e.next=5,Ge({video:{deviceId:r,source:z.CAMERA,frameRate:c,dimension:o,facingMode:n},audio:!1});case 5:return u=e.sent,d=u.getVideoTracks()[0],$t.info("CameraVideoTrack created"),e.abrupt("return",new tr(d,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s})));case 11:throw e.prev=11,e.t0=e.catch(2),l(e.t0);case 14:case"end":return e.stop()}}),e,null,[[2,11]])})));return function(t){return e.apply(this,arguments)}}(),or=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,l;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.displaySurface,n=void 0===r?"monitor":r,i=t.dimension,o=void 0===i?"VD_1920x1080":i,a=t.optimizationMode,s=void 0===a?"detail":a,c=Math.min(t.frameRate||5,30),e.prev=2,e.next=5,Ge({video:{source:z.SCREENCAST,displaySurface:n,frameRate:c,dimension:o},audio:!1});case 5:return u=e.sent,(l=new Zt(u.getVideoTracks()[0],null,Object.assign({},t,{frameRate:c,dimension:o,optimizationMode:s}))).setSource(z.SCREENCAST),$t.info("ScreenVideoTrack created"),e.abrupt("return",[l]);case 12:throw e.prev=12,e.t0=e.catch(2),b(e.t0);case 15:case"end":return e.stop()}}),e,null,[[2,12]])})));return function(t){return e.apply(this,arguments)}}(),ar=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c,u,d,p,f,v,h,m,y,g,b,S,k,P,w;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Math.min(t.frameRate||15,30),i=t.deviceId,o=t.facingMode,a=t.dimension,s=void 0===a?"VD_640x480":a,c=t.optimizationMode,u=void 0===c?"balanced":c,d={AEC:!0,AGC:!0,ANS:!0},f=(p=r||d).AEC,v=void 0===f||f,h=p.AGC,m=void 0===h||h,y=p.ANS,g=void 0===y||y,e.prev=4,e.next=7,Ge({video:{deviceId:i,source:z.CAMERA,frameRate:n,dimension:s,facingMode:o},audio:{deviceId:null==r?void 0:r.deviceId,source:K.MIC,AEC:v,AGC:m,ANS:g}});case 7:return b=e.sent,S=b.getVideoTracks()[0],k=b.getAudioTracks()[0],$t.info("CameraVideoTrack and MicrophoneTrack created"),P=new tr(S,Object.assign({},t,{frameRate:n,dimension:s,optimizationMode:u})),w=new rr(k,Object.assign({},Object.assign({},r,{AEC:v,AGC:m,ANS:g}))),e.abrupt("return",[P,w]);case 16:throw e.prev=16,e.t0=e.catch(4),l(e.t0);case 19:case"end":return e.stop()}}),e,null,[[4,16]])})));return function(t,r){return e.apply(this,arguments)}}(),sr=function(){var e=M(se.mark((function e(t){var r,n,a,s,c,u,l,d;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=(r=t||{}).mediaStreamTrack,a=r.dimension,s=void 0===a?"VD_640x480":a,c=r.optimizationMode,u=void 0===c?"balanced":c,l=Math.min(t.frameRate||15,30),n instanceof MediaStreamTrack&&"video"===n.kind){e.next=4;break}throw new i(o.InvaildArgument,"missing video mediaStreamTrack");case 4:return(d=new Zt(n,null,Object.assign({},t,{frameRate:l,dimension:s,optimizationMode:u}))).setSource(z.CAMERA),e.abrupt("return",d);case 7:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),cr=function(){var e=M(se.mark((function e(t){var r,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if((r=(t||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===r.kind){e.next=3;break}throw new i(o.InvaildArgument,"missing audio mediaStreamTrack");case 3:return(n=new er(r)).setSource(K.MIC),e.abrupt("return",n);case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function ur(e,t,r,n){var i=Ue(F(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function lr(e,t,r){return t=F(t),N(e,dr()?Reflect.construct(t,r||[],F(e).constructor):t.apply(e,r))}function dr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(dr=function(){return!!e})()}var pr,fr=t().log,vr=gt(),hr=function(){function e(t,r,n){var i;return C(this,e),i=lr(this,e,[t,n]),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.userId=r,i}return U(e,Tt),L(e,[{key:"getUserId",value:function(){return fr.info("getUserId"),this.userId}},{key:"onFirstFrame",value:function(){this.emit("first-frame-decoded")}},{key:"attachSubscription",value:function(e){this.subscription&&this.subscription.off("audio-first-frame",this.onFirstFrame),this.subscription=e,null==e||e.on("audio-first-frame",this.onFirstFrame)}}])}(),mr=function(){function e(t,r,n){var i;return C(this,e),i=lr(this,e,[t,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return U(e,hr),L(e,[{key:"getMediaStreamTrack",value:function(){return Oe.audioSFU?lt(this.sfuStream):ur(e,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){fr.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){fr.info("setVolume",e),vr.getElement(this)[0]&&(vr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(fr.info("getVolume"),vr.getElement(this)[0])return vr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(e){var t=this;return fr.info("setSpeaker",e),new Promise((function(r,n){var a,s=vr.getElement(t)[0];s||n(new i(o.InvaildState,"please playout audio first")),s.setSinkId||n(new i(o.SpeakerSetNotSupported)),null===(a=s.setSinkId)||void 0===a||a.call(s,e).then((function(){t.deviceId=e,r()})).catch((function(e){n(u(e))}))}))}},{key:"getVolumeLevel",value:function(){return dt(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return fr.info("remote audio play"),ur(e,"innnerPlay",this,3)([{}])}}])}(),yr=function(){function e(t,r){return C(this,e),lr(this,e,[t,r])}return U(e,hr),L(e,[{key:"play",value:function(t,r){return fr.info("remote video play"),ur(e,"innnerPlay",this,3)([{element:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(fr.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&ur(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return fr.info("getCurrentFrameData"),this.isPlaying?pt(vr.getElement(this)[0]):null}}])}();!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(pr||(pr={}));var gr=S({nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"uint32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}}}),br=gr.lookupType("signal_msg.Response"),Sr=gr.lookupType("signal_msg.BatchNotification"),kr=gr.lookupType("signal_msg.MediaMessage"),Pr=gr.lookupType("signal_msg.StreamNotification");gr.lookupType("signal_msg.ProgressNotification");var wr=gr.lookupType("signal_msg.ServerFailoverNotification"),Or=gr.lookupType("signal_msg.PublishRequest"),Tr=gr.lookupType("signal_msg.SoacRequest"),Er=gr.lookupType("signal_msg.UnpublishRequest"),Ir=gr.lookupType("signal_msg.StreamControlRequest"),Rr=gr.lookupType("signal_msg.SubscribeRequest"),Ar=gr.lookupType("signal_msg.SetStreamPropertiesRequest"),_r=gr.lookupType("signal_msg.UnsubscribeRequest"),Mr=gr.lookupType("signal_msg.SubscriptionControlRequest"),Cr=gr.lookupType("signal_msg.CreatePeerConnectionRequest"),Dr=gr.lookupType("signal_msg.ClosePeerConnectionRequest"),xr=gr.lookupType("signal_msg.BatchPublishRequest"),jr=gr.lookupType("signal_msg.BatchUnpublishRequest"),Lr=gr.lookupType("signal_msg.BatchSubscribeRequest"),Nr=gr.lookupType("signal_msg.BatchUnsubscribeRequest"),Fr=gr.lookupType("signal_msg.JoinGroupRequest"),Gr=gr.lookupType("signal_msg.SetGroupPropertiesRequest"),Ur=gr.lookupType("signal_msg.DismissGroupRequest"),Vr=gr.lookupType("signal_msg.LeaveGroupRequest"),Br=gr.lookupType("signal_msg.SyncDataRequest"),qr=gr.lookupType("signal_msg.SyncDataByIdsRequest"),Hr=gr.lookupType("signal_msg.GroupChangeLog"),Yr=gr.lookupType("signal_msg.GroupListChangeLog"),Qr=gr.lookupType("signal_msg.SetParticipantPropertiesRequest"),Jr=gr.lookupType("signal_msg.QueryStreamsVerRequest"),Wr=gr.lookupType("signal_msg.QueryStreamsRequest");function Kr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Kr=function(){return!!e})()}var zr=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,Kr()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"loggedIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"rpcId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=t,r.rpcId=0,r.reporter=t.reporter,r.handleBatchNotifyEvent=r.handleBatchNotifyEvent.bind(r),r.handleNotifyEvent=r.handleNotifyEvent.bind(r),r.handleConnectionStateChangeEvent=r.handleConnectionStateChangeEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.handleUserEvent=r.handleUserEvent.bind(r),r.channel.on("connection-state-change",r.handleConnectionStateChangeEvent),r.channel.on("sync",r.handleSyncEvent),r.channel.on("batch-notify",r.handleBatchNotifyEvent),r.channel.on("notify",r.handleNotifyEvent),r.channel.on("user",r.handleUserEvent),r}return U(e,c),L(e,[{key:"join",value:function(e,t){return this.channel.join(e,t).then((function(e){return{joinResponse:e.joinResponse,iceConfig:e.iceConfig}}))}},{key:"leave",value:function(){return this.channel.leave()}},{key:"handleUserEvent",value:function(e,t){this.emit("user",e,t)}},{key:"handleSyncEvent",value:function(e){this.emit("sync",e)}},{key:"handleConnectionStateChangeEvent",value:function(e,t,r){this.emit("connection-state-change",e,t,r)}},{key:"handleNotifyEvent",value:function(e,t){"stream"===e?this.emit("stream",Pr.decode(t)):"serverFailover"===e?this.emit("serverFailover",wr.decode(t)):"media-message"===e?this.emit("media-message",kr.decode(t)):"group"===e?this.emit("group",Hr.decode(t)):"group-list"===e&&this.emit("group-list",Yr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;Sr.decode(e).notificationItem.forEach((function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)}))}},{key:"createPeerConnection",value:function(e){var t=Cr.encode(e).finish();return this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=Dr.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=Lr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=Gr.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=Nr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=xr.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=jr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=Or.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){var t=Qr.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=Tr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=Er.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=Ir.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=Ar.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=Rr.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=_r.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=Mr.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=Jr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=Wr.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=Fr.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=Vr.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=Ur.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=Br.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=qr.encode(e).finish();return this.rpc("sync-data-by-ids",t,e).then((function(e){return e.syncDataByIdsResponse}))}},{key:"observeAllGroups",value:function(){return this.rpc("observe-all-groups",null).then((function(e){return e.observeAllGroupsResponse}))}},{key:"unobserveAllGroups",value:function(){return this.rpc("unobserve-all-groups",null).then((function(e){return e.unobserveAllGroupsResponse}))}},{key:"rpc",value:function(e,t){var r=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(i,o){var a=r.rpcId++;r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," param====> ").concat(JSON.stringify(n||""))),r.channel.signaling.rpc(e,t,n).then((function(t){var n=br.decode(t);n.code===pr.Result.Ok?(r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," result====> ").concat(JSON.stringify(n))),i(n)):(r.reporter.log.debug("rtc rpcId ".concat(a,":").concat(e," error====> ").concat(JSON.stringify(n))),o(n))}))}))}}])}();function $r(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return($r=function(){return!!e})()}var Xr=function(){function e(){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,$r()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"timer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t().statsConfig;return r.interval=(null==a?void 0:a.statsIntervalMs)||2e3,r.start(),r}return U(e,c),L(e,[{key:"start",value:function(){var e=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=d((function(){e.makeReport()}),this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(v(this.timer,"interval"),this.timer=null)}}])}();function Zr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function en(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Zr(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Zr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function tn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return rn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?rn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function rn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function nn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(nn=function(){return!!e})()}var on={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},an={totalFramesSent:0,totalBytesSent:0,totalPacketsLost:0,totalPacketsSent:0,totalFramesEncoded:0,timestamp:0,totalQpSum:0,maxSendFrameHeight:0,maxSendFrameWidth:0,captureFrameHeight:0,captureFrameWidth:0,captureFramesPerSecond:0,sendFramesPerSecond:0,availableOutgoingBitrate:0,targetBitrate:0,roundTripTime:0,encodeFramesPerSecond:0,totalEncodedTime:0,trackStats:new Map},sn=function(){function t(e){var r,n,i,o;C(this,t),n=this,i=F(i=t),r=N(n,nn()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"videoSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSendReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"bweReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastVideoSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"lastAudioSendInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.connection=e.connection,r.pc=e.connection.pc;var a=e.tracks.filter((function(e){return"video"===e.trackMediaType}))[0];return r.source=null==a?void 0:a.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},an),r.videoSendReport={attr_bitrate:0,attr_capture_frames:0,attr_enc_average_elapsed_ms:0,attr_encode_qp_sim:"",attr_encoded_framerate_sim:"",attr_resolution_sim:"",attr_stream_options:"",attr_duration_ms:0},r.lastAudioSendInfo=Object.assign({},on),r.audioSendReport={attr_duration_ms:0,attr_bitrate:0},r.bweReport={attr_rtt:0,attr_lossrate:0,attr_reported_bitrate:0,attr_duration_ms:0},r}return U(t,Xr),L(t,[{key:"extractVideoMetrics",value:function(t){var r=this,n=Object.assign({source:this.source,trackStats:[]},an,this.connection.peerConnectionStats);if(n.timestamp=Date.now(),this.track){var i=this.track.getMediaStreamTrack().getSettings(),o=i.width,a=i.height,s=i.frameRate;n.captureFramesPerSecond=s===1/0?0:s||0,n.captureFrameWidth=o||0,n.captureFrameHeight=a||0}var c=new Map,u=Qe(n,this.lastVideoSendInfo);return t.forEach((function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var i=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(i.sendFrameWidth=t.frameWidth||0,i.sendFrameHeight=t.frameHeight||0,i.framesSent=t.framesSent||0,i.framesEncoded=t.framesEncoded||0,i.targetBitrate=t.targetBitrate||0,i.qpSum=t.qpSum||0,i.bytesSent=t.bytesSent||0,i.packetsSent=t.packetsSent||0,i.packetsSentForLost=i.packetsSent||0,i.sentTimestamp=t.timestamp||0,i.totalEncodeTime=t.totalEncodeTime||0,i.keyFramesEncoded=t.keyFramesEncoded||0,i.firCount=t.firCount||0,i.pliCount=t.pliCount||0,i.retransmittedBytesSent=t.retransmittedBytesSent||0,i.retransmittedPacketsSent=t.retransmittedPacketsSent||0,i.qualityLimitationReason=t.qualityLimitationReason||"",i.sendFramesPerSecond=t.framesPerSecond||0,i.sendFrameWidth>n.maxSendFrameWidth){if(n.maxSendFrameWidth=i.sendFrameWidth,!i.sendFramesPerSecond&&o){var a=We(i.framesSent||i.framesEncoded,o.framesSent||o.framesEncoded);i.sendFramesPerSecond=Math.round(a/u)}if(i.framesEncoded){var s=We(i.framesEncoded,null==o?void 0:o.framesEncoded);n.encodeFramesPerSecond=Math.round(s/u)}n.sendFramesPerSecond=i.sendFramesPerSecond}c.set(t.ssrc,i),n.targetBitrate=i.targetBitrate,n.totalBytesSent+=i.bytesSent,n.totalPacketsSent+=i.packetsSent,n.totalEncodedTime+=i.totalEncodeTime,n.totalFramesEncoded+=i.framesEncoded,n.totalFramesSent+=i.framesSent,n.totalQpSum+=i.qpSum,n.maxSendFrameHeight=Math.max(i.sendFrameHeight,n.maxSendFrameHeight),c.set(t.ssrc,i)}else if(/track/i.test(t.type)&&!1===t.remoteSource){if(e.isSafari()){var l=c.get(t.ssrc)||{};l.sendFrameHeight>0||(l.sendFrameWidth=t.frameWidth||0,l.sendFrameHeight=t.frameHeight||0),l.framesSent=t.framesSent||0,l.totalEncodeTime=t.totalEncodeTime||0,c.set(t.ssrc,l),n.totalFramesEncoded+=l.framesEncoded,n.totalEncodedTime+=l.totalEncodeTime,n.totalFramesSent+=l.framesSent,c.set(t.ssrc,l)}}else if(/remote-inbound-rtp/i.test(t.type)){var d=c.get(t.ssrc)||{},p=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};d.packetsLost=t.packetsLost||0,d.lostTimestamp=t.timestamp,n.totalPacketsLost+=d.packetsLost,d.packetsLost===(p.packetsLost||0)&&(d.packetsSentForLost=p.packetsSentForLost||0,d.lostTimestamp=p.lostTimestamp||0),c.set(t.ssrc,d)}})),n.trackStats=c,n}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],n=tn(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=Et(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=We(a.framesSent,s.framesSent),u=We(a.framesEncoded,s.framesEncoded),l=We(a.keyFramesEncoded,s.keyFramesEncoded),d=We(a.retransmittedBytesSent,s.retransmittedBytesSent),p=We(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=We(a.firCount,s.firCount),v=We(a.pliCount,s.pliCount),h=We(a.packetsSent,s.packetsSent),m=We(a.packetsSentForLost,s.packetsSentForLost),y=We(a.lostTimestamp,s.lostTimestamp),g=We(a.sentTimestamp,s.sentTimestamp),b=We(a.packetsLost,s.packetsLost),S=We(a.totalEncodeTime,s.totalEncodeTime),k=We(a.qpSum,s.qpSum),P=a.qualityLimitationReason,w=a.sendFrameWidth,O=en(en({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:w,qualityLimitationReason:P},a),{},{deltaQbSum:k,deltaPacketsSent:h,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:y,deltaFramesEncoded:u,deltaKeyFramesEncoded:l,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:v,deltaTimestampForSent:g,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:p});r.push(O)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,l=We(e.timestamp,this.lastVideoSendInfo.timestamp),d=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var v=f.deltaFramesEncoded||f.deltaFramesSent;d&&(d=0===v),s.attr_encoded_framerate_sim.push(ce({},p,Math.round(1e3*v/l))),s.attr_encode_qp_sim.push(ce({},p,Math.round((f.deltaQbSum||0)/(v||Number.EPSILON))));var h=f.deltaTimestampForLost,m=f.deltaTimestampForSent,y=f.deltaPacketsLost,g=f.deltaPacketsSentForLost;if(y&&g&&h&&m){var b=y/h/(g/m);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,k=Object.entries(s);S<k.length;S++){var P=Et(k[S],2),w=P[0],O=P[1];t[w]=O.length?JSON.stringify(O):""}var T=0,E=We(o,this.lastVideoSendInfo.totalFramesEncoded),I=We(a,this.lastVideoSendInfo.totalEncodedTime);E&&I&&(T=Math.round(1e3*I/E));var R=We(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=l,t.attr_bitrate=l>0?Math.min(Math.round(8*R*1e3/l),2e7):0,t.attr_enc_average_elapsed_ms=T,this.videoSendReport=t,d&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:l,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},on,this.connection.peerConnectionStats);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(We(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*We(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/We(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"getStats",value:function(){var e,t,r=this,n=this.tranceiver,a=this.pc;if(!a||null==n||null===(e=n.sender)||void 0===e||!e.track)return Promise.resolve({});if(null==a||!a.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");return null===(t=this.pc.getStats(n.sender.track))||void 0===t?void 0:t.then((function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e)}}))}}])}();function cn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return un(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?un(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function un(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ln(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ln=function(){return!!e})()}var dn={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},pn={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},fn=function(){function e(t){var r,n,i,o,a;C(this,e),i=this,o=F(o=e),n=N(i,ln()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=t.connection,c=t.transceiver,u=t.uid,l=t.stream,p=t.transceivers;return n.connection=s,n.pc=s.pc,n.tranceiver=c,n.tranceivers=p,n.firstReportTimer=d((function(){n.getStats().then((function(e){n.makeFirstReport(e)}))}),400,"interval"),n.source="mcu"!==u&&(null===(r=l.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},pn),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},dn),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return U(e,Xr),L(e,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},dn,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},dn,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=cn(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},pn,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(We(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=We(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=We(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=We(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,l=t.packetsReceivedForLost,d=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=We(e.timestamp,i);if(e.bytesReceived-u>=0){var v=We(e.packetsLost,a),h=We(e.packetsReceivedForLost,l),m=0;try{m=Math.round(v/h*255)}catch(e){m=0}isNaN(m)&&(m=0);var y=We(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*y/f),attr_dec_frames:y,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:We(e.framesDropped,c),attr_fir_count:We(e.firCount,r),attr_freeze_count:We(e.freezeCount,o),attr_pli_count:We(e.pliCount,n),attr_retx_bytes:We(e.retransmittedBytesReceived,d),attr_retx_packets:We(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*We(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:y,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(e){var t=this.firstReportFlag,r=t.audioFirstFrame,n=t.audioFirstPacket,i=t.videoFirstPacket,o=e.audioMetrics,a=e.videoMetrics;if(o&&a){if((r||-1===(null==o?void 0:o.decodingNormal))&&n&&i)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(o){if((r||-1===(null==o?void 0:o.decodingNormal))&&n)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a&&i)return void(this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=o&&o.packetsReceived&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==o?void 0:o.decodingNormal)>0&&!r&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=a&&a.packetsReceived&&!i&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var e,t=this,r=this.tranceiver,n=this.tranceivers,a=this.pc;if(!(a&&(null!=n&&n.length||null!=r&&r.receiver.track)))return Promise.resolve({});if(null==a||!a.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var s=n.map((function(e){return e.receiver.track})).filter((function(e){return!!e}));return Promise.all(s.map((function(e){return a.getStats(e)}))).then((function(e){return{audioMetrics:t.extractMultipleAudioMetrics(e)}}))}return null!=r&&null!==(e=r.receiver)&&void 0!==e&&e.track?a.getStats(r.receiver.track).then((function(e){return{videoMetrics:t.source?t.extractVideoMetrics(e):void 0,audioMetrics:t.source?void 0:t.extractAudioMetrics(e)}})):void 0}},{key:"stop",value:function(){var t,r,n;(t="stop",r=this,"function"==typeof(n=Ue(F(e.prototype),t,r))?function(e){return n.apply(r,e)}:n)([]),this.firstReportTimer&&(v(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();function vn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return hn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?hn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function hn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function mn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function yn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?mn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):mn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function gn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(gn=function(){return!!e})()}var bn=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,gn()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t.connection,s=t.stream,c=t.uid,u=t.resolutionInfo,l=t.userConfigResolution;return r.connection=a,r.resolutionInfo=u,r.userConfigResolution=l,r.signaling=a.signaling,r.stream=s,r.uid=c,r.reporter=a.reporter,r.connection.once("ended",(function(){r.clear()})),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=re.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return U(e,c),L(e,[{key:"handleStreamAdd",value:function(e,t){var r,n=this,i=function(){n.reporter.trace.subscribe({init:!1,capabilities:n.stream.media,remoteStreamId:n.stream.id,remoteUserId:n.uid,sessionId:n.id,elapse:Date.now()-n.startTime,resolutionInfo:n.resolutionInfo}),n.startTime=Date.now()};if(Oe.audioSFU&&"audio"===e.kind){var o,a=null===(o=this.transceivers)||void 0===o?void 0:o.map((function(e){var t;return null===(t=e.receiver)||void 0===t||null===(t=t.track)||void 0===t?void 0:t.id}));null!=a&&a.includes(e.id)&&!this._stream&&(this._stream=t,i())}else e.id===(null===(r=this.transceiver)||void 0===r||null===(r=r.receiver)||void 0===r||null===(r=r.track)||void 0===r?void 0:r.id)&&(this._stream=new MediaStream([e]),i())}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===re.Processing)return this.clear(),this.signaling.unsubscribe({subscriptionId:this.id}).catch((function(t){e.reporter.log.warn("negative ack for unsubscribing, ".concat(t))}))}},{key:"mute",value:function(e){return this.signaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.signaling.subscriptionControl({subscriptionId:this.id,operation:"play",track:e})}},{key:"applyOptions",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=Sn(this.stream,e),t||(this.userConfigResolution=e),this.signaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==re.End&&(this.reset(),this.state=re.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new fn(this),this.onMonitor()}},{key:"addTransceivers",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.transceivers=e,this.monitor=new fn(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:-1,remoteUserId:this.uid})}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=Qe(r,o),s=We(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=Qe(n,d),f=We(n.bytesReceived,d.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(We(null==n?void 0:n.framesDecoded,d.framesDecoded)/p),receiveFrameRate:Math.round(We(null==n?void 0:n.framesReceived,d.framesReceived)/p),receiveFramesDropped:We(null==n?void 0:n.framesDropped,d.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},h=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),m=(null===(l=this.stream.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.source)===z.CAMERA&&f>5e3&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&m?h&&v.receiveFramesDropped>0&&!Oe.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=m),this.videoStatsMap.set(t,v)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(yn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(yn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-first-packet",(function(){e.reporter.trace.audioFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("audio-first-frame",(function(){e.emit("audio-first-frame")}))):(this.monitor.on("video-first-packet",(function(){e.reporter.trace.videoFirstPacket({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid})})),this.monitor.on("video-recv-stream",(function(t){e.reporter.metric.videoRecvStream(yn({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(),Sn=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=Dt(n);return Ct(i,Ee(e))}return t},kn=function(e){var t,r={audio:[],video:[]},n=vn(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo;if(!a){var c=Pn(o,s),u=c.audio,l=c.video;if(u){var d=yn(yn({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:xn()}]});Oe.audioSFU&&(d.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:xn()}}))),r.audio.push(d)}else if(l){var p,f;r.video.push(yn(yn({},l),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:xn(),rtxSsrc:xn()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},Pn=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:Sn(e,t)}}return a},wn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=[],o={},t.forEach((function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var u=new bn(yn(yn({},r),{},{uid:s,userConfigResolution:c,resolutionInfo:c&&Sn(n,c),stream:n}));o[n.id]=u}})),s=new Promise((function(e,r){a=function(){var a=M(se.mark((function a(){var s;return se.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return s=kn(t),a.next=3,Vn(n,s,o);case 3:n.signaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:Oe.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:s}).then(function(){var r=M(se.mark((function r(n){var a,s,c,u,l;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=4;break}return i.forEach((function(e){e.error=e.error||Ie(e.stream,s)})),r.abrupt("return",e(i));case 4:c=vn(a),r.prev=5,l=se.mark((function e(){var r,n,a,s,c,l;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],l=t.findIndex((function(e){return e.stream.id===s.id})),"ok"===a&&c?(c.id=n,i[l].id=n,i[l].subscription=c):"ok"!==a&&(i[l].error=Ie(c.stream,a));case 4:case"end":return e.stop()}}),e)})),c.s();case 8:if((u=c.n()).done){r.next=12;break}return r.delegateYield(l(),"t0",10);case 10:r.next=8;break;case 12:r.next=17;break;case 14:r.prev=14,r.t1=r.catch(5),c.e(r.t1);case 17:return r.prev=17,c.f(),r.finish(17);case 20:e(i);case 21:case"end":return r.stop()}}),r,null,[[5,14,17,20]])})));return function(e){return r.apply(this,arguments)}}()).catch(r);case 4:case"end":return a.stop()}}),a)})));return function(){return a.apply(this,arguments)}}()})),n.addTask(a),e.abrupt("return",s);case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),On=function(){var e=M(se.mark((function e(t,r){var n,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,o=new Promise((function(e,r){n=function(){var n=M(se.mark((function n(){var o,a;return se.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.audio)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return!(null===(t=e.stream)||void 0===t||null===(t=t.media)||void 0===t||!t.video)})).map((function(e){return e.id})),n.next=4,Bn(i,t);case 4:i.signaling.batchUnSubscribe({connectionId:i.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",o);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function Tn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function En(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Tn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Tn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function In(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Rn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Rn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Rn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var An={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},_n=0,Mn=0,Cn=0,Dn=new Set,xn=function(){if(0==_n||0==Mn)return 0;var e=Math.min(Mn+1,1e4);do{var t=_n+(Mn&Cn++);if(0!=t&&!Dn.has(t))return t}while(--e>0);return 0},jn=function(t,r){var n,i;if((null===(n=t.rids)||void 0===n?void 0:n.length)>1)return e.isFirefox()&&(r=Un(r)),r.rids=null===(i=t.rids)||void 0===i?void 0:i.map((function(e){return{direction:"recv",id:e.id}})),r.simulcast={dir1:"recv",list1:t.simulcast.list1},r},Ln=function(){var e=M(se.mark((function e(t){var r,n,i,o,a,s,c;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.connection,n=t.transceiver,i=r.remoteSDP,o=r.pc,e.next=4,o.createOffer();case 4:return a=e.sent,e.next=7,o.setLocalDescription(a);case 7:return r.localSDP=R.parse(a.sdp),s=r.localSDP.media.find((function(e){return e.mid==n.mid})),c=i.media.find((function(e){return e.mid==n.mid})),jn(s,c),e.next=13,o.setRemoteDescription({type:"answer",sdp:R.write(i)});case 13:r.remoteSDP=i;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),Nn=function(){var t=M(se.mark((function t(r,n){var i,o,a,s,c,u,l,d,p,f;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=r.pc,o=r.idToTransceiverMap,a=r.remoteSDP,s=new MediaStream(n.map((function(e){return e.getMediaStreamTrack()}))),c=n.map((function(e){var t={direction:"sendonly"};if(e instanceof Zt){var n=Ht(e).encodings;t.sendEncodings=n.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var i=r.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Zt&&i.sender.setParameters){var a=e.optimizationMode,s=i.sender.getParameters();s.degradationPreference=An[a]||"balanced",i.sender.setParameters(s)}return o.set(e.getTrackId(),i),i})),t.next=5,i.createOffer();case 5:return u=t.sent,l=R.parse(u.sdp),t.next=9,i.setLocalDescription(u);case 9:r.localSDP=l,a.groups[0].mids=r.localSDP.groups[0].mids,d=In(c),t.prev=12,f=se.mark((function t(){var r,n,i,o;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=p.value,n=a.media.find((function(e){return e.type===r.sender.track.kind})),e.isFirefox()&&"video"===n.type&&(delete n.rids,delete n.simulcast),i=En(En({},n),{},{ext:ke(n.ext),mid:r.mid}),o=l.media.find((function(e){return e.mid==r.mid})),jn(o,i),a.media.push(i);case 7:case"end":return t.stop()}}),t)})),d.s();case 15:if((p=d.n()).done){t.next=19;break}return t.delegateYield(f(),"t0",17);case 17:t.next=15;break;case 19:t.next=24;break;case 21:t.prev=21,t.t1=t.catch(12),d.e(t.t1);case 24:return t.prev=24,d.f(),t.finish(24);case 27:return t.next=29,i.setRemoteDescription({type:"answer",sdp:R.write(a)});case 29:return r.remoteSDP=a,t.abrupt("return",{localSDP:r.localSDP,stream:s});case 31:case"end":return t.stop()}}),t,null,[[12,21,24,27]])})));return function(e,r){return t.apply(this,arguments)}}(),Fn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=t.pc,i=t.remoteSDP,r.map((function(e){return e.transceiver})).forEach((function(e){if(e){n.removeTrack(e.sender);var t=i.media.find((function(t){return t.mid==(null==e?void 0:e.mid)}));e.direction="inactive",t.direction="inactive"}})),e.next=5,n.createOffer();case 5:return o=e.sent,a=R.parse(o.sdp),e.next=9,n.setLocalDescription(o);case 9:return t.localSDP=a,i.groups[0].mids=a.groups[0].mids,t.remoteSDP=i,e.next=14,n.setRemoteDescription({type:"answer",sdp:R.write(i)});case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Gn=function(e,t,r){var n=e.ssrc,i=e.rtxSsrc;!function(e){e.ssrc&&Dn.add(e.ssrc),e.rtxSsrc&&Dn.add(e.rtxSsrc)}(e),t.ssrcGroups=[],i&&t.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(i)}),t.ssrcs=[],[n,i].filter((function(e){return void 0!==e})).forEach((function(e){t.ssrcs.push({attribute:"msid",value:"".concat(r," v").concat(n),id:e},{attribute:"cname",value:g(),id:e})}))},Un=function(e){var t;return null!=e&&null!==(t=e.ext)&&void 0!==t&&t.some((function(e){return e.uri.includes("rtp-stream-id")}))||e.ext.push({value:8,uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id"},{value:9,uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"}),e},Vn=function(){var e=M(se.mark((function e(t,r,n){var i,o,a,s,c,u,l,d,p,f,v,h,m,y,g,b,S,k,P,w,O,T,E,I,A,_,M,C;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(a=t.pc,s=t.idToTransceiverMap,c=t.remoteSDP,u=t.idToTransceiversMap,l=c.media.find((function(e){return"video"===e.type})),d=c.media.find((function(e){return"audio"===e.type})),p=null===(i=l.ssrcs)||void 0===i?void 0:i.find((function(e){return"msid"===e.attribute})).value.split(" ")[0],null!==(o=r.audio)&&void 0!==o&&o[0])if(v=null===(f=r.audio)||void 0===f?void 0:f[0],h=v.from,Oe.audioSFU){if(u.get(h)){m=In(u.get(h));try{for(m.s();!(y=m.n()).done;)y.value.direction="recvonly"}catch(e){m.e(e)}finally{m.f()}g=c.media.filter((function(e){return"audio"===e.type})),b=In(g);try{for(b.s();!(S=b.n()).done;)S.value.direction="sendonly"}catch(e){b.e(e)}finally{b.f()}}else t.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return t.pc.addTransceiver("audio",{direction:"recvonly"})})),u.set(h,t.mcuAudioTranceivers);n[h].addTransceivers(u.get(h))}else s.get(h)||s.set(h,t.mcuAudioTranceiver),s.get(h).direction="recvonly",d.direction="sendonly",n[h].addTransceiver(s.get(h));k=In(r.video),e.prev=6,w=se.mark((function e(){var t,r,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=P.value,r=t.from,i=s.get(r)){e.next=7;break}s.set(r,a.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===i.direction){e.next=18;break}return i.direction="inactive",e.next=11,a.createOffer();case 11:return o=e.sent,e.next=14,a.setLocalDescription(o);case 14:return c.media.find((function(e){return e.mid==i.mid})).direction="inactive",e.next=18,a.setRemoteDescription({type:"answer",sdp:R.write(c)});case 18:s.get(r).direction="recvonly";case 19:n[r].addTransceiver(s.get(r));case 20:case"end":return e.stop()}}),e)})),k.s();case 9:if((P=k.n()).done){e.next=13;break}return e.delegateYield(w(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),k.e(e.t1);case 18:return e.prev=18,k.f(),e.finish(18);case 21:return e.next=23,a.createOffer();case 23:return O=e.sent,T=R.parse(O.sdp),c.groups[0].mids=T.groups[0].mids,e.next=28,a.setLocalDescription(O);case 28:t.localSDP=T,Oe.audioSFU&&r.audio[0]&&(E=r.audio[0],I=E.ssrcGroup,A=E.from,u.get(A).forEach((function(e,t){var r,n=null===(r=I[t])||void 0===r?void 0:r.ssrc,i=c.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=En(En({},d),{},{mid:e.mid}),c.media.push(i)),i.ssrcs=qn(n,p),i.direction="sendonly"}))),_=In(r.video),e.prev=31,C=se.mark((function e(){var t,r,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=M.value,r=t.from,i=t.subSsrcGroup,o=s.get(r),(a=c.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})))||((a=En({},l)).mid=o.mid,c.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,Gn(i,a,p);case 8:case"end":return e.stop()}}),e)})),_.s();case 34:if((M=_.n()).done){e.next=38;break}return e.delegateYield(C(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),_.e(e.t3);case 43:return e.prev=43,_.f(),e.finish(43);case 46:return t.remoteSDP=c,e.next=49,a.setRemoteDescription({type:"answer",sdp:R.write(c)});case 49:case"end":return e.stop()}}),e,null,[[6,15,18,21],[31,40,43,46]])})));return function(t,r,n){return e.apply(this,arguments)}}(),Bn=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c,u,l,d,p,f,v;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=t.pc,i=t.remoteSDP,o=[],a=In(r);try{for(a.s();!(s=a.n()).done;)c=s.value,u=c.transceiver,l=c.transceivers,u?o.push(u):l&&o.push.apply(o,ke(l))}catch(e){a.e(e)}finally{a.f()}return o.forEach((function(e){e.direction="inactive"})),e.next=7,n.createOffer();case 7:return d=e.sent,e.next=10,n.setLocalDescription(d);case 10:t.localSDP=R.parse(d.sdp),p=se.mark((function e(){var t;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=v[f],i.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),f=0,v=o;case 13:if(!(f<v.length)){e.next=18;break}return e.delegateYield(p(),"t0",15);case 15:f++,e.next=13;break;case 18:return t.remoteSDP=i,e.next=21,n.setRemoteDescription({type:"answer",sdp:R.write(i)});case 21:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),qn=function(e,t){return[{attribute:"msid",value:"".concat(t," v").concat(e),id:e},{attribute:"cname",value:g(),id:e}]},Hn=function(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"all",o=r.direction,a=r.remoteSDP,s=R.parse(t);"relay"===i&&s.media.forEach((function(e){e.candidates=e.candidates.filter((function(e){return k(e.ip)}))})),n&&(s=function(e,t){var r=t.media.find((function(e){return"audio"===e.type})),n=t.media.find((function(e){return"video"===e.type}));return e.media.forEach((function(t,i){var o=t.mid,a=t.ssrcGroups,s=void 0===a?[]:a,c=t.ssrcs,u=void 0===c?[]:c,l=t.rids,d=void 0===l?[]:l;"audio"===t.type?e.media[i]=En(En({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=En(En({},n),{},{mid:o,ssrcGroups:s,ssrcs:u}),d.length&&(e.media[i].rids=d,e.media[i].simulcast={dir1:"recv",list1:d.map((function(e){return"~".concat(e.id)})).join(";")}))})),e}(a,s));var c=s.media.find((function(e){return"video"===e.type}));if("uplink"===o&&e.isFirefox()&&Oe.simulcast&&(c.ext=c.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!c.ssrcs&&"downlink"===o){var u=xn(),l=s.msidSemantic.token;c.ssrcs=qn(u,l)}return r.remoteSDP=s,s},Yn=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=In(n);try{for(u.s();!(r=u.n()).done;){var l=r.value,d=l.config,p=l.payload,f=d.split(";");c[p]={};var v,h=In(f);try{for(h.s();!(v=h.n()).done;){var m=Et(v.value.split("="),2),y=m[0],g=m[1];c[p][y]=g}}catch(e){h.e(e)}finally{h.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var k=n.length-1;k>=0;k--){var P=n[k].payload;s.includes(P)&&n.splice(k,1)}for(var w=o.length-1;w>=0;w--)s.includes(o[w].payload)&&o.splice(w,1);for(var O=a.length-1;O>=0;O--)s.includes(a[O].payload)&&a.splice(O,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},Qn=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return Yn(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},Jn=function(e){var t=e.media.find((function(e){return"video"===e.type}));return Yn(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function Wn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Kn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Wn(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Wn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function zn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return $n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?$n(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function $n(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Xn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Xn=function(){return!!e})()}var Zn=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,Xn()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"tracks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mid",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"encodings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"feedbackIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var a=t.connection,s=t.uid,c=t.tracks,u=void 0===c?[]:c;return r.tracks=u,r.connection=a,r.signaling=a.signaling,r.uid=s,r.reporter=a.reporter,r.state=re.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),r.applyOptions=r.applyOptions.bind(r),r.applyOptions=$e(r.applyOptions,1e3,!1),u.forEach((function(e){e.on(he,r.handleTracEvent)})),r.encodings=Ht(u[0]).encodings,r.state=re.Processing,r.connection.once("ended",(function(){r.clear()})),r}return U(e,c),L(e,[{key:"stop",value:function(){var e=this;return this.state!==re.Processing?Promise.resolve():ti([this],{connection:this.connection}).catch((function(t){e.clear(),e.reporter.log.warn("negative ack for unpublish, ".concat(m(t)))}))}},{key:"mute",value:function(){if(this.tracks.length&&this.state===re.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!0,this.id),this.signaling.streamControl({streamId:this.id,operation:"pause",data:e})}}},{key:"unmute",value:function(){if(this.tracks.length&&this.state===re.Processing){var e=this.tracks[0].trackMediaType;return this.reporter.trace.localControl(e,!1,this.id),this.signaling.streamControl({streamId:this.id,operation:"play",data:e})}}},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0];this.addTransceiver(this.connection.idToTransceiverMap.get(t.getTrackId())),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.signaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this.connection,r=this.transceiver,n=e.getMediaStreamTrack().getSettings(),i=n.width,o=n.height,a=qt(i,o);this.signaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:a});var s=function(e,t){var r=Gt(e,t),n=function(n){var i=Et(Ut(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(St.LD),sd:n(St.SD),fhd:n(r)}}(i,o);t.addTask(M(se.mark((function e(){var t;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return console.log("scales",s),(t=r.sender.getParameters()).encodings.forEach((function(e){e.scaleResolutionDownBy=s[e.rid]})),e.abrupt("return",r.sender.setParameters(t).then((function(){console.log(r.sender.getParameters().encodings)})));case 4:case"end":return e.stop()}}),e)}))))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){Oe.republish?n.handleRepublish(t):n.stop().then((function(){n.connection.sessionManager.channel.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==re.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(he,e.handleTracEvent)})),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset(),this.state=re.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],n=r.index,i=r.bitrate;if(this.reporter.log.debug(e),!(n<this.feedbackIndex||this.state!==re.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask((function(){return new Promise((function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map((function(e){return e.rid})),l=zn(c.encodings);try{for(l.s();!(n=l.n()).done;){var d,p=n.value,f=zn(e);try{for(f.s();!(d=f.n()).done;){d.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){l.e(e)}finally{l.f()}if(console.log(c.encodings),s)return o.sender.setParameters(c).then((function(){return Ln(t).then(r)}));r()}))}))}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof Zt&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask((function(){var e=n.sender.getParameters();return e.degradationPreference=An[o]||"balanced",n.sender.setParameters(e),Ln(t)}))}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=re.Processing,this.feedbackIndex=-1,this.monitor=new sn(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;this.transceiver&&(null===(t=this.transceiver.sender.track)||void 0===t||t.stop(),this.transceiver.sender.replaceTrack(e))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,n=e.videoMetrics;if(r){var i,o=(null===(i=this.metricsMap.get(t))||void 0===i?void 0:i.audioMetrics)||{},a=Qe(r,o),s=We(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,l,d=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===d?[]:d,f=(null===(l=this.metricsMap.get(t))||void 0===l?void 0:l.videoMetrics)||{},v=Qe(n,f),h=We(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*h/v};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(Kn({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(Kn({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(Kn({sessionId:e.id},t))}))}}])}(),ei=function(){var e=M(se.mark((function e(t,r){var n,i,o,a,s,c=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=c.length>2&&void 0!==c[2]?c[2]:["common"],i={},e.next=4,Nn(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Zt){var c;i.video=i.video||[];var u=o.ssrcGroups,l=void 0===u?[]:u,d=Ht(e),p=d.encodings,f=d.resolutionLevel;p.length>1&&(l=p.map((function(){return{semantics:"FID",ssrcs:"".concat(xn()," ").concat(xn())}})));var v=l.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),h=p[p.length-1],m={trackId:e.getTrackId(),forwardOnly:e.source===z.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:v,source:e.source||z.CAMERA,streamParameters:{ssrc:null==v||null===(c=v[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(h.maxBitrate),resolution:{width:h.targetWidth,height:h.targetHeight},framerate:h.maxFramerate},ssrcParameters:v.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}}))};i.video.push(m)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),ti=function(){var e=M(se.mark((function e(t,r){var n,i;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new Promise((function(e,i){n=function(){var n=M(se.mark((function n(){var o,a;return se.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=t.filter((function(e){var t;return"audio"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),a=t.filter((function(e){var t;return"video"===(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.trackMediaType)})).map((function(e){return e.id})),n.next=4,Fn(r.connection,t);case 4:r.connection.signaling.batchUnPublish({connectionId:r.connection.id,audio:o,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(i);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ri=function(){return!!e})()}var ni={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},ii=function(){function t(e){var r,n,i,o;return C(this,t),n=this,i=F(i=t),r=N(n,ri()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},ni)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return U(t,Xr),L(t,[{key:"extractMetrics",value:function(t){var r=Object.assign({},this.connectionMetrics),n="";return t.forEach((function(t){var i;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===n)e.networkType=(null!==(i=t.networkType)&&void 0!==i?i:e.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(t.type)&&"succeeded"===t.state)n=t.localCandidateId,e.isFirefox()||(r.roundTripTime=1e3*(t.currentRoundTripTime||t.totalRoundTripTime/t.responsesReceived)),void 0!==t.availableOutgoingBitrate&&(r.availableOutgoingBitrate=t.availableOutgoingBitrate);else if(/codec/i.test(t.type)){var o,a;null!==(o=t.mimeType)&&void 0!==o&&o.includes("audio")?r.audioCodec=t.mimeType.replace("audio/",""):null!==(a=t.mimeType)&&void 0!==a&&a.includes("video")&&(r.videoCodec=t.mimeType.replace("video/",""),r.sdpFmtpLine=t.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},r),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var e=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new i(o.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then((function(t){return e.extractMetrics(t)}))}}])}();function oi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ai(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ai(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ai(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function si(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(si=function(){return!!e})()}var ci={uplink:"",downlink:""},ui=function(){function t(e){var r,n,i,o;C(this,t),n=this,i=F(i=t),r=N(n,si()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"pendingTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:ne.New}),Object.defineProperty(r,"exchangeSdpTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"peerConnectionStats",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"subSdpFmtpLines",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(r,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;r.reporter.log.debug("connectionId:".concat(r.id," ice gathering state: ").concat(t))}}),r.pc=null;var a=e.direction,s=e.sessionManager;return r.signaling=s.channel.signaling,r.sessionManager=s,r.reporter=s.reporter,r.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}}(),r.subSdpFmtpLines=[],r.direction=a,r.idToTransceiverMap=new Map,r.idToTransceiversMap=new Map,r.createPeerConnection(),r.id="".concat(r.direction,"_").concat(g()),r.startSinglePC().then((function(){r.state=ne.Idle,r.enquenTask.start()})),r}return U(t,c),L(t,[{key:"startSinglePC",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return"uplink"===this.direction?(this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly"})):(this.mcuAudioStream=null,this.mcuAudioTranceiver=this.pc.addTransceiver("audio",{direction:"recvonly"}),this.pc.addTransceiver("video",{direction:"recvonly"})),e&&function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),l=ke(n.sessions.values());if("downlink"===c){var d=r.media.slice(2),p=l.filter((function(e){return e instanceof bn})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!Oe.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var v=[];u.forEach((function(e){var t={direction:e.direction},r=d.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&v.push(i))})),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var h=l.filter((function(e){return e instanceof Zn}));u.forEach((function(e){var t={direction:e.direction},r=h.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof Zt){var s=Ht(n).encodings;t.sendEncodings=s.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}}(this),this.exchangeSDP(e)}},{key:"stopSinglePC",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]||this.emit("ended"),this.signaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"reset",value:function(){this.pendingTask&&(this.pendingTask=null)}},{key:"closePeerConnection",value:function(){this.pc&&(this.reporter.log.debug("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?Oe.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==ne.Ended&&(this.state=ne.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.reporter.log.debug("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"handleClientReoffer",value:(r=M(se.mark((function e(){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state!==ne.New){e.next=2;break}return e.abrupt("return",Promise.reject());case 2:return this.reporter.log.debug("connectionId:".concat(this.id,": start client reoffer")),e.prev=3,e.next=6,this.stopSinglePC(!0);case 6:this.removeAllListeners(),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(3),this.reporter.log.debug("connectionId:".concat(this.id," client reoffer close failed ").concat(m(e.t0)));case 12:this.closePeerConnection();case 13:case"end":return e.stop()}}),e,this,[[3,9]])}))),function(){return r.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var e=this,t=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,t),"failed"===t||"closed"===t?(this.clientFailoverTimer&&v(this.clientFailoverTimer),this.clientFailoverTimer=d((function(){e.state!==ne.New&&e.emit("reoffer")}),1e4)):"connected"===t&&(this.clientFailoverTimer&&(v(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(v(this.createPeerConnectionTimer),this.createPeerConnectionTimer=null))}},{key:"getPeerConnectionConfig",value:function(){var t=this.sessionManager.channel.iceConfig,r=t.username,n=t.password,i=t.port,o=t.iceServerList,a={bundlePolicy:"max-bundle",iceTransportPolicy:o.length?"relay":"all",sdpSemantics:"unified-plan"};if(o.length){var s,c=[],u=oi(o);try{for(u.s();!(s=u.n()).done;){var l=s.value;c.push("turn:".concat(l,":").concat(i,"?transport=udp"),"turn:".concat(l,":").concat(i,"?transport=tcp"))}}catch(e){u.e(e)}finally{u.f()}e.isFirefox()&&c.splice(4,2),"relay"===ci[this.direction]&&(ci[this.direction]="all",a.iceTransportPolicy="all"),a.iceServers=[{urls:c,username:r,credential:n}]}return ci[this.direction]=a.iceTransportPolicy,this.reporter.log.debug("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var e=this;this.pc?this.reporter.log.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=d((function(){var t;"connected"===(null===(t=e.pc)||void 0===t?void 0:t.connectionState)||e.exchangeSdpTask||e.emit("reoffer")}),4e3))}},{key:"attachEvents",value:function(){var e=this;this.pc&&(this.pc.ontrack=function(t){e.onTrack(t)},this.pc.oniceconnectionstatechange=function(){e.onIceConnectionStateChange()},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new ii(this),this.monitor.on("metrics",(function(t){e.peerConnectionStats=t})))}},{key:"getStats",value:function(){var e,t,r=this;return this.monitor?null===(e=this.monitor)||void 0===e||null===(t=e.getStats)||void 0===t?void 0:t.call(e).then((function(e){r.peerConnectionStats=e})):Promise.resolve()}},{key:"detachEvents",value:function(){this.createPeerConnectionTimer&&v(this.createPeerConnectionTimer),this.clientFailoverTimer&&v(this.clientFailoverTimer),this.pc&&(this.pc.ontrack=null,this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onicegatheringstatechange=null,this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null)}},{key:"startTask",value:function(){var e=this;return new Promise((function(t,r){e.pendingTask={resolve:t,reject:r},e.exchangeSDP(),d((function(){var t;e.pendingTask&&e.state===ne.Processing&&(null===(t=e.pendingTask)||void 0===t||t.reject(),e.fireEndedEvent())}),15e3)}))}},{key:"exchangeSDP",value:function(){var t,r=this,n=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return new Promise((function(a,s){r.exchangeSdpTask={resolve:a,reject:s},r.pc.createOffer().then((function(e){var i,o,a;return t=e,n&&(t.sdp=R.write((i=r.localSDP,o=R.parse(t.sdp),a=o.media,i.media.forEach((function(e){var t=e.mid,r=e.ssrcGroups,n=void 0===r?[]:r,i=e.ssrcs,o=void 0===i?[]:i,s=e.type,c=a.findIndex((function(e){return e.mid==t&&e.type===s}));c>-1&&(a[c]=En(En({},a[c]),{},{ssrcGroups:n,ssrcs:o}))})),o))),r.pc.setLocalDescription(t).catch((function(e){throw r.reporter.log.error("connectionId:".concat(r.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){r.reporter.log.debug("connectionId:".concat(r.id," set local sdp success"));var a=function(t,r){var n=r.direction,i=["uplink"===n,Oe.downlinkForbidHighProfile],o=R.parse(t);if(i.some((function(e){return e}))&&(o=Qn(o,"64")),Oe.disableTransportCC&&function(e){e.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!e.uri.includes("transport-wide-cc")})),e.rtcpFb=e.rtcpFb.filter((function(e){return"transport-cc"!==e.type}))}))}(o),"downlink"===n&&!Oe.downlinkForbidHighProfile){var a=[];o.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&a.push(t)})),r.subSdpFmtpLines=a}if(e.isFirefox()&&(o=Jn(o)),"uplink"===n&&e.isFirefox()&&Oe.simulcast){var s=o.media.find((function(e){return"video"===e.type}));Un(s)}return r.localSDP=o,o}(t.sdp,r);t.sdp=R.write(a),r.offerSDP=a,t.sdp=R.write(a);var s,c={direction:"downlink"!==r.direction?"in":"out",sdpOffer:t.sdp,connectionId:r.id,isFailover:n,optionsJsonStr:JSON.stringify({supportCVO:1})};if(n){var u=R.parse(t.sdp);u.media=u.media.slice(0,2),u.groups=[{mids:"0 1",type:"BUNDLE"}],c.sdpOffer=R.write(u)}return function(e){var t=e.fn,r=e.times,n=e.interval,i=void 0===n?0:n,o=e.key,a=Ke.get(o),s=function(){a&&(v(a),Ke.delete(o),a=null)};s();var c=function(){var e=M(se.mark((function e(){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,r--,e.next=4,t();case 4:s(),e.next=14;break;case 7:if(e.prev=7,e.t0=e.catch(0),!(r<=0)){e.next=12;break}throw s(),e.t0;case 12:a=d((function(){c()}),i),Ke.set(o,a);case 14:case"end":return e.stop()}}),e,null,[[0,7]])})));return function(){return e.apply(this,arguments)}}();return c()}({key:"createPeerConnection_".concat(r.direction),fn:(s=M(se.mark((function e(){var t;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===(null===(t=r.sessionManager)||void 0===t||null===(t=t.channel)||void 0===t||null===(t=t.client)||void 0===t?void 0:t.connectionState)){e.next=2;break}return e.abrupt("return");case 2:if(c.isFailover||!r.prevId){e.next=7;break}return e.next=5,r.stopSinglePC(!0);case 5:r.id="".concat(r.direction,"_").concat(g()),c.connectionId=r.id;case 7:return r.prevId=r.id,e.abrupt("return",r.signaling.createPeerConnection(c).then((function(e){var t=e.sdpAnswer,a=Hn(t,r,n,ci[r.direction]);r.pc.setRemoteDescription({sdp:R.write(a),type:"answer"}).then((function(){var e;r.reporter.log.debug("connectionId:".concat(r.id," receive answer success")),null===(e=r.exchangeSdpTask)||void 0===e||e.resolve(),r.exchangeSdpTask=void 0})).catch((function(e){var t,n;r.reporter.log.error("connectionId:".concat(r.id," Set remote description failed: ").concat(e)),null===(t=r.exchangeSdpTask)||void 0===t||t.reject(e),r.exchangeSdpTask=void 0,null===(n=r.pendingTask)||void 0===n||n.reject(new i(o.IceConnectionAnswerFail)),r.fireEndedEvent()}))})));case 9:case"end":return e.stop()}}),e)}))),function(){return s.apply(this,arguments)}),times:3,interval:2e3})})).catch((function(e){var t,n;r.reporter.log.error("connectionId:".concat(r.id," Failed to create offer or set SDP. Message: ").concat(e.message)),null===(t=r.pendingTask)||void 0===t||t.reject(new i(o.IceConnectionSetLocalDescFail)),r.fireEndedEvent(),null===(n=r.exchangeSdpTask)||void 0===n||n.reject(e),r.exchangeSdpTask=void 0}))}))}},{key:"reoffer",value:function(){var e=this;return this.state===ne.New?Promise.reject():(this.reporter.log.debug("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=ne.New,this.startSinglePC(!0).then((function(){e.state=ne.Idle,e.enquenTask.start()})))}},{key:"handleHighProfileFallback",value:function(){Oe.downlinkForbidHighProfile=!0,this.reporter.log.debug("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.reporter.log.debug("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var r}();function li(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function di(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?li(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):li(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function pi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return fi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?fi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function fi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function vi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(vi=function(){return!!e})()}var hi=function(){function e(t,r){var n,i,o,a;return C(this,e),i=this,o=F(o=e),n=N(i,vi()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(n,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.channel=r,n.client=t,n.reporter=r.reporter,n.streamIdToSessionId=new Map,n.sessions=new Map,n.handleMediaMessage=n.handleMediaMessage.bind(n),n.handleServerFailover=n.handleServerFailover.bind(n),n.handleRepulish=n.handleRepulish.bind(n),n.handleResubscribe=n.handleResubscribe.bind(n),n}return U(e,c),L(e,[{key:"getOrCreatePeerConnection",value:function(e){var t=this;return"uplink"===e?(this.uplink||(this.uplink=new ui({direction:e,sessionManager:this}),this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){t.uplink=null}))),this.uplink):(this.downlink||(this.downlink=new ui({direction:e,sessionManager:this}),this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){t.downlink=null}))),this.downlink)}},{key:"handleRepulish",value:(p=M(se.mark((function e(){var t,r,n,i,o,a,s;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){e.next=2;break}return e.abrupt("return");case 2:r=ke(this.client.localTracks),n=pi(this.sessions.values());try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof Zn&&o.state===re.Processing&&(o.clear(),this.sessions.delete(o.id))}catch(e){n.e(e)}finally{n.f()}return this.client.emit("media-reconnect-start",this.client.userId),a=null===(t=this.uplink)||void 0===t?void 0:t.id,e.prev=7,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),e.next=11,null===(s=this.uplink)||void 0===s?void 0:s.handleClientReoffer();case 11:if(this.uplink=null,this.reporter.log.info("".concat(this.client.userId," republish ").concat(r.map((function(e){return e.trackMediaType})).join()," start")),!r.length){e.next=16;break}return e.next=16,this.batchPublish(r);case 16:this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),this.client.emit("media-reconnect-end",this.client.userId),e.next=26;break;case 20:e.prev=20,e.t0=e.catch(7),this.reporter.log.debug("".concat(this.client.userId," republish failed for ").concat(m(e.t0))),this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),this.client.emit("media-reconnect-end",this.client.userId),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 26:case"end":return e.stop()}}),e,this,[[7,20]])}))),function(){return p.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(l=M(se.mark((function e(t){var r,n,i,o,a,s,c,u,l,d,p;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){e.next=2;break}return e.abrupt("return");case 2:r=[],n=pi(t);try{for(n.s();!(i=n.n()).done;)(o=i.value)instanceof bn&&o.state===re.Processing&&(r.push({stream:o.stream,uid:o.uid,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){n.e(e)}finally{n.f()}return a=r.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",a),this.reporter.log.info("resubscribe ".concat(a," start")),e.prev=8,e.next=11,this.batchUnscribe(r);case 11:return e.next=13,this.batchSubscribe(r);case 13:s=e.sent,c=pi(s);try{for(c.s();!(u=c.n()).done;)l=u.value,d=l.subscription,p=l.error,d&&!p&&this.handleSubscribeReoffer(d)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=24;break;case 19:e.prev=19,e.t0=e.catch(8),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(m(e.t0))),this.client.emit("media-reconnect-end",a),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 24:case"end":return e.stop()}}),e,this,[[8,19]])}))),function(e){return l.apply(this,arguments)})},{key:"handleResubscribe",value:(u=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,v,h,y,g=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=g.length>0&&void 0!==g[0]&&g[0],"disconnected"!==this.channel.internalChannel.connectionState){e.next=3;break}return e.abrupt("return");case 3:n=r?"server":"client",i=[],o=pi(this.sessions.values());try{for(o.s();!(a=o.n()).done;)(s=a.value)instanceof bn&&s.state===re.Processing&&(i.push({stream:s.stream,uid:s.uid}),this.removeSession(s.id))}catch(e){o.e(e)}finally{o.f()}return c=i.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",c),this.reporter.log.info("resubscribe ".concat(c," start")),u=null===(t=this.downlink)||void 0===t?void 0:t.id,e.prev=11,this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferStart")),e.next=15,null===(l=this.downlink)||void 0===l?void 0:l.handleClientReoffer();case 15:if(this.downlink=null,!i.length){e.next=22;break}return e.next=19,this.batchSubscribe(i);case 19:d=e.sent,p=pi(d);try{for(p.s();!(f=p.n()).done;)v=f.value,h=v.subscription,y=v.error,h&&!y&&this.handleSubscribeReoffer(h)}catch(e){p.e(e)}finally{p.f()}case 22:this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferSuccess")),this.reporter.log.debug("".concat(this.client.userId," resubscribe ").concat(c," success")),this.client.emit("media-reconnect-end",c),e.next=33;break;case 27:e.prev=27,e.t0=e.catch(11),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(m(e.t0))),this.reporter.trace.connectionsEvent(u,"".concat(n,"ReofferFailed")),this.client.emit("media-reconnect-end",c),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 33:case"end":return e.stop()}}),e,this,[[11,27]])}))),function(){return u.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return this.sessions.get(this.streamIdToSessionId.get(e))}},{key:"handleSubscribeReoffer",value:function(e){var t,r=e.uid,n=e.mediaStream,i=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===z.SCREENCAST,o=n.getAudioTracks()[0],a=n.getVideoTracks()[0],s=o?"audio":i?"screen":"camera";if(this.reporter.log.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.channel.remoteAudioTrack){var c,u;if(Oe.audioSFU)null===(c=(u=this.channel.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,n);else this.channel.remoteAudioTrack.replaceTrack(o)}else{var l=this.channel.userManager.remoteUsers.find((function(e){return e.userId===r}));a&&null!=l&&l.auxiliaryTrack&&i?l.auxiliaryTrack.replaceTrack(a):a&&null!=l&&l.videoTrack&&!i&&l.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.reporter.log.debug("serverFailover ".concat(JSON.stringify(e)));var r,n=e.actions,i=pi(void 0===n?[]:n);try{var o=function(){var e,n,i=r.value,o=i.actionName,a=i.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,l=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then((function(){t.reporter.log.info("".concat(u," republish ").concat(l.map((function(e){return e.trackMediaType})).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)})).catch((function(e){t.reporter.log.debug("".concat(t.client.userId," republish failed for ").concat(m(e))),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.channel.signaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")}))}else a===(null===(n=t.downlink)||void 0===n?void 0:n.id)&&t.handleResubscribe(!0)};for(i.s();!(r=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}},{key:"addSession",value:function(e,t){this.sessions.set(t.id,t),this.streamIdToSessionId.set(e,t.id)}},{key:"getNetworkQuality",value:function(e,t){return e>50||t>600?X.BAD:e>30||t>450?X.POOR:e>20||t>300?X.NORMAL:e>10||t>200?X.GOOD:e>=0||t>=0?X.GREAT:X.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(s=M(se.mark((function e(){var t,r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=ke(this.sessions.values())).length){e.next=4;break}return this.emit("network-quality",X.UNKNOWN,X.UNKNOWN),e.abrupt("return");case 4:if(0!==t.filter((function(e){var t,r=e.connection;return"connected"===(null==r||null===(t=r.pc)||void 0===t?void 0:t.connectionState)})).length){e.next=8;break}return this.emit("network-quality",X.DISCONNECTED,X.DISCONNECTED),e.abrupt("return");case 8:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then((function(e){var t=Et(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,l=0,d=0,p=0;if(n){var f=n.camera,v=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,d=Math.max(d,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,d=Math.max(d,v.rtt||0))}for(var h in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,d=Math.max(d,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,l+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[h],y=m.camera,g=m.auxiliary;y&&(u+=y.receivePacketsLost,l+=y.receivePackets,p=Math.max(p,y.rtt||0)),g&&(u+=g.receivePacketsLost,l+=g.receivePackets,p=Math.max(p,g.rtt||0))}var b=-1,S=-1,k={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:l};if(s){var P,w,O=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(O<0&&(O=c),k.totalUplinkPacketsSentForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalUplinkPacketsSentForLost)||0,0!==O){var T;k.totalUplinkPacketsSentForLost=s;var E=s-((null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0);E<0&&(E=s),b=O/E}}if(l){var I,R,A,_,M=u-((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0);M<0&&(M=u),k.totalDownlinkPacketsRecvForLost=(null===(R=r.lastChannelNetworkQuality)||void 0===R?void 0:R.totalDownlinkPacketsRecvForLost)||0,null===(A=r.lastChannelNetworkQuality)||void 0===A||A.totalDownlinkPacketsRecvForLost,M&&(u!==((null===(_=r.lastChannelNetworkQuality)||void 0===_?void 0:_.totalDownlinkPacketsLost)||0)&&(k.totalDownlinkPacketsRecvForLost=l),S=M/l)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*b,100),d),r.getNetworkQuality(Math.min(100*S,100),p)),r.lastChannelNetworkQuality=k}));case 9:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"removeSession",value:function(e,t){t&&(e=this.streamIdToSessionId.get(t),this.streamIdToSessionId.delete(t));var r=this.sessions.get(e);r&&(r.clear(),this.sessions.delete(e))}},{key:"batchPublish",value:function(e,t){var r=this,n=Date.now();return function(e){var t,r=e.tracks,n=e.connection,i=e.labels,o=r.map((function(t){return{publication:new Zn(Kn(Kn({},e),{},{tracks:[t]})),track:t}})),a=new Promise((function(e,a){t=function(){var t=M(se.mark((function t(){var s,c;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,ei(r,n,i);case 2:return s=t.sent,c={connectionId:n.id,media:s,simulcast:Oe.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.signaling.batchPublish(c).then(function(){var t=M(se.mark((function t(r){var n,i,a,s,c;return se.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=4;break}return o.forEach((function(e){e.error=Re(e.track,i)})),t.abrupt("return",e(o));case 4:a=zn(n),t.prev=5,c=se.mark((function e(){var t,r,n,i,a,c,u;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,a=o.findIndex((function(e){return e.track.getTrackId()===n.id})),c=o[a]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(o[a].error=Re(o[a].track,i));case 4:case"end":return e.stop()}}),e)})),a.s();case 8:if((s=a.n()).done){t.next=12;break}return t.delegateYield(c(),"t0",10);case 10:t.next=8;break;case 12:t.next=17;break;case 14:t.prev=14,t.t1=t.catch(5),a.e(t.t1);case 17:return t.prev=17,a.f(),t.finish(17);case 20:e(o);case 21:case"end":return t.stop()}}),t,null,[[5,14,17,20]])})));return function(e){return t.apply(this,arguments)}}()).catch((function(e){a(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),a}({uid:this.client.userId,tracks:e,connection:this.getOrCreatePeerConnection("uplink"),labels:t}).then((function(e){var t,i=pi(e);try{var o=function(){var e=t.value,i=e.error,o=e.publication,a=e.track;i?r.reporter.trace.publish(!1,a,"",Date.now()-n):(r.addSession(a.getTrackId(),o),r.reporter.trace.publish(!0,a,o.id,Date.now()-n),r.reporter.trace.publish(!1,a,o.id,Date.now()-n),o.on("ended",(function(){r.removeSession(o.id)})))};for(i.s();!(t=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}}))}},{key:"batchUnPublish",value:function(e){var t=this;return e.length?ti(e,{connection:this.getOrCreatePeerConnection("uplink")}).then((function(){var r,n=pi(e);try{for(n.s();!(r=n.n()).done;){var i,o,a,s=r.value;t.streamIdToSessionId.delete(null===(i=s.tracks)||void 0===i||null===(i=i[0])||void 0===i||null===(o=(a=i).getTrackId)||void 0===o?void 0:o.call(a)),t.removeSession(s.id)}}catch(e){n.e(e)}finally{n.f()}})):Promise.resolve()}},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,i=function(e){return wn(e,{connection:t.getOrCreatePeerConnection("downlink")}).then(function(){var r=M(se.mark((function r(o){var a,s,c,u;return se.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:for(a=new Map,s=[],c=0;c<o.length;c++)"RoomBusy"===(null===(u=o[c].error)||void 0===u?void 0:u.message)&&(s.push(e[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){r.next=12;break}return n++,r.next=7,ze(1);case 7:if("connected"!==t.client.connectionState){r.next=12;break}return r.next=10,i(s);case 10:r.sent.forEach((function(e,t){var r=a.get(t);o[r]=e}));case 12:return r.abrupt("return",o);case 13:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}())};return i(e).then((function(e){var n,i=pi(e);try{var o=function(){var e=n.value,i=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;o&&(t.reporter.trace.subscribe({init:!0,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:a,resolutionInfo:u}),"mcu"===o.uid&&t.reporter.trace.subscribe({init:!1,capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:o.id,resolutionInfo:u}),t.addSession(s.id,o),o.on("ended",(function(){t.removeSession(a)}))),i&&t.reporter.trace.subscribe({init:!1,capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-r,sessionId:"",resolutionInfo:u})};for(i.s();!(n=i.n()).done;)o()}catch(e){i.e(e)}finally{i.f()}return e}))}},{key:"batchUnscribe",value:(a=M(se.mark((function e(t){var r,n,i,o=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,a=e.stream,s=e.session;r[t]={},o?r[t].error=o:(i[null==a?void 0:a.id]=t,n.push(s))})),e.abrupt("return",On(n,{connection:this.getOrCreatePeerConnection("downlink")}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];o.removeSession(i.id)}return r})));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"clear",value:function(){var e,t,r=this;this.sessions.forEach((function(e){r.removeSession(e.id)})),null===(e=this.uplink)||void 0===e||e.closePeerConnection(),this.uplink=null,null===(t=this.downlink)||void 0===t||t.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(v(this.networkQualityInterval,"interval"),this.networkQualityInterval=null),this.channel.signaling.off("media-message",this.handleMediaMessage),this.channel.signaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:function(){this.startNetworkQualityTimer(),this.uplink=this.getOrCreatePeerConnection("uplink"),this.downlink=this.getOrCreatePeerConnection("downlink"),this.channel.signaling.on("media-message",this.handleMediaMessage),this.channel.signaling.on("serverFailover",this.handleServerFailover)}},{key:"startNetworkQualityTimer",value:function(){var e=this;this.networkQualityInterval=d((function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?e.emit("network-quality",X.DISCONNECTED,X.DISCONNECTED):"connected"!==e.client.connectionState?e.emit("network-quality",X.BAD,X.BAD):"connected"===e.client.connectionState?e.checkChannelNetworkQuality():e.emit("network-quality",X.UNKNOWN,X.UNKNOWN)}),2e3,"interval")}},{key:"getLocalAudioStats",value:(o=M(se.mark((function e(){var t,r,n,i=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=ke(this.sessions.values()).filter((function(e){var t,r;return e instanceof Zn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"audio"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)})},{key:"getLocalVideoStats",value:(i=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,v,h=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=h.length>0&&void 0!==h[0]?h[0]:"network",i=ke(this.sessions.values()).filter((function(e){var t;return e instanceof Zn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&"video"===e.tracks[0].trackMediaType})),e.next=4,Promise.all(i.map((function(e){return e.getMetrics(n)})));case 4:o=function(e){var t;return(null==e||null===(t=e.fmtp)||void 0===t?void 0:t.filter((function(e){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.includes("profile-level-id")})).map((function(e){var t,r=(null==e||null===(t=e.config)||void 0===t?void 0:t.split(";"))||[],n=r.findIndex((function(e){return e.includes("profile-level-id")}));return r[n].split("=")[1]})))||[]},a=null===(t=this.uplink)||void 0===t||null===(t=t.offerSDP)||void 0===t||null===(t=t.media)||void 0===t?void 0:t.find((function(e){return"video"===e.type})),s=null===(r=this.downlink)||void 0===r||null===(r=r.offerSDP)||void 0===r||null===(r=r.media)||void 0===r?void 0:r.find((function(e){return"video"===e.type})),c={uplinkProfile:ke(new Set(o(a))),downlinkProfile:ke(new Set(o(s)))},u=pi(i),e.prev=9,u.s();case 11:if((l=u.n()).done){e.next=21;break}if(d=l.value,p=d.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=d.tracks,v=f[0].source===z.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return i.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(n=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=ke(this.sessions.values()).filter((function(e){var t;return e instanceof bn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.video})),e.next=4,Promise.all(r.map((function(e){return e.getMetrics(t)})));case 4:n={},i=pi(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,l=s.stream,d=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=l.media.video)||void 0===a?void 0:a.source)===z.SCREENCAST?"auxiliary":"camera",n[u]=di(di({},n[u]||{}),{},ce({},p,d));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return n.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(r=M(se.mark((function e(){var t,r,n,i=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=ke(this.sessions.values()).filter((function(e){var t;return e instanceof bn&&"connected"===(null===(t=e.connection)||void 0===t||null===(t=t.pc)||void 0===t?void 0:t.connectionState)&&e.stream.media.audio})),e.next=4,Promise.all(n.map((function(e){return e.getMetrics(r)})));case 4:return e.abrupt("return",(null===(t=n[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 5:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"handleMediaMessage",value:(t=M(se.mark((function e(t){var r,n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.reporter.log.debug("remote feedback: ".concat(t.payload)),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=4;break}return e.abrupt("return");case 4:n=ke(this.sessions.values()).filter((function(e){return e instanceof Zn&&e.state===re.Processing&&e.tracks[0].source===z.CAMERA})),i=pi(n),e.prev=6,a=se.mark((function e(){var t,n;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(n=r.filter((function(e){return e.mid==t.transceiver.mid}))).length&&t.applyOptions(n);case 3:case"end":return e.stop()}}),e)})),i.s();case 9:if((o=i.n()).done){e.next=13;break}return e.delegateYield(a(),"t0",11);case 11:e.next=9;break;case 13:e.next=18;break;case 15:e.prev=15,e.t1=e.catch(6),i.e(e.t1);case 18:return e.prev=18,i.f(),e.finish(18);case 21:case"end":return e.stop()}}),e,this,[[6,15,18,21]])}))),function(e){return t.apply(this,arguments)})}]);var t,r,n,i,o,a,s,u,l,p}();function mi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return yi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?yi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function yi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function gi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(gi=function(){return!!e})()}var bi={name:"name"},Si=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,gi()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"groupIds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"groups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"default",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"listVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=t,r.groups=new Map,r.listVer=0,r.groupIds=new Set,r.handleGroupListEvents=r.handleGroupListEvents.bind(r),r.handleGroupEvents=r.handleGroupEvents.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r}return U(e,c),L(e,[{key:"joinedIds",get:function(){var e=this.channel.userManager.currentPid,t=new Set;return this.groups.forEach((function(r){var n=r.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.channel.userManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.channel.signaling.on("group-list",this.handleGroupListEvents),this.channel.signaling.on("group",this.handleGroupEvents),this.channel.signaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.channel.signaling.off("group",this.handleGroupEvents),this.channel.signaling.off("group-list",this.handleGroupListEvents),this.channel.signaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(e){var t=e.publishAudioToGroup,r=void 0===t||t,n=e.groupId,a=e.userData;if(this.joinedIds.has(n))throw new i(o.InvaildArgument,"you were in group already");return this.channel.signaling.joinGroup({groupId:n,userData:a,autoJoinGroupAudio:!!r,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(e){var t=e.groupId,r=e.publishAudioToChannel,n=void 0===r||r;if(!this.joinedIds.has(t))throw new i(o.InvaildArgument,"you are not in the group");return this.channel.signaling.leaveGroup({groupId:t,reasonCode:pr.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(e){if(!this.groupIds.has(e))throw new i(o.InvaildArgument,"group not existed");return this.channel.signaling.dismissGroup({groupId:e})}},{key:"addUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;n&&!n.find((function(t){return t.pid===e.pid}))&&n.push(e)}},{key:"removeUser",value:function(e,t){var r,n=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(n){var i=n.findIndex((function(t){return t.pid===e.pid}));i>-1&&n.splice(i,1)}}},{key:"observerAllGroup",value:function(){return this.channel.signaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.channel.signaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.channel.signaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,n=e.type,i=e.updateOpt;if(this.channel.reporter.log.debug("groupList ".concat(JSON.stringify(e))),r!==this.listVer+1&&!t||n!==pr.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===pr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===pr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID&&this.groupIds.delete(a),this.listVer=r}}},{key:"handleGroupEvents",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.channel.reporter.log.debug("group ".concat(JSON.stringify(e)));var n,i=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(i);if(s!==pr.OptType.OPT_TYPE_ADD||u){if(s===pr.OptType.OPT_TYPE_REMOVE&&u){var l,d=null==u||null===(l=u.audioInfo)||void 0===l||null===(l=l.audio)||void 0===l?void 0:l.id;this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),d)}else if(s===pr.OptType.OPT_TYPE_UPDATE){var p=c.updateAction,f=c.participants;if(u&&(u.ver+1===o||r)){if(p===pr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var v,h=u.participants.map((function(e){return e.pid})),m=mi(f);try{for(m.s();!(v=m.n()).done;){var y=v.value;h.includes(y.pid)||(u.participants.push(y),this.emit("group","user-join",i,{userId:y.uid,userData:y.userData}))}}catch(e){m.e(e)}finally{m.f()}}else if(p===pr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=f.map((function(e){return e.pid})),b=ke(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),b.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(p===pr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.channel.reporter.log.debug("group ".concat(i," audioStream lost"));else if(p===pr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.channel.reporter.log.debug("group ".concat(i," audioStream recover"));else if(p===pr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES)c.properties.forEach((function(e){var r=!0;u.properties||(u.properties=[]),u.properties.forEach((function(t){t.key===e.key&&(t.value=e.value,r=!1)})),r&&u.properties.push(e),t.emit("group","info-updated",i,{key:"set-".concat(bi[e.key]),value:e.value})}));else if(p===pr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var S,k=c.properties.map((function(e){return e.key}));u.properties=null===(S=u.properties)||void 0===S?void 0:S.filter((function(e){var t=e.key;return!k.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(bi[e.key])})}))}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(n=a.audioInfo)||void 0===n||null===(n=n.audio)||void 0===n||null===(n=n.media)||void 0===n||delete n.video,null==a.ver&&(a.ver=o),this.groups.set(i,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.channel.signaling.syncData({type:pr.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],l=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),d=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==l[e.key]})),v=c.filter((function(e){return!l.has(e.key)})),h=a.filter((function(e){return!d.includes(e.pid)})),m=u.filter((function(e){return!p.includes(e.pid)}));h.length&&t.handleGroupEvents({id:e,type:pr.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:pr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:h}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pr.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:pr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:pr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:pr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:pr.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.channel.signaling.syncDataByIds({type:pr.DataType.DATA_TYPE_GROUP,ids:e.map((function(e){return{id:e}}))}).then((function(e){e.fullSync.groupData.groupInfos.forEach((function(e){t.groupIds.add(e.id),t.groups.set(e.id,e)}))}))}},{key:"syncGroupList",value:function(){var e=this;this.channel.signaling.syncData({type:pr.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then((function(t){var r=t.fullSync,n=r.ver,i=r.groupListData.groupIds,o=void 0===i?[]:i,a=o.filter((function(t){return!e.groupIds.has(t)})),s=ke(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:pr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:pr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}();function ki(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ki=function(){return!!e})()}var Pi=function(){function e(t,r){var n,i,o,a;C(this,e),i=this,o=F(o=e),n=N(i,ki()?Reflect.construct(o,[],F(i).constructor):o.apply(i,a)),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=t.user;return n.userId=s,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.channel=r,n.joinedTime=Date.now(),n.update(t),n}return U(e,c),L(e,[{key:"relatedStreams",get:function(){var e=this;return ke(this.channel.streamManager.streams.values()).filter((function(t){var r;return(null==t||null===(r=t.info)||void 0===r?void 0:r.owner)===e.id}))}},{key:"hasAuxiliary",get:function(){return this.relatedStreams.some((function(e){var t;return(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===z.SCREENCAST}))}},{key:"hasVideo",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.video)||void 0===t?void 0:t.source)===z.CAMERA}))}},{key:"hasAudio",get:function(){return this.relatedStreams.some((function(e){var t,r=e.media;return(null==r||null===(t=r.audio)||void 0===t?void 0:t.source)===K.MIC}))}},{key:"audioMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.audio)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.audio)||void 0===r?void 0:r.source)===K.MIC}))}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===z.SCREENCAST}))}},{key:"videoMuted",get:function(){return this.relatedStreams.some((function(e){var t,r,n=e.media;return"active"!==(null==n||null===(t=n.video)||void 0===t?void 0:t.status)&&(null==n||null===(r=n.video)||void 0===r?void 0:r.source)===z.CAMERA}))}},{key:"updateNetworkOfUser",value:function(e){var t;if(this.properties.SdkType!==P.Web&&e){var r=e.split("");r[oe.UPLINK]=Je(r[oe.UPLINK]),r[oe.DOWNLINK]=Je(r[oe.DOWNLINK]),e=r.join("")}e!==(null===(t=this.properties)||void 0===t?void 0:t[ve])&&(this.properties[ve]=e)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[ve])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=Ae(e.mediaStream,"video",this.userId,r);return r||i.once("first-frame-decoded",(function(){e.handleVideoFirstFrame()})),t?this.auxiliaryTrack=i:this.videoTrack=i,n.mirror&&i.setSourceMirror(n.mirror),i}}])}();function wi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Oi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Oi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Oi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ti(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ti=function(){return!!e})()}var Ei=function(){function e(t){var r,n,i,o;return C(this,e),n=this,i=F(i=e),r=N(n,Ti()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(r,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"currentPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.users=new Map,r.channel=t,r.reporter=t.reporter,r.handleEvent=r.handleEvent.bind(r),r}return U(e,c),L(e,[{key:"remoteUsers",get:function(){var e=this;return w(ke(this.users.values()).sort((function(e,t){return e.joinedTime-t.joinedTime})),"userId").filter((function(t){return t.userId&&t.id!==e.currentPid}))}},{key:"init",value:function(e,t){var r,n=wi(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new Pi(i,this.channel);this.users.set(i.user,o),t===i.user&&(this.currentUid=i.user)}}catch(e){n.e(e)}finally{n.f()}this.currentPid=t,this.channel.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentPid="",this.currentUid="",this.users.clear(),this.channel.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t){if(this.reporter.log.debug("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var r=new Pi(t,this.channel);this.users.set(t.user,r),this.emit("user","join",r)}else if("leave"===e){var n=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",n)}else if("update"===e){var i=this.users.get(t.user);null==i||i.update(t)}}},{key:"setParticipantProperties",value:function(e){return this.channel.signaling.setParticipantProperties({participantId:this.currentPid,roomId:this.channel.roomId,propertiesJsonStr:JSON.stringify(ce({},ve,e))})}}])}();function Ii(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Ri(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ri(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Ri(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ai(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function _i(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ai(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ai(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Mi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Mi=function(){return!!e})()}var Ci=function(){function e(t){var r,n,i,o;C(this,e),n=this,i=F(i=e),r=N(n,Mi()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"streams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"totalVer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var a=t.signaling,s=t.reporter;return r.signaling=a,r.reporter=s,r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.sync=r.sync.bind(r),r}return U(e,c),L(e,[{key:"clear",value:function(){this.streams.clear(),this.totalVer=0,this.signaling.off("stream",this.handleEvent),this.signaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,n=e.find((function(e){return"admin"===e.info.owner&&"mixed"===e.type}));null==n||null===(r=n.media)||void 0===r||delete r.video,this.streams=new Map(e.map((function(e){return[e.id,e]}))),this.totalVer=t,this.signaling.on("stream",this.handleEvent),this.signaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(e){var t,r=e.id,n=e.info.owner,i=e.media,o=i.video,a=i.audio;if(!this.streams.get(r)){var s=null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source,c=ke(this.streams.values()).find((function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===s}));c&&this.remove(c.id),this.reporter.trace.streamsEvent(r,"add"),this.streams.set(e.id,e);var u=(null==o?void 0:o.source)===O.SCREENCAST;((null==o?void 0:o.source)===O.CAMERA||u)&&this.emit("stream","add",{id:r,owner:n,mediaType:"video",auxiliary:u}),(null==a?void 0:a.source)!==K.MIC&&(null==a?void 0:a.source)!==K.MIXED||this.emit("stream","add",{id:r,owner:n,mediaType:"audio"})}}},{key:"remove",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.streams.get(e);if(r&&(this.streams.delete(e),t)){this.reporter.trace.streamsEvent(e,"remove");var n=r.media,i=n.video,o=n.audio,a=r.info.owner,s=(null==i?void 0:i.source)===O.SCREENCAST;((null==i?void 0:i.source)===O.CAMERA||s)&&this.emit("stream","remove",{id:e,owner:a,mediaType:"video",auxiliary:s}),(null==o?void 0:o.source)!==K.MIC&&(null==o?void 0:o.source)!==K.MIXED||this.emit("stream","remove",{id:e,owner:a,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return ke(this.streams.values()).find((function(t){var r,n;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(n=t.media.video)||void 0===n?void 0:n.trackId)===e}))}},{key:"handleEvent",value:function(e,t){var r=this,n=e.streamId,i=e.status,o=e.stream,a=e.msg,s=e.totalVer,c={add:[],remove:[],update:["audio.status","video.status","properties","highestResolutionLevel"]}[i];c.length&&!c.includes(a.field)||this.reporter.log.debug("streamEvent ".concat(JSON.stringify(e)));var u=this.totalVer;if(s===u+1||s==pe||t)if("add"===i){if(!o||!o.media||!o.info)return;this.add(o)}else if("remove"===i)this.remove(n,!0);else if("update"===i){var l=a.field,d=a.streamStatus,p=a.activeStream,f=a.extraValue,v=a.streamVer,h=a.propertiesJsonStr,m=a.highestResolutionLevel,y=this.streams.get(n);if(y){v!==pe&&(y.version=v);var g=y.media,b=g.audio,S=g.video,k=y.info.owner;if("audio.status"===l||"video.status"===l){var P;"audio.status"===l?(P="audio",b.status=d):"video.status"===l&&(P="video",S.status=d),this.reporter.trace.streamsEvent(n,"".concat(P," ").concat(d));var w="active"===d?"unmute":"mute";this.emit("stream","update",{owner:k,id:n,updateStatus:"".concat(w,"-").concat(P)})}else if("activeInput"===l){var T=[p].concat(f||[]).map((function(e){var t;return null===(t=r.streams.get(e))||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner})).filter((function(e){return!!e}));this.reporter.trace.streamsEvent(JSON.stringify(T),l),this.emit("stream","volumeActive",{owners:T})}else if("properties"==l){var E,I=JSON.parse(h);y.info.attributesJsonStr=JSON.stringify(_i(_i({},JSON.parse(y.info.attributesJsonStr)),I));var R=(null===(E=y.media)||void 0===E||null===(E=E.video)||void 0===E?void 0:E.source)===O.SCREENCAST;this.emit("stream","update",{owner:k,id:n,properties:I,auxiliary:R})}else"highestResolutionLevel"===l&&(y.media.video.highestResolutionLevel=m,this.emit("stream","update",{owner:k,id:n,highestResolutionLevel:m}))}}t||s<=this.totalVer&&s!==pe||(s===u+1&&(this.totalVer=s),s>u+1&&!t&&this.sync())}},{key:"sync",value:(t=M(se.mark((function e(){var t,r,n,i,o,a,s,c,u,l,d,p,f,v,h=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=4,this.signaling.getStreamsVer({});case 4:n=e.sent,i=n.streamVersions,o=n.totalVer,a=ke(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=Ii(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,l=u.streamId,d=u.streamVer,!l.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(l))?p&&p.version!==d&&t.push(l):(r.push(l),t.push(l));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),v=a.filter((function(e){return!f.includes(e)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=33;break}return e.abrupt("return");case 33:this.signaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=Ii(h.streams.values());try{for(s.s();!(n=s.n()).done;){var c=n.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,l=Ii(o);try{for(l.s();!(u=l.n()).done;){var d=u.value;h.streams.has(d.id)?h.streams.set(d.id,d.stream):a.set(d.id,d.stream)}}catch(e){l.e(e)}finally{l.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var m=p[f];v.includes(m.id)?h.handleEvent({status:"remove",streamId:m.id,stream:m,totalVer:i},!0):r.includes(m.id)&&h.handleEvent({status:"add",streamId:m.id,stream:m,totalVer:i},!0)}a.clear(),h.totalVer=i}));case 34:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return t.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var t}();function Di(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return xi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?xi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function xi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ji(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Li(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ji(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ji(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ni(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ni=function(){return!!e})()}var Fi=function(){function e(t,r){var n,a,s,c;return C(this,e),a=this,s=F(s=e),n=N(a,Ni()?Reflect.construct(s,[],F(a).constructor):s.apply(a,c)),Object.defineProperty(n,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"groupManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"userManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"remoteAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"internalChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"roomId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"defaultVideoStreamType",{enumerable:!0,configurable:!0,writable:!0,value:"high"}),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscribedAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"micMixedGroups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"iceConfig",{enumerable:!0,configurable:!0,writable:!0,value:{level:0,iceServerList:[]}}),Object.defineProperty(n,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,r=e.mediaType,a=e.action,s=e.uid,c=e.auxiliary,u=n.getStream(e),l=n.userManager.users.get(s),d=n.groups.some((function(e){return e.joined})),p="mcu"===s?n.remoteAudioTrack:c?null==l?void 0:l.auxiliaryTrack:null==l?void 0:l.videoTrack;return"mcu"===s&&"video"===r||s&&"mcu"!==s&&"audio"===r?t=new i(o.InvaildArgument,"only support ".concat(a," mcu audio")):"mcu"===s&&d&&"subscribe"===a?t=new i(o.SubscribeInvaild,"cannot subscribe mcu while in group"):"subscribe"===a&&p?t=new i(o.SubscribeInvaild,"duplicated subscription"):u&&("unsubscribe"!==a||p)||(n.reporter.log.warn("".concat(s," videoTrack not existed")),t=new i(o.SubscribeStreamNotExisted)),{uid:s,user:l,error:t,stream:u,session:"unsubscribe"===a?n.sessionManager.getSessionByStreamId(u.id):null,resolutionInfo:"video"===r?Ct(n.defaultVideoStreamType,Ee(u)):null}}}),Object.defineProperty(n,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,o=t.streams,a=t.streamsVer,s=t.groupList,c=t.groupListVer;n.streamManager.init(o,a),n.groupManager.init(s,c),n.userManager.init(i,r),n.streamManager.on("stream",n.handleStreamEvent),n.userManager.on("user",n.handleUserEvent),n.groupManager.on("group",n.handleGroupEvent)}}),n.reporter=r,n.internalChannel=new A({reporter:r,sdkVersion:de}),n.signaling=new zr(n.internalChannel),n.client=t,n.micMixedGroups=new Set,n.groupManager=new Si(n),n.userManager=new Ei(n),n.streamManager=new Ci(n),n.sessionManager=new hi(t,n),n.subscribedAudioStream="",n.handleStreamEvent=n.handleStreamEvent.bind(n),n.handleUserEvent=n.handleUserEvent.bind(n),n.handleGroupEvent=n.handleGroupEvent.bind(n),n}return U(e,c),L(e,[{key:"localTracks",get:function(){return ke(this.sessionManager.sessions.values()).filter((function(e){return e.state===re.Processing&&e instanceof Zn})).map((function(e){return e.tracks[0]}))}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map((function(t){return Li(Li({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})}))}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=t.highestResolutionLevel,l=this.internalChannel.userManager.participants,d=l.get(n),p=this.userManager.users.get(null==d?void 0:d.user),f=n===this.userManager.currentPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,i,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stop(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stop(),p.videoTrack=null)),this.client.emit("user-unpublished",p,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.userManager.currentUid,s);else if(null!=(null==c?void 0:c.mirror)){var v=o?p.auxiliaryTrack:p.videoTrack;null==v||v.setSourceMirror(c.mirror)}else if(null!=u){var h=this.sessionManager.getSessionByStreamId(r);if(!h)return;h.stream.media.video.highestResolutionLevel=u;var m=h.userConfigResolution,y=h.resolutionInfo;if(u>=m.resolutionLevel&&m.resolutionLevel>y.resolutionLevel)h.applyOptions(m,!0);else if(u<m.resolutionLevel){var g=Ct(Dt(u),Ee(h.stream));h.applyOptions(g,!0)}}}else if("volumeActive"===e){var b=a.map((function(e){return l.get(e)})).map((function(e){return null==e?void 0:e.user})).filter((function(e){return!!e}));this.client.emit("volume-indicator",b)}}},{key:"handleGroupEvent",value:function(e,t,r){if("add"===e)this.client.emit("group-add",t);else if("remove"===e)this.micMixedGroups.delete(t.id),r===this.subscribedAudioStream&&(this.remoteAudioTrack.stop(),this.remoteAudioTrack=null,this.updateSubscribedAudioStream(!1,r)),this.client.emit("group-remove",t);else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var n=r.key,i=r.value;this.client.emit("group-info-updated",t,n,i)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e&&this.client.emit("user-left",t)}},{key:"getStream",value:function(e){var t,r=e.groupId,n=e.uid,i=e.auxiliary;if(r){var o,a=this.groupManager.groups.get(r);return null==a||null===(o=a.audioInfo)||void 0===o?void 0:o.audio}var s="mcu"===n?ke(this.streamManager.streams.values()):null===(t=this.userManager.users.get(n))||void 0===t?void 0:t.relatedStreams;return"mcu"===n?s.find((function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r})):s.find((function(e){var t=e.media.video;return(null==t?void 0:t.source)===(i?O.SCREENCAST:O.CAMERA)}))}},{key:"join",value:(s=M(se.mark((function e(t){var r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("dingrtc channel join",t,Oe.gslb[0]),e.abrupt("return",this.signaling.join(t,Oe.gslb[0]).then((function(e){var t,n,i,o,a,s=e.joinResponse,c=e.iceConfig,u=r.internalChannel.staticConfig;return null!=(null==u||null===(t=u.websdkConfig)||void 0===t?void 0:t.simulcast)&&(Oe.simulcast=null==u||null===(n=u.websdkConfig)||void 0===n?void 0:n.simulcast),r.roomId=s.room.id,i=s.room.ssrcMask,o=s.room.ssrcClientSequence,a=Math.log2(i+1),o>2147483647>>a||(Mn=i,_n=(o<<a|2147483648)>>>0),r.reporter.updateCommonInfo({roomId:r.roomId,participantId:s.id}),c&&c.uis&&r.setIceConfig(c.uis),r.sessionManager.start(),r.handleJoinResponse(s),s})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter((function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)})),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.userManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stop(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.userManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.signaling.leave()}},{key:"publish",value:(a=M(se.mark((function e(t){var r,n,i,o;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some((function(e){return e.joined}))?o.push.apply(o,ke(ke(r).map((function(e){var t;return null===(t=n.groups.get(e))||void 0===t||null===(t=t.audioInfo)||void 0===t?void 0:t.label})).filter((function(e){return!!e})))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"unpublish",value:function(e){var t=this,r=new Set(e.map((function(e){return e.getTrackId()}))),n=ke(this.sessionManager.sessions.values()).filter((function(e){var t;return e instanceof Zn&&r.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())}));return n.forEach((function(e){t.reporter.trace.unpublish(e.id)})),this.sessionManager.batchUnPublish(n)}},{key:"getRemoteTrack",value:function(e,t){var r=this;if(!t.mediaStream)return null;var n=this.userManager.users.get(e.uid);if("audio"===e.mediaType){var i=this.remoteAudioTrack;return this.remoteAudioTrack=Ae(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",(function(){r.remoteAudioTrack.emit("first-frame-decoded")})),this.remoteAudioTrack}return n.getRemoteVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(n=M(se.mark((function e(t){var r=this;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.sessionManager.batchSubscribe(t.map(this.handleSubscribeParam)).then(function(){var e=M(se.mark((function e(n){var i;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=[],t.forEach((function(e,t){var o=e.auxiliary,a=e.uid,s=n[t],c=s.error,u=s.subscription;i.push({uid:a,auxiliary:o,error:c,track:r.getRemoteTrack(e,u)})})),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){var t,r=this,n=[],i=Di(e);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.handleSubscribeParam(Li(Li({},o),{},{action:"unsubscribe"})),s=a.session,c=a.stream,u=a.user,l=a.uid;this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:l}),c&&n.push(Li({stream:c,user:u,session:s},o))}}catch(e){i.e(e)}finally{i.f()}return n.length?this.sessionManager.batchUnscribe(n).then((function(e){for(var t=0,i=n;t<i.length;t++){var o,a=i[t],s=a.mediaType,c=a.user,u=a.auxiliary;if("audio"===s)r.updateSubscribedAudioStream(!1,""),null===(o=r.remoteAudioTrack)||void 0===o||o.stop(),r.remoteAudioTrack=null;else if(u){var l;null===(l=c.auxiliaryTrack)||void 0===l||l.stop(),c.auxiliaryTrack=null}else{var d;null===(d=c.videoTrack)||void 0===d||d.stop(),c.videoTrack=null}}return e})):Promise.resolve()}},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new i(o.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream)throw new i(o.InvaildState,"you were subscribed group or channel already");return this.sessionManager.batchSubscribe([{stream:r,uid:e}]).then((function(n){return t.updateSubscribedAudioStream(!0,r.id),t.remoteAudioTrack=Ae(n[0].subscription.mediaStream,"audio",e,t.remoteAudioTrack),t.remoteAudioTrack}))}},{key:"unsubscribeGroup",value:function(e){var t=this,r=this.getStream({groupId:e});if(!r)throw new i(o.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream!==r.id)throw new i(o.InvaildState,"you were not subscribed the group");return this.sessionManager.batchUnscribe([{stream:r,session:this.sessionManager.getSessionByStreamId(r.id)}]).then((function(){r.id===t.subscribedAudioStream&&(t.updateSubscribedAudioStream(!1,""),t.remoteAudioTrack.stop(),t.remoteAudioTrack=null)}))}},{key:"setRemoteStreamType",value:function(e,t,r){this.reporter.log.info("setRemoteStreamType",e,t,r);var n=this.getStream({uid:e,mediaType:"video",auxiliary:r}),i=this.sessionManager.getSessionByStreamId(n.id),o=Ct(t,Ee(n));return i.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then((function(e){var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)}))}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then((function(){t.micMixedGroups.delete(r)}))}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then((function(){t.micMixedGroups.delete(e)}))}},{key:"mixGroupAudio",value:function(e,t,r){return this.signaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(r=M(se.mark((function e(t,r){var n,i,o,a=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=!(a.length>2&&void 0!==a[2])||a[2],i=[],null!=r&&i.push(this.groupManager.groups.get(r).audioInfo.label),!this.localTracks.includes(t)){e.next=18;break}if(o=this.streamManager.getStreamByTrackId(t.getTrackId()),null==r){e.next=14;break}return e.next=8,this.mixGroupAudio(o.id,i[0],"mix");case 8:if(this.micMixedGroups.add(r),!n){e.next=12;break}return e.next=12,this.mixGroupAudio(o.id,"common","unmix");case 12:e.next=16;break;case 14:return e.next=16,this.mixGroupAudio(o.id,"common","mix");case 16:e.next=22;break;case 18:return n||i.push("common"),e.next=21,this.sessionManager.batchPublish([t],i);case 21:this.micMixedGroups.add(r);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"unpublishFromGroup",value:(t=M(se.mark((function e(t,r){var n,i,o,a=arguments;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=a.length>2&&void 0!==a[2]&&a[2],i=this.groupManager.groups.get(r).audioInfo.label,o=this.streamManager.getStreamByTrackId(t.getTrackId()),e.next=5,this.mixGroupAudio(o.id,i,"unmix");case 5:if(this.micMixedGroups.delete(r),!n){e.next=9;break}return e.next=9,this.mixGroupAudio(o.id,"common","mix");case 9:case"end":return e.stop()}}),e,this)}))),function(e,r){return t.apply(this,arguments)})}]);var t,r,n,a,s}();function Gi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Gi=function(){return!!e})()}var Ui={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},Vi=function(){function e(t){var r,n,i,o,a;return C(this,e),n=this,i=F(i=e),r=N(n,Gi()?Reflect.construct(i,[],F(n).constructor):i.apply(n,o)),Object.defineProperty(r,"audioDeviceBufferReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioDeviceBufferInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"makeReport",{enumerable:!0,configurable:!0,writable:!0,value:(a=M(se.mark((function e(){var t,n,i,o,a;return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,r.client.getLocalAudioStats();case 2:return t=e.sent,n=t.audioLevel,e.next=6,r.client.getRemoteAudioStats();case 6:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:We(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 11:case"end":return e.stop()}}),e)}))),function(){return a.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},Ui),r.client=t,r}return U(e,Xr),L(e)}();function Bi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function qi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Bi(Object(r),!0).forEach((function(t){ce(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Bi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Hi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Yi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Yi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Yi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Qi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Qi=function(){return!!e})()}var Ji=function(){function t(){var e,r,n,i;return C(this,t),r=this,n=F(n=t),e=N(r,Qi()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(e,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"id",{enumerable:!0,configurable:!0,writable:!0,value:g(6)}),Object.defineProperty(e,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:E(e.id)}),Object.defineProperty(e,"channel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(e,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),e.channel=new Fi(e,e.reporter),e.handleVisibilitychange=e.handleVisibilitychange.bind(e),e.handleNetworkQuality=e.handleNetworkQuality.bind(e),e.handleConnectionChangeEvent=e.handleConnectionChangeEvent.bind(e),e.handlePageUnload=e.handlePageUnload.bind(e),e.init(),e}return U(t,c),L(t,[{key:"remoteUsers",get:function(){return this.channel.userManager.remoteUsers}},{key:"groups",get:function(){return this.channel.groups}},{key:"userId",get:function(){var e;return(null===(e=this.channel.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.channel.localTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.channel.internalChannel)||void 0===e?void 0:e.connectionState)||"disconnected"}},{key:"init",value:function(){this.syncStatTimer&&(v(this.syncStatTimer,"interval"),this.syncStatTimer=null),this.currentClientState="",this.channelName="",this.channel.clear(),this.removeEventListeners(),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.clientStatSync=[0,0,0,0,0,0]}},{key:"join",value:function(e){var t=this;return this.addEventListeners(),this.channel.join(e).then((function(r){var n;return t.channelName=e.channel,t.monitor=new Vi(t),t.monitor.on("audio-device-buffer",(function(e){t.reporter.metric.audioDeviceBuffer(e)})),t.syncStatTimer=d((function(){t.sendClientStatToRemote()}),2e3,"interval"),{remoteUsers:t.remoteUsers,timeLeft:null===(n=r.room)||void 0===n?void 0:n.timeLeft}})).catch((function(e){throw t.init(),e}))}},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.reporter.log.info("setRemoteDefaultVideoStreamType",e),this.channel.defaultVideoStreamType=e}},{key:"leave",value:function(){this.reporter.log.info("leave"),this.channel.leave(),this.init()}},{key:"publish",value:function(e){var t=this;if(this.reporter.log.info("publish",(Array.isArray(e)?e:[e]).map((function(e){return e.trackMediaType}))),"connected"!==this.connectionState)return Promise.reject(new i(o.PublishNotJoinChannel));var r,n=(Array.isArray(e)?e:[e]).filter((function(e){return e instanceof Xt&&!t.localTracks.includes(e)})),a=n.concat(this.localTracks),s=ce(ce(ce(ce({},z.CAMERA,0),z.SCREENCAST,0),K.MIC,0),K.MIXED,0),c=Hi(a);try{for(c.s();!(r=c.n()).done;){var u=r.value;if(s[u.source]++,s[u.source]>=2)throw new i(o.QuotaLimitExceed,"".concat(u.source," published already"))}}catch(e){c.e(e)}finally{c.f()}if(!n.length)throw new i(o.PublishNoStream);return this.channel.publish(n)}},{key:"unpublish",value:function(e){var t=Array.isArray(e)?e:[e];return e||(t=this.localTracks),this.reporter.log.info("unpublish",t.map((function(e){return e.trackMediaType}))),this.channel.unpublish(t)}},{key:"subscribe",value:(n=M(se.mark((function e(t,r,n){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.reporter.log.info("subscribe",t,r),"connected"===this.connectionState){e.next=3;break}throw new i(o.SubscribeNotJoinChannel);case 3:return e.abrupt("return",this.channel.batchSubscribe([{uid:t,mediaType:r,action:"subscribe",auxiliary:n}]).then((function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n})));case 4:case"end":return e.stop()}}),e,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){if(Array.isArray(e)&&e.length){if(this.reporter.log.info("batchSubscribe",e),"connected"!==this.connectionState)throw new i(o.SubscribeNotJoinChannel);return this.channel.batchSubscribe(e.map((function(e){return qi(qi({},e),{},{action:"subscribe"})})))}}},{key:"unsubscribe",value:(r=M(se.mark((function e(t,r,n){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("unsubscribe",t,r),e.abrupt("return",this.channel.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r,action:"unsubscribe"}]).then((function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){if(Array.isArray(e)&&e.length)return this.reporter.log.info("batchUnsubscribe",e),"connected"!==this.connectionState?Promise.reject(new i(o.SubscribeNotJoinChannel)):this.channel.batchUnsubscribe(e.map((function(e){return qi(qi({},e),{},{action:"unsubscribe"})})))}},{key:"getLocalAudioStats",value:function(){return this.channel.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.channel.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:function(e,t,r){var n=this;this.reporter.log.info("setRemoteVideoStreamType",e,t);var i=this.remoteUsers.find((function(t){return t.userId===e}));return null!=i&&i.relatedStreams?this.channel.setRemoteStreamType(e,t,r).then((function(){n.emit("stream-type-changed",e,t,r)})):(this.reporter.log.warn("".concat(e," videoTrack not existed")),Promise.reject("viedoTrack doesnt exiested"))}},{key:"getRemoteVideoStats",value:function(){return this.channel.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.channel.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach((function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[ve])||void 0===r?void 0:r[oe.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[ve])||void 0===n?void 0:n[oe.UPLINK])||0)}})),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.reporter.log.debug("connectionStateChange from ".concat(t," to ").concat(e," ").concat(r||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var e=this,t=this.clientStatSync.join("");if(t!==this.currentClientState){var r=Je(null,t[oe.UPLINK]),n=Je(null,this.currentClientState[oe.UPLINK]),i=Je(null,t[oe.DOWNLINK]),o=Je(null,this.currentClientState[oe.DOWNLINK]);r===n&&i===o||this.channel.userManager.setParticipantProperties(t).catch((function(t){e.reporter.log.debug("setParticipantProperties error ".concat(m(t)))})),this.currentClientState=t}}},{key:"handleVisibilitychange",value:function(){var t="visible"!==document.visibilityState,r=t?T.APP_BACKGROUND:T.APP_FOREGROUND;(e.isAndroid()||e.isIOS())&&(this.reporter.sender.sendEvent(r),this.clientStatSync[oe.BACKGROUND_MODE]=Number(t))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[oe.UPLINK]=e,this.clientStatSync[oe.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.reporter.log.info("leave for ".concat(e.type)),this.leave())}},{key:"addEventListeners",value:function(){window.addEventListener(e.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.addEventListener("visibilitychange",this.handleVisibilitychange),this.channel.sessionManager.on("network-quality",this.handleNetworkQuality),this.channel.signaling.on("connection-state-change",this.handleConnectionChangeEvent)}},{key:"removeEventListeners",value:function(){window.removeEventListener(e.isSafari()?"beforeunload":"pagehide",this.handlePageUnload),document.removeEventListener("visibilitychange",this.handleVisibilitychange),this.channel.sessionManager.off("network-quality",this.handleNetworkQuality),this.channel.signaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(e){var t=e.userData,r=e.groupId,n=new TextEncoder;if(!r||n.encode(r).length>64)throw new i(o.InvaildArgument,"join group with invalid groupId");if(t){var a=new TextEncoder;if("string"!=typeof t||a.encode(t).length>64)throw new i(o.InvaildArgument,"join group with invalid userData")}return this.channel.joinGroup(e)}},{key:"leaveGroup",value:function(e){return this.channel.leaveGroup({groupId:e,publishAudioToChannel:!1})}},{key:"setGroupName",value:function(e,t){var r=new TextEncoder;if(!t||r.encode(t).length>64)throw new i(o.InvaildArgument,"update group with invalid name");return this.channel.setGroupProperties(e,{key:"name",value:t})}},{key:"subscribeGroup",value:function(e){return this.channel.subscribeGroup(e)}},{key:"unsubscribeGroup",value:function(e){return this.channel.unsubscribeGroup(e)}},{key:"mixAudioToGroup",value:function(e,t,r){if("audio"!==e.trackMediaType)throw new i(o.InvaildArgument,"only support publish audio to group");if("connected"!==this.connectionState)throw new i(o.PublishNotJoinChannel);if(t){if(this.reporter.log.info("mix audio track:".concat(e.getTrackId()," to group ").concat(r)),null==r&&this.channel.micMixedGroups.size)throw new i(o.InvaildState,"cannot mix audio to channel while mixing to others group");return this.channel.publishToGroup(e,r,!0)}if(this.reporter.log.info("unmix audio track:".concat(e.getTrackId()," from group ").concat(r)),!this.channel.micMixedGroups.has(r))throw new i(o.InvaildState,"cannot unmix audio from the unmixed group");return this.channel.unpublishFromGroup(e,r)}},{key:"dismissGroup",value:function(e){return this.channel.dismissGroup(e)}},{key:"register",value:function(e){e.attach(this.channel.internalChannel,this.channel)}},{key:"ungister",value:function(e){e.detach(this.channel.internalChannel)}}]);var r,n}(),Wi={height:360,width:640};function Ki(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ki=function(){return!!e})()}ct();var zi=t().log,$i=function(){function e(){var t,r,n,i;if(C(this,e),r=this,n=F(n=e),t=N(r,Ki()?Reflect.construct(n,[],F(r).constructor):n.apply(r,i)),Object.defineProperty(t,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t.VERSION=de,!ye.checkSupported())return N(t);var o=Le.getInstance();return o.on("camera-changed",(function(e){t.emit("camera-changed",e)})),o.on("microphone-changed",(function(e){t.emit("microphone-changed",e)})),o.on("playback-device-changed",(function(e){t.emit("playback-device-changed",e)})),y.on("autoplay-failed",(function(e){t.emit("autoplay-failed",e)})),t}return U(e,c),L(e,[{key:"createClient",value:function(){return zi.info("createClient"),new Ji}},{key:"checkSystemRequirements",value:function(){return zi.info("checkSystemRequirements"),ye.checkSupported()}},{key:"getSupportedCodec",value:function(){return zi.info("getSupportedCodec"),ye.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return zi.info("createCameraVideoTrack",e),ir(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return zi.info("createMicrophoneAudioTrack",e),nr(e)}},{key:"createCustomVideoTrack",value:function(e){return zi.info("createCustomVideoTrack",e),sr(e)}},{key:"createCustomAudioTrack",value:function(e){return zi.info("createCustomAudioTrack",e),cr(e)}},{key:"createScreenVideoTrack",value:function(e){return zi.info("createScreenVideoTrack",e),or(e)}},{key:"createMicrophoneAndCameraTracks",value:(t=M(se.mark((function e(t,r){return se.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return zi.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",ar(t,r));case 2:case"end":return e.stop()}}),e)}))),function(e,r){return t.apply(this,arguments)})},{key:"getCameras",value:function(){return zi.info("getCameras"),Le.getCameras()}},{key:"getDevices",value:function(){return zi.info("getDevices"),Le.getDevices()}},{key:"getPlaybackDevices",value:function(){return zi.info("getPlaybackDevices"),Le.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return zi.info("getMicrophones"),Le.getMicrophones()}},{key:"setLogLevel",value:function(e){I(e),zi.info("setLogLevel",e)}},{key:"setClientConfig",value:function(e){zi.info("setClientConfig",e),Oe.setClientConfig(e)}}]);var t}(),Xi=new $i;export{K as AudioSourceInfo,ue as AudioSourceState,Wi as FALLBACK_SUB_VIDEO_PROFILE,z as VideoSourceInfo,Xi as default};
|