dingrtc 3.6.2-fix.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("webrtc-adapter");var e=require("@dingrtc/shared"),t=require("sdp-transform"),r=require("@dingrtc/channel");function n(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 i(e){return function(){var t=this,r=arguments;return new Promise((function(i,o){var a=e.apply(t,r);function s(e){n(a,i,o,s,c,"next",e)}function c(e){n(a,i,o,s,c,"throw",e)}s(void 0)}))}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e){return a="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},a(e)}function s(e){var t=function(e,t){if("object"!=a(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=a(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==a(t)?t:t+""}function c(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,s(n.key),n)}}function u(e,t,r){return t&&c(e.prototype,t),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e,t){if(t&&("object"==a(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 l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function f(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&&p(e,t)}function v(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var m={exports:{}},h={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}(h);var y=h.exports;!function(e){var t=y.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=Object.create((t&&t.prototype instanceof S?t:S).prototype),o=new M(n||[]);return s(i,"_invoke",{value:A(e,r,o)}),i}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 m="suspendedStart",h="suspendedYield",y="executing",g="completed",b={};function S(){}function k(){}function P(){}var E={};p(E,u,(function(){return this}));var w=Object.getPrototypeOf,T=w&&w(w(x([])));T&&T!==o&&a.call(T,u)&&(E=T);var O=P.prototype=S.prototype=Object.create(E);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=m;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=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===m)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:h,u.arg===b)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=g,r.method="throw",r.arg=u.arg)}}}function C(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,C(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 _(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 D(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function M(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(_,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(O,"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(O),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(O),p(O,l,"Generator"),p(O,u,(function(){return this})),p(O,"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,M.prototype={constructor:M,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(D),!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(this.prev>=o.tryLoc){var c=a.call(o,"catchLoc"),u=a.call(o,"finallyLoc");if(c&&u){if(o.catchLoc>this.prev)return r(o.catchLoc,!0);if(o.finallyLoc>this.prev)return r(o.finallyLoc)}else if(c){if(o.catchLoc>this.prev)return r(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(o.finallyLoc>this.prev)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(this.prev>=n.tryLoc&&a.call(n,"finallyLoc")&&n.finallyLoc>this.prev){var i=n;break}}i&&("break"===e||"continue"===e)&&t>=i.tryLoc&&i.finallyLoc>=t&&(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),D(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;D(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}(m);var g=(0,m.exports)(),b=g;try{regeneratorRuntime=g}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=g:Function("r","regeneratorRuntime = r")(g)}var S,k,P,E,w,T,O,I,R,A,C,_,D,M,x=v(b);function j(e,t,r){return(t=s(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"}(S||(S={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(k||(k={})),exports.AudioSourceInfo=void 0,(P=exports.AudioSourceInfo||(exports.AudioSourceInfo={})).MIC="mic",P.SCREENCAST="screen-cast",P.MIXED="mixed",exports.VideoSourceInfo=void 0,(E=exports.VideoSourceInfo||(exports.VideoSourceInfo={})).CAMERA="camera",E.SCREENCAST="screen-cast",E.MIXED="mixed",function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(w||(w={})),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"}(T||(T={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(O||(O={})),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"}(I||(I={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(R||(R={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(A||(A={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(C||(C={})),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"}(_||(_={})),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"}(D||(D={})),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"}(M||(M={}));var L,N={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]};exports.AudioSourceState=void 0,(L=exports.AudioSourceState||(exports.AudioSourceState={})).Playing="playing",L.Paused="paused",L.Stopped="stopped";var V="3.6.1",G=-999,U="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0});var F="onertc_state_sync",B="onertc_internal_track_event",q=function(e){return{width:N[e][0],height:N[e][1]}},H=function(e){return"object"===a(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST},Y=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&&(n.deviceId=e.Environment.isSafari()?t.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},J=function(t){if(!e.isObject(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,n=t.video;if(!H(t)&&"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(H(t)&&"object"===a(r)&&r.source!==exports.AudioSourceInfo.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(i.audio="object"===a(r)&&r.source===exports.AudioSourceInfo.MIC||"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST?Y(r):t.audio,"object"===a(n)){var o,s=n.frameRate,c=n.deviceId,u=n.source,d=n.facingMode,l=n.displaySurface,p=n.dimension;i.video=Object.create({}),e.isNumber(s)&&(i.video.frameRate=Math.min(n.frameRate,30)),p&&(o=q(p)),o&&o.width&&o.height&&(u===exports.VideoSourceInfo.SCREENCAST?(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.width})),e.isString(c)&&c&&(i.video.deviceId={exact:c}),u===exports.VideoSourceInfo.SCREENCAST&&(e.Environment.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 H(t)?navigator.mediaDevices.getDisplayMedia(i):navigator.mediaDevices.getUserMedia(i)};function W(){return W="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var n=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=l(e)););return e}(e,t);if(n){var i=Object.getOwnPropertyDescriptor(n,t);return i.get?i.get.call(3>arguments.length?e:r):i.value}},W.apply(null,arguments)}function Q(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function K(e,t){if(e){if("string"==typeof e)return Q(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)?Q(e,t):void 0}}function z(e){return function(e){if(Array.isArray(e))return Q(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||K(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.")}()}var $,X,Z=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},ee=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},te=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r>0||(r=1),r},re=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},ne=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return 0>r&&(r=e),r},ie=new Map,oe=function(t){return new Promise((function(r){e.addTimer(r,1e3*t)}))},ae=e.getReporter().log,se="rtc-intersecting",ce="visible",ue="invisible",de=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],le=function(e){return"".concat(null==e?void 0:e.getAttribute(U),"-").concat(null==e?void 0:e.rtcPurpose)},pe=function(){return u((function t(r,n){var i=this;o(this,t),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 e.Debouncer}),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(){i.mediaElementPool.forEach((function(e){return i._resetMediaElement(e)})),i.mediaElementPool=[],i.allElements.clear(),i.mediaElementsInUse.forEach((function(e){return i._resetMediaElement(e)})),i.mediaElementsInUse=[],document.removeEventListener("click",i._onUserInteraction),document.removeEventListener("touchstart",i._onUserInteraction),document.removeEventListener("visibilitychange",i._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),i.mediaPlaybackCheckInterval&&(e.removeTimer(i.mediaPlaybackCheckInterval,"interval"),i.mediaPlaybackCheckInterval=null),[].concat(z(i.mediaElementPool),z(i.mediaElementsInUse)).forEach((function(e){var t;return null===(t=i.observer)||void 0===t?void 0:t.unobserve(e)}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(e){i.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject;if(t.error){var n="".concat(e,": ").concat(le(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=Z(r);ae.debug(n,o),"visible"===document.visibilityState&&ee(r)&&t.load()}if(t.paused){var a=!1;if(i.hasActivated&&"video"===i.mediaKind?function(e){return e&&e.getAttribute(se)===ce}(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(le(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(se),", mediaStream="),c=Z(r);ae.error(s,c),ee(r)&&t.load(),t.paused&&t.play().catch((function(e){console.error("inPoll",e)}))}}}})),i.debouncer.debounce(i._tryReloadOnCurrentTimeFreeze.bind(i,e),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(e){i.mediaElementsInUse.forEach((function(t){if(t.srcObject){var r=t.srcObject,n="video"===i.mediaKind?r.getVideoTracks()[0]:void 0;if(!t.paused&&i.currentTimeOfLastCheckMap.get(t)===t.currentTime&&!0!==(null==n?void 0:n.muted)){var o="".concat(e,": ").concat(le(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=Z(r);return ae.error(o,a),void("visible"===document.visibilityState&&ee(r)&&t.load())}i.currentTimeOfLastCheckMap.set(t,t.currentTime)}}))}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){i._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="error event on ".concat(i.mediaKind," playback, mediaStream="),n=Z(null==t?void 0:t.srcObject);ae.error(r,n,null==t?void 0:t.error)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="pause event on ".concat(i.mediaKind," playback, mediaStream="),n=Z(null==t?void 0:t.srcObject);ae.error(r,n,null==t?void 0:t.error)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target,r="play event on ".concat(i.mediaKind," playback, mediaStream="),n=Z(null==t?void 0:t.srcObject);ae.debug(r,n)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=[].concat(z(i.mediaElementPool),z(i.mediaElementsInUse));if(!i.hasActivated&&(i.hasActivated=!0,t.forEach((function(e){e.load()})),i._activatedListener))try{i._activatedListener()}catch(t){ae.error("error occurred when exec activatedListener",e.tryJsonStringify(t))}i._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),this.mediaElementsInUse=[],this.mediaElementPool=[],this.mediaKind=r,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(se,ce):null===(r=e.target)||void 0===r||r.setAttribute(se,ue)}))})));for(var a=0;n>a;a++){var s,c=this._createElement();null===(s=this.observer)||void 0===s||s.observe(c),this.addAtttribute(c),c.setAttribute(U,"".concat(r,"-").concat(a)),this.mediaElementPool.push(c),this.allElements.add(c)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=e.addTimer((function(){i.hasActivated&&i._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")}),4e3,"interval")}),[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(U,"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){de.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}}])}(),fe=function(){return $||he(),$},ve=function(){return X||he(),X},me=e.Environment.isIOS()||e.Environment.isAndroid()?9:25,he=function(){$||($=new pe("audio",2)),X||(X=new pe("video",me))},ye=new AudioContext,ge=function(e){var t=e.getAudioTracks(),r=ye.createMediaStreamDestination();return t.forEach((function(e){ye.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},be=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;n.length>o;++o)n[o]=i[o]/128-1}for(var a=0,s=0;n.length>s;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},Se=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")};function ke(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ke=function(){return!!e})()}var Pe=e.getReporter(),Ee=Pe.log,we=Pe.trace,Te=new Map,Oe=function(){function t(r,n){var i,a,s,c;return o(this,t),a=this,s=l(s=t),i=d(a,ke()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(i,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"isPlaying",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(i,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:we}),Object.defineProperty(i,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"element",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"playerConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"wrapperDom",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),i.trackId=e.createUuid(),r?(i.trackMediaType=r.kind,i.trackSettings=r.getSettings()):n&&(i.trackMediaType="audio"),"audio"===i.trackMediaType&&(i.audioContext=ye,i.analyser=i.audioContext.createAnalyser()),i.setMediaStreamTrack(r,n),i}return f(t,e.EventEmitter),u(t,[{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(t,r){var n=this,i=this.mediaStreamTrack;if(i&&(i.onended=null),t||r){var o;if(i&&t&&(t.enabled=i.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),t)this.sourceNode=null===(o=this.audioContext)||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([t]));else if(r){var a,s=ge(r);this.sourceNode=null===(a=this.audioContext)||void 0===a?void 0:a.createMediaStreamSource(new MediaStream([s]))}t?(this.mediaStreamTrack=t,this.mediaStreamTrack.onended=function(){n.source===exports.VideoSourceInfo.SCREENCAST?n.logger.sendEvent("SCREEN_DEVICE_STOP"):n.source===exports.AudioSourceInfo.MIC?new e.DingRTCError(e.ErrorCode.MicInterrupt):n.source===exports.VideoSourceInfo.CAMERA&&new e.DingRTCError(e.ErrorCode.CameraInterrupt)}):r&&(this.sfuStream=r)}}},{key:"replaceTrack",value:function(e,t){Ee.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e)}},{key:"replaceTrackInner",value:function(e,t){this.setMediaStreamTrack(e,t),this.emit(B,"replace",this),this.isPlaying&&this.innnerPlay()}},{key:"setSource",value:function(e){e===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_START"):e===exports.VideoSourceInfo.SCREENCAST?this.logger.sendEvent("SCREEN_DEVICE_START"):e===exports.AudioSourceInfo.MIC&&this.logger.sendEvent("AUDIO_DEVICE_START"),this.source=e}},{key:"stop",value:function(){this.isPlaying=!1,Ee.info("stop paly track ".concat(this.getTrackId())),this.element&&(Te.get(this.wrapperDom)===this&&Te.delete(this.wrapperDom),this.wrapperDom&&(this.wrapperDom.removeChild(this.element),this.wrapperDom=null),this.element.pause(),this.element.srcObject=null,"audio"===this.trackMediaType?fe().pushElement(this.element):ve().pushElement(this.element),this.setMediaElement(null))}},{key:"innnerPlay",value:function(t,r){var n=this,i=this.element;r&&(this.playerConfig=r);var o,a,s,c=this.playerConfig||{},u=c.mirror,d=c.fit;if(t&&(o="string"==typeof t?document.querySelector(t):t,!document.contains(o)))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"wrapper dom not found");if(i){if(o&&this.wrapperDom&&o!==this.wrapperDom)return this.stop(),void this.innnerPlay(t,r);i.pause(),i.style.transform=!this.sourceMirror!=!u?"scaleX(-1)":"",i.srcObject=this.sfuStream||new MediaStream([this.getMediaStreamTrack()]),i.load()}else{if("audio"===this.trackMediaType){a=this.sfuStream||new MediaStream([this.getMediaStreamTrack()]),(s=fe().popElement()).srcObject=a,i=s;try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(t){Ee.debug("resume audioContext failed: ".concat(e.tryJsonStringify(t)))}}else{var l=Te.get(o);l&&l.stop();var p=function(e,t,r){var n=ve().popElement();n.style.width="100%",n.style.height="100%";var i=r.fit;return!0===r.mirror&&(n.style.transform="scaleX(-1)"),i&&(n.style.objectFit=i),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n}(o,new MediaStream([this.getMediaStreamTrack()]),{mirror:!this.sourceMirror!=!u,fit:d});this.wrapperDom=o,i=p,Te.set(this.wrapperDom,this)}this.setMediaElement(i)}i.paused&&i.play().then((function(){n.isPlaying=!0})).catch((function(t){"NotAllowedError"===t.name?(n.isPlaying=!1,Ee.error("autoplay failed",e.tryJsonStringify(t)),e.EventBus.emit("autoplay-failed",n)):Ee.warn("".concat(n.trackMediaType," play has exception"),e.tryJsonStringify(t))}))}},{key:"setMediaElement",value:function(e){this.element=e}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function Ie(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)||K(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.")}()}var Re=e.getReporter().log,Ae=new(function(){return u((function t(){o(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.Environment.system,this.browser=e.Environment.browserType,this.browserVersion=e.Environment.browserVersion}),[{key:"getSupportedCodec",value:(t=i(x.mark((function t(){var r,n,i;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return r={audio:[],video:[]},t.prev=1,(n=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"}),t.next=7,n.createOffer();case 7:if(i=t.sent.sdp){t.next=10;break}return t.abrupt("return",r);case 10:return n.close(),n=null,i.match(/ VP8/i)&&r.video.push("VP8"),i.match(/ VP9/i)&&r.video.push("VP9"),i.match(/ AV1/i)&&r.video.push("AV1"),i.match(/ H264/i)&&r.video.push("H264"),i.match(/ H265/i)&&r.video.push("H265"),i.match(/ opus/i)&&r.audio.push("OPUS"),i.match(/ PCMU/i)&&r.audio.push("PCMU"),i.match(/ PCMA/i)&&r.audio.push("PCMA"),i.match(/ G722/i)&&r.audio.push("G722"),t.abrupt("return",r);case 24:throw t.prev=24,t.t0=t.catch(1),Re.error("get supportedCodecs failed"),new e.DingRTCError(e.ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 28:case"end":return t.stop()}}),t,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.Environment.isChrome()||e.Environment.isFirefox()?parseInt(e.Environment.browserVersion,10)>=69:e.Environment.isOpera()?parseInt(e.Environment.browserVersion,10)>=45:e.Environment.isSafari()?parseInt(e.Environment.browserVersion,10)>=11:(e.Environment.isWeixin()||e.Environment.isQQBrowser(),!0);var a=t&&o;return Re.debug("checkSystemRequirements, api:",t,"browser",o),a}},{key:"isSupportScreenShare",value:function(){return!this.system.includes(e.SystemType.ANDROID)&&this.system!==e.SystemType.IOS&&((this.browser!==e.BrowserType.SAFARI||parseInt(this.browserVersion)>=13)&&((this.browser!==e.BrowserType.FIREFOX||parseInt(this.browserVersion)>=66)&&!!(navigator&&navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)))}}]);var t}());function Ce(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ce=function(){return!!e})()}var _e,De=new(function(){function t(){var e,r,n,i;return o(this,t),r=this,n=l(n=t),e=d(r,Ce()?Reflect.construct(n,[],l(r).constructor):n.apply(r,i)),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"grouptalk",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),e.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),e}return f(t,e.EventEmitter),u(t,[{key:"setClientConfig",value:function(t){var r=t||{},n=r.gslb,i=r.simulcast,o=r.audioSFU;"string"==typeof n&&(this.gslb=[n],e.setGslb(n)),Array.isArray(n)&&e.isString(n[0])&&(this.gslb=n,e.setGslb(n[0])),null!=i&&function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{};return!(!r.setParameters||!r.getParameters||e.Environment.isFirefox()||(e.Environment.isSafari()?14>parseInt(e.Environment.browserVersion):e.Environment.isChrome()&&81>parseInt(e.Environment.browserVersion)))}()&&(this.simulcast=!!i),null!=o&&(this.audioSFU=!!o)}}])}());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 xe(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(r),!0).forEach((function(t){j(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(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={}));var je=j(j(j(j(j({},_e.LLD,"lld"),_e.LD,"ld"),_e.SD,"sd"),_e.HD,"hd"),_e.FHD,"fhd"),Le={high:[1228800,2764800],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},Ne=function(e,t){var r=Ve(e,t),n=function(e,t){var r={high:M.FHD,low:M.LD,FHD:M.FHD,HD:M.HD,SD:M.SD,LD:M.LD},n=r[e]||M.None,i=t[t.length-1].width*t[t.length-1].height;if(Le[e][0]>i){var o=Object.entries(Le).find((function(e){var t=Ie(e,2)[1];return i>t[0]&&t[1]>=i}));n=r[Ie(o,1)[0]]}return n}(e,t);return{resolution:r,resolutionLevel:n}},Ve=function(e,t){var r=Le[e],n=t.length;if(t[0].width*t[0].height>Le.FHD[1])return t[0];for(var i=0;n>i;i++){var o=t[i].width*t[i].height;if(o>=r[0]&&r[1]>=o)return t[i]}for(var a=n-1;a>=0;a--){if(r[1]>t[a].width*t[a].height)return t[a]}return t[0]},Ge=[49152,76800,307200,1228800,2764800],Ue=[200,350,1e3,1800,2828],Fe=[[256,144],[320,180],[640,360],[1280,720],[1920,1080]],Be=[[256,192],[320,240],[640,480],[1280,960],[1920,1440]],qe=function(e,t){var r=_e.FHD,n=e*t;return n>Ge[_e.LLD]?n>Ge[_e.LD]?n>Ge[_e.SD]?n>Ge[_e.HD]?n>Ge[_e.FHD]||(r=_e.FHD):r=_e.HD:r=_e.SD:r=_e.LD:r=_e.LLD,r},He=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=Ue[qe(i.width,i.height)];r=Math.round(Math.max(n*o,50))}return r},Ye=function(e){var t=e.getMaxBitrate(),r=e.trackSettings,n=r.height,i=r.width,o=r.frameRate,a=[],s=qe(i,n);if(!De.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST)return[{maxFramerate:o,maxBitrate:t,scaleResolutionDownBy:1,active:!0,rid:"",minBitrate:Math.round((t+30)/2),targetWidth:i,targetHeight:n}];var c=s>_e.HD?3:2,u=function(e){var r=function(e,t,r,n){var i=0,o=0;if(r>=n)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=Fe[r][0],o=Fe[r][1];else if(4*t==3*e)i=Be[r][0],o=Be[r][1];else{var s=Math.sqrt(1*Fe[r][0]*Fe[r][1]/e/t);o=Math.round(t*(s=1*(i=(i=Math.round(e*s))+15&-16)/e))}return[i,o]}(i,n,e,s),a=Ie(r,2),c=a[1];return{targetWidth:a[0],rid:je[e],targetHeight:c,minBitrate:50,maxFramerate:o,maxBitrate:Math.round(Math.max(30,t*(Ue[e]/Ue[s]))),scaleResolutionDownBy:1/(c/n)}};s>_e.LLD&&a.push(xe({active:!1},u(_e.LLD))),s>_e.LD&&a.push(xe({active:c>1},u(_e.LD))),s>_e.SD&&a.push(xe({active:c>2},u(_e.SD))),s>_e.HD?(a.push(xe({active:!1},u(_e.HD))),a.push(xe({active:!0},u(_e.FHD)))):a.push(xe({active:!0},u(s)));for(var d=0,l=0;a.length>l;++l)0!=l&&(a[l].minBitrate=d),d=Math.round(Math.max((a[l].maxBitrate+a[l].minBitrate)/2,a[l].maxBitrate-400));return a.shift(),a};function Je(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 We(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Je(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Je(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Qe(e,t,r){return t=l(t),d(e,Ke()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function Ke(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ke=function(){return!!e})()}function ze(e,t,r,n){var i=W(l(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var $e=e.getReporter().log,Xe=function(){function t(e,r){var n;(o(this,t),n=Qe(this,t,[e]),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}),e)&&(n.muted=e.muted);return n.enabled=!0,n.isPlaying=!1,n.deviceId=r,n}return f(t,Oe),u(t,[{key:"setMediaStreamTrack",value:function(e){var r,n=this;ze(t,"setMediaStreamTrack",this)([e]),e&&(this.trackSettings=e.getSettings(),null===(r=this.element)||void 0===r||r.addEventListener("loadeddata",(function(){n.emit("first-frame-decoded")})),e.onended=function(){n.stop(),n.close&&n.close(),n.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay(e,t)}},{key:"setEnabled",value:function(t){return $e.info("setEnabled",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.enabled=t,this.emit(B,t?"unmute":"mute"),t?this.updateNewTrack():(null===(r=this.mediaStreamTrack)||void 0===r||r.stop(),this.setMediaStreamTrack(null),this.source===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"),Promise.resolve()));var r}},{key:"close",value:function(){var e;$e.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(B,"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===exports.VideoSourceInfo.CAMERA?this.logger.sendEvent("VIDEO_DEVICE_STOP"):this.source===exports.VideoSourceInfo.SCREENCAST&&this.logger.sendEvent("SCREEN_DEVICE_STOP"))}},{key:"setMuted",value:function(t){return $e.info("setMuted",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.muted=t,this.mediaStreamTrack.enabled=!t,this.emit(B,t?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var t=this;return $e.debug("gengrate new audioTrack"),new Promise((function(r,n){var i;J({audio:We(We({source:t.source},t.config),{},{deviceId:t.deviceId})}).then((function(e){i=e.getAudioTracks()[0]})).catch((function(r){try{var o=t.audioContext.createOscillator(),a=t.audioContext.createMediaStreamDestination();o.connect(a),i=a.stream.getAudioTracks()[0]}catch(t){$e.error("gengrate new audioTrack error",e.parseAudioDeviceError(r)),n(e.parseAudioDeviceError(r))}})).finally((function(){i&&r(i)}))}))}},{key:"getVideoTrack",value:function(){var t=this;return $e.debug("gengrate new videoTrack"),new Promise((function(r,n){var i;J({video:We(We({source:t.source},t.config),{},{deviceId:t.deviceId}),audio:!1}).then((function(e){i=e.getVideoTracks()[0],r(i)})).catch((function(t){$e.error("gengrate new videoTrack error",e.parseVideoDeviceError(t)),n(e.parseVideoDeviceError(t))}))}))}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,$e.debug("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t)})):void 0}},{key:"setDevice",value:(r=i(x.mark((function e(t){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if($e.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof tt)||"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 r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if($e.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(),Ze=function(){function t(e,r,n){var i;return o(this,t),(i=Qe(this,t,[e,r])).config=n,e&&(i.maxBitrate=He(e,n.frameRate,n.maxBitrate)),i}return f(t,Xe),u(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(t){var r=this;$e.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),t);var n=t.dimension,i=t.frameRate,o=t.maxBitrate,a=t.optimizationMode,s=t.mirror;if(i&&Number.isNaN(i))return Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid frameRate"));if(n&&!N[n])return Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid dimension"));!s!=!this.config.mirror&&(this.emit(B,"mirror",s),this.config.mirror=s),a&&a!==this.optimizationMode&&(this.config.optimizationMode=a,this.emit(B,"optimizationMode"));var c=!1;if(n&&this.config.dimension!==n&&(this.config.dimension=n,c=!0),i&&this.config.frameRate!==Math.min(30,i)&&(this.config.frameRate=Math.min(30,i),c=!0),o&&this.maxBitrate!==o&&(c=!0),!c)return Promise.resolve();var u=We({frameRate:this.config.frameRate},q(this.config.dimension)),d=this.getMediaStreamTrack();return null==d?void 0:d.applyConstraints(u).then((function(){r.maxBitrate=He(r.getMediaStreamTrack(),r.config.frameRate,o),r.emit(B,"republish",r)})).catch((function(t){var n=e.parseVideoDeviceError(t);throw $e.error("videoTrack ".concat(r.getTrackId()," setEncoderConfiguration error"),n),n}))}},{key:"getCurrentFrameData",value:function(){return $e.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:Se(this.element)}},{key:"play",value:function(e,r){return $e.info("local video play"),ze(t,"play",this)([e,r])}}])}(),et=function(){function e(t,r){return o(this,e),Qe(this,e,[t,r])}return f(e,Xe),u(e,[{key:"setVolume",value:function(e){$e.info("setVolume",e),this.isClosed||this.element&&(this.element.volume=e)}},{key:"getVolume",value:function(){if($e.info("getVolume"),!this.isClosed)return this.element?this.element.volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:be(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return $e.info("local audio play"),ze(e,"play",this)([])}}])}(),tt=function(){function e(t,r){var n;return o(this,e),(n=Qe(this,e,[t,r.deviceId,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return f(e,Ze),u(e)}(),rt=function(){function e(t,r){var n;return o(this,e),(n=Qe(this,e,[t,(r||{}).deviceId])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=n.audioContext.createAnalyser(),n}return f(e,et),u(e,[{key:"setVolume",value:function(e){$e.info("setVolume",e),this.isClosed||this.element&&(this.element.volume=e)}},{key:"getVolume",value:function(){if($e.info("getVolume"),!this.isClosed)return this.element?this.element.volume:void 0}}])}(),nt=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d,l;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n={AEC:!0,AGC:!0,ANS:!0},a=void 0===(o=(i=r||n).AEC)||o,c=void 0===(s=i.AGC)||s,d=void 0===(u=i.ANS)||u,t.prev=2,t.next=5,J({video:!1,audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:a,AGC:c,ANS:d}});case 5:return l=t.sent.getAudioTracks()[0],$e.info("MicrophoneAudioTrack created"),t.abrupt("return",new rt(l,Object.assign({},r,{AEC:a,AGC:c,ANS:d})));case 11:throw t.prev=11,t.t0=t.catch(2),e.parseAudioDeviceError(t.t0);case 14:case"end":return t.stop()}}),t,null,[[2,11]])})));return function(e){return t.apply(this,arguments)}}(),it=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=r.deviceId,i=r.facingMode,a=void 0===(o=r.dimension)?"VD_640x480":o,c=void 0===(s=r.optimizationMode)?"balanced":s,u=Math.min(30,r.frameRate||15),t.prev=2,t.next=5,J({video:{deviceId:n,source:exports.VideoSourceInfo.CAMERA,frameRate:u,dimension:a,facingMode:i},audio:!1});case 5:return d=t.sent.getVideoTracks()[0],$e.info("CameraVideoTrack created"),t.abrupt("return",new tt(d,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c})));case 11:throw t.prev=11,t.t0=t.catch(2),e.parseVideoDeviceError(t.t0);case 14:case"end":return t.stop()}}),t,null,[[2,11]])})));return function(e){return t.apply(this,arguments)}}(),ot=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=void 0===(n=r.displaySurface)?"monitor":n,a=void 0===(o=r.dimension)?"VD_1920x1080":o,c=void 0===(s=r.optimizationMode)?"detail":s,u=Math.min(r.frameRate||5,30),t.prev=2,t.next=5,J({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:i,frameRate:u,dimension:a},audio:!1});case 5:return(d=new Ze(t.sent.getVideoTracks()[0],null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.SCREENCAST),$e.info("ScreenVideoTrack created"),t.abrupt("return",[d]);case 12:throw t.prev=12,t.t0=t.catch(2),e.parseScreenShareError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[2,12]])})));return function(e){return t.apply(this,arguments)}}(),at=function(){var t=i(x.mark((function t(r,n){var i,o,a,s,c,u,d,l,p,f,v,m,h,y,g,b,S,k,P,E;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return i=Math.min(r.frameRate||15,30),o=r.deviceId,a=r.facingMode,c=void 0===(s=r.dimension)?"VD_640x480":s,d=void 0===(u=r.optimizationMode)?"balanced":u,l={AEC:!0,AGC:!0,ANS:!0},v=void 0===(f=(p=n||l).AEC)||f,h=void 0===(m=p.AGC)||m,g=void 0===(y=p.ANS)||y,t.prev=4,t.next=7,J({video:{deviceId:o,source:exports.VideoSourceInfo.CAMERA,frameRate:i,dimension:c,facingMode:a},audio:{deviceId:null==n?void 0:n.deviceId,source:exports.AudioSourceInfo.MIC,AEC:v,AGC:h,ANS:g}});case 7:return S=(b=t.sent).getVideoTracks()[0],k=b.getAudioTracks()[0],$e.info("CameraVideoTrack and MicrophoneTrack created"),P=new tt(S,Object.assign({},r,{frameRate:i,dimension:c,optimizationMode:d})),E=new rt(k,Object.assign({},Object.assign({},n,{AEC:v,AGC:h,ANS:g}))),t.abrupt("return",[P,E]);case 16:throw t.prev=16,t.t0=t.catch(4),e.parseVideoDeviceError(t.t0);case 19:case"end":return t.stop()}}),t,null,[[4,16]])})));return function(e,r){return t.apply(this,arguments)}}(),st=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(i=(n=r||{}).mediaStreamTrack,a=void 0===(o=n.dimension)?"VD_640x480":o,c=void 0===(s=n.optimizationMode)?"balanced":s,u=Math.min(r.frameRate||15,30),i instanceof MediaStreamTrack&&"video"===i.kind){t.next=4;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 4:return(d=new Ze(i,null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.CAMERA),t.abrupt("return",d);case 7:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),ct=function(){var t=i(x.mark((function t(r){var n,i;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if((n=(r||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){t.next=3;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 3:return(i=new et(n)).setSource(exports.AudioSourceInfo.MIC),t.abrupt("return",i);case 6:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();function ut(e,t,r,n){var i=W(l(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function dt(e,t,r){return t=l(t),d(e,lt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function lt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(lt=function(){return!!e})()}var pt,ft=e.getReporter().log,vt=function(){function e(t,r,n){var i;return o(this,e),i=dt(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 f(e,Oe),u(e,[{key:"getUserId",value:function(){return ft.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)}}])}(),mt=function(){function t(e,r,n){var i;return o(this,t),i=dt(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return f(t,vt),u(t,[{key:"getMediaStreamTrack",value:function(){return De.audioSFU?ge(this.sfuStream):ut(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){ft.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){ft.info("setVolume",e),this.element&&(this.element.volume=e)}},{key:"getVolume",value:function(){if(ft.info("getVolume"),this.element)return this.element.volume}},{key:"setSpeaker",value:function(t){var r=this;return ft.info("setSpeaker",t),new Promise((function(n,i){var o,a=r.element;a||i(new e.DingRTCError(e.ErrorCode.InvaildState,"please playout audio first")),a.setSinkId||i(new e.DingRTCError(e.ErrorCode.SpeakerSetNotSupported)),null===(o=a.setSinkId)||void 0===o||o.call(a,t).then((function(){r.deviceId=t,n()})).catch((function(t){i(e.parseAudioDeviceError(t))}))}))}},{key:"getVolumeLevel",value:function(){return be(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return ft.info("remote audio play"),ut(t,"innnerPlay",this,3)([])}}])}(),ht=function(){function e(t,r){return o(this,e),dt(this,e,[t,r])}return f(e,vt),u(e,[{key:"play",value:function(t,r){return ft.info("remote video play"),ut(e,"innnerPlay",this,3)([t,r])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(ft.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&ut(e,"innnerPlay",this,3)([]))}},{key:"setMediaElement",value:function(t){var r,n=this;ut(e,"setMediaElement",this,3)([t]),null===(r=this.element)||void 0===r||r.addEventListener("loadeddata",(function(){n.emit("first-frame-decoded")}))}},{key:"getCurrentFrameData",value:function(){return ft.info("getCurrentFrameData"),this.isPlaying?Se(this.element):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"}(pt||(pt={}));var yt=e.getProtobufRoot({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}}}}}}}),gt=yt.lookupType("signal_msg.Response"),bt=yt.lookupType("signal_msg.BatchNotification"),St=yt.lookupType("signal_msg.MediaMessage"),kt=yt.lookupType("signal_msg.StreamNotification");yt.lookupType("signal_msg.ProgressNotification");var Pt=yt.lookupType("signal_msg.ServerFailoverNotification"),Et=yt.lookupType("signal_msg.PublishRequest"),wt=yt.lookupType("signal_msg.SoacRequest"),Tt=yt.lookupType("signal_msg.UnpublishRequest"),Ot=yt.lookupType("signal_msg.StreamControlRequest"),It=yt.lookupType("signal_msg.SubscribeRequest"),Rt=yt.lookupType("signal_msg.SetStreamPropertiesRequest"),At=yt.lookupType("signal_msg.UnsubscribeRequest"),Ct=yt.lookupType("signal_msg.SubscriptionControlRequest"),_t=yt.lookupType("signal_msg.CreatePeerConnectionRequest"),Dt=yt.lookupType("signal_msg.ClosePeerConnectionRequest"),Mt=yt.lookupType("signal_msg.BatchPublishRequest"),xt=yt.lookupType("signal_msg.BatchUnpublishRequest"),jt=yt.lookupType("signal_msg.BatchSubscribeRequest"),Lt=yt.lookupType("signal_msg.BatchUnsubscribeRequest"),Nt=yt.lookupType("signal_msg.JoinGroupRequest"),Vt=yt.lookupType("signal_msg.SetGroupPropertiesRequest"),Gt=yt.lookupType("signal_msg.DismissGroupRequest"),Ut=yt.lookupType("signal_msg.LeaveGroupRequest"),Ft=yt.lookupType("signal_msg.SyncDataRequest"),Bt=yt.lookupType("signal_msg.SyncDataByIdsRequest"),qt=yt.lookupType("signal_msg.GroupChangeLog"),Ht=yt.lookupType("signal_msg.GroupListChangeLog"),Yt=yt.lookupType("signal_msg.SetParticipantPropertiesRequest"),Jt=yt.lookupType("signal_msg.QueryStreamsVerRequest"),Wt=yt.lookupType("signal_msg.QueryStreamsRequest");function Qt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Qt=function(){return!!e})()}var Kt=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Qt()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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=e,r.rpcId=0,r.reporter=e.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 f(t,e.EventEmitter),u(t,[{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",kt.decode(t)):"serverFailover"===e?this.emit("serverFailover",Pt.decode(t)):"media-message"===e?this.emit("media-message",St.decode(t)):"group"===e?this.emit("group",qt.decode(t)):"group-list"===e&&this.emit("group-list",Ht.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;bt.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=_t.encode(e).finish();return this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=Dt.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=jt.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=Vt.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=Lt.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=Mt.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=xt.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=Et.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){var t=Yt.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=wt.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=Tt.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=Ot.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=Rt.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=It.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=At.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=Ct.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=Jt.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=Wt.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=Nt.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=Ut.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=Gt.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=Ft.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=Bt.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=gt.decode(t);n.code===pt.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 zt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(zt=function(){return!!e})()}var $t=function(){function t(){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,zt()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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 s=e.getReporter().statsConfig;return r.interval=(null==s?void 0:s.statsIntervalMs)||2e3,r.start(),r}return f(t,e.EventEmitter),u(t,[{key:"start",value:function(){var t=this;this.stop(),this.makeReport&&this.makeReport(),this.timer=e.addTimer((function(){t.makeReport()}),this.interval,"interval")}},{key:"stop",value:function(){this.timer&&(e.removeTimer(this.timer,"interval"),this.timer=null)}}])}();function Xt(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 Zt(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xt(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xt(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function er(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 tr(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)?tr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 tr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function rr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(rr=function(){return!!e})()}var nr={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},ir={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},or=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,rr()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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 s=e.tracks.filter((function(e){return"video"===e.trackMediaType}))[0];return r.source=null==s?void 0:s.source,r.track=e.tracks[0],r.tranceiver=e.transceiver,r.lastVideoSendInfo=Object.assign({},ir),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({},nr),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 f(t,$t),u(t,[{key:"extractVideoMetrics",value:function(t){var r=this,n=Object.assign({source:this.source,trackStats:[]},ir,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=te(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.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=ne(i.framesSent||i.framesEncoded,o.framesSent||o.framesEncoded);i.sendFramesPerSecond=Math.round(a/u)}if(i.framesEncoded){var s=ne(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.Environment.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=er(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=Ie(t.value,2),o=i[1],a=this.lastVideoSendInfo.trackStats.get(i[0])||{},s=ne(o.framesSent,a.framesSent),c=ne(o.framesEncoded,a.framesEncoded),u=ne(o.keyFramesEncoded,a.keyFramesEncoded),d=ne(o.retransmittedBytesSent,a.retransmittedBytesSent),l=ne(o.retransmittedPacketsSent,a.retransmittedPacketsSent),p=ne(o.firCount,a.firCount),f=ne(o.pliCount,a.pliCount),v=ne(o.packetsSent,a.packetsSent),m=ne(o.packetsSentForLost,a.packetsSentForLost),h=ne(o.lostTimestamp,a.lostTimestamp),y=ne(o.packetsLost,a.packetsLost),g=ne(o.totalEncodeTime,a.totalEncodeTime),b=ne(o.qpSum,a.qpSum),S=Zt(Zt({sendFrameHeight:o.sendFrameHeight,sendFrameWidth:o.sendFrameWidth,qualityLimitationReason:o.qualityLimitationReason},o),{},{deltaQbSum:b,deltaPacketsSent:v,deltaPacketsLost:y,deltaFramesSent:s,deltaTimestampForLost:h,deltaFramesEncoded:c,deltaKeyFramesEncoded:u,deltaFirCount:p,deltaEncodedTime:g,deltaPliCount:f,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:d,deltaRetransmittedPacketsSent:l});r.push(S)}}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){for(var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime,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=ne(e.timestamp,this.lastVideoSendInfo.timestamp),l=0,p=0;n.length>p;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),l=Math.max(f.deltaTimestampForLost),f.sendFrameWidth&&(f.deltaFramesEncoded||f.deltaFramesSent)&&(s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)}),s.attr_encoded_framerate_sim.push(j({},p,Math.round(1e3*(f.deltaFramesEncoded||f.deltaFramesSent)/d))),s.attr_encode_qp_sim.push(j({},p,Math.round((f.deltaQbSum||0)/(f.deltaFramesEncoded||f.deltaFramesSent))))),f.deltaPacketsLost&&f.deltaPacketsSentForLost&&c.push(f.deltaPacketsLost/f.deltaPacketsSentForLost*255)}for(var v=0,m=Object.entries(s);m.length>v;v++){var h=Ie(m[v],2),y=h[1];t[h[0]]=y.length?JSON.stringify(y):""}var g=0,b=ne(o,this.lastVideoSendInfo.totalFramesEncoded),S=ne(a,this.lastVideoSendInfo.totalEncodedTime);b&&S&&(g=Math.round(1e3*S/b));var k=ne(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=d,t.attr_bitrate=d>0?Math.min(Math.round(8*k*1e3/d),2e7):0,t.attr_enc_average_elapsed_ms=g,this.videoSendReport=t,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),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({},nr,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.sampleRate;r.channels=n.channelCount,r.sampleRate=i}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(ne(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*ne(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/ne(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 t,r,n=this,i=this.tranceiver,o=this.pc;if(!o||null==i||null===(t=i.sender)||void 0===t||!t.track)return Promise.resolve({});if(null==o||!o.getStats)throw new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"getStats is not supported");return null===(r=this.pc.getStats(i.sender.track))||void 0===r?void 0:r.then((function(e){return{videoMetrics:n.source?n.extractVideoMetrics(e):void 0,audioMetrics:n.source?void 0:n.extractAudioMetrics(e)}}))}}])}();function ar(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 sr(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)?sr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 sr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function cr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(cr=function(){return!!e})()}var ur={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},dr={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},lr=function(){function t(r){var n,i,a,s,c;o(this,t),a=this,s=l(s=t),i=d(a,cr()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(i,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var u=r.connection,p=r.transceiver,f=r.uid,v=r.stream,m=r.transceivers;return i.connection=u,i.pc=u.pc,i.tranceiver=p,i.tranceivers=m,i.firstReportTimer=e.addTimer((function(){i.getStats().then((function(e){i.makeFirstReport(e)}))}),400,"interval"),i.source="mcu"!==f&&(null===(n=v.media)||void 0===n||null===(n=n.video)||void 0===n?void 0:n.source),i.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},i.lastVideoReceiveInfo=Object.assign({},dr),i.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},i.lastAudioReceiveInfo=Object.assign({},ur),i.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},i}return f(t,$t),u(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},ur,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.packetsReceivedForLost=n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?t.lastAudioReceiveInfo.packetsReceived||0: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({},ur,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=ar(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.packetsReceivedForLost=n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},dr,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.packetsReceivedForLost=r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?t.lastVideoReceiveInfo.packetsReceived||0: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(ne(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=ne(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=ne(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=ne(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=ne(e.timestamp,i);if(e.bytesReceived-u>=0){var v=ne(e.packetsLost,a),m=ne(e.packetsReceivedForLost,d),h=0;try{h=Math.round(v/m*255)}catch(e){h=0}isNaN(h)&&(h=0);var y=ne(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:ne(e.framesDropped,c),attr_fir_count:ne(e.firCount,r),attr_freeze_count:ne(e.freezeCount,o),attr_pli_count:ne(e.pliCount,n),attr_retx_bytes:ne(e.retransmittedBytesReceived,l),attr_retx_packets:ne(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*ne(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(h,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(t){var r=this.firstReportFlag,n=r.audioFirstFrame,i=r.audioFirstPacket,o=r.videoFirstPacket,a=t.audioMetrics,s=t.videoMetrics;if(a&&s){if((n||-1===(null==a?void 0:a.decodingNormal))&&i&&o)return void(this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a){if((n||-1===(null==a?void 0:a.decodingNormal))&&i)return void(this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(s&&o)return void(this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null));null!=a&&a.packetsReceived&&!i&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==a?void 0:a.decodingNormal)>0&&!n&&(this.emit("audio-first-frame"),this.firstReportFlag.audioFirstPacket=!0),null!=s&&s.packetsReceived&&!o&&(this.emit("video-first-packet"),this.firstReportFlag.videoFirstPacket=!0)}},{key:"getStats",value:function(){var t,r=this,n=this.tranceiver,i=this.tranceivers,o=this.pc;if(!(o&&(null!=i&&i.length||null!=n&&n.receiver.track)))return Promise.resolve({});if(null==o||!o.getStats)throw new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"getStats is not supported");if(i&&i.length){var a=i.map((function(e){return e.receiver.track})).filter((function(e){return!!e}));return Promise.all(a.map((function(e){return o.getStats(e)}))).then((function(e){return{audioMetrics:r.extractMultipleAudioMetrics(e)}}))}return null!=n&&null!==(t=n.receiver)&&void 0!==t&&t.track?o.getStats(n.receiver.track).then((function(e){return{videoMetrics:r.source?r.extractVideoMetrics(e):void 0,audioMetrics:r.source?void 0:r.extractAudioMetrics(e)}})):void 0}},{key:"stop",value:function(){var r,n,i;(r="stop",n=this,"function"==typeof(i=W(l(t.prototype),r,n))?function(e){return i.apply(n,e)}:i)([]),this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}(),pr=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},fr=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,z(i.parameters.resolution)),n.sort(pr),n},vr=function(t,r){var n,i=t.media,o=i.audio,a=i.video;if(r===_.QuotaLimit)return n=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if(o)n=new e.DingRTCError(e.ErrorCode.SubscribeAudioStreamFailed,r);else if(a){var s=a.source;s===exports.VideoSourceInfo.CAMERA?n=new e.DingRTCError(e.ErrorCode.SubscribeVideoStreamFailed,r):s===exports.VideoSourceInfo.SCREENCAST&&(n=new e.DingRTCError(e.ErrorCode.SubscribeScreenShareFailed,r))}return n},mr=function(t,r){var n,i=t.trackMediaType;if(r===_.QuotaLimit)return n=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if("audio"===i)n=new e.DingRTCError(e.ErrorCode.PublishAudioStreamFailed,r);else{var o=t.source;o===exports.VideoSourceInfo.CAMERA?n=new e.DingRTCError(e.ErrorCode.PublishVideoStreamFailed,r):o===exports.VideoSourceInfo.SCREENCAST&&(n=new e.DingRTCError(e.ErrorCode.PublishScreenShareFailed,r))}return n},hr=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?De.audioSFU?n?n.replaceStream(e):i=new mt(null,r,e):n?n.replaceTrack(a[0]):i=new mt(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new ht(o[0],r)),i};function yr(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 gr(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)?gr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 gr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function br(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 Sr(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?br(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):br(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function kr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(kr=function(){return!!e})()}var Pr=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,kr()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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,"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 s=e.connection,c=e.stream,u=e.uid,p=e.resolutionInfo;return r.connection=s,r.resolutionInfo=p,r.signaling=s.signaling,r.stream=c,r.uid=u,r.reporter=s.reporter,r.connection.once("ended",(function(){r.clear()})),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=A.Processing,r.handleStreamAdd=r.handleStreamAdd.bind(r),r.connection.on("track",r.handleStreamAdd),r}return f(t,e.EventEmitter),u(t,[{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(De.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===A.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:"clear",value:function(){this.state!==A.End&&(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.state=A.End,this.connection.reset(),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 lr(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 lr(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=te(r,o),s=ne(r.bytesReceived,o.bytesReceived);this.audioStatsMap.set(t,{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})}else if(n){var c,u=(null===(c=this.metricsMap.get(t))||void 0===c?void 0:c.videoMetrics)||{},d=te(n,u),l=ne(n.bytesReceived,u.bytesReceived),p={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*l/d,decodeFrameRate:Math.round(ne(null==n?void 0:n.framesDecoded,u.framesDecoded)/d),receiveFrameRate:Math.round(ne(null==n?void 0:n.framesReceived,u.framesReceived)/d),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp};this.videoStatsMap.set(t,p)}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(Sr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(Sr({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(Sr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(),Er=function(e){var t,r={audio:[],video:[]},n=yr(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream;if(!i.error){var a=wr(o,i.resolutionInfo),s=a.audio,c=a.video;if(s){var u=Sr(Sr({},s),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:Lr()}]});De.audioSFU&&(u.ssrcGroup=[,,,,,,].fill(0).map((function(){return{ssrc:Lr()}}))),r.audio.push(u)}else if(c){var d,l;r.video.push(Sr(Sr({},c),{},{trackId:null===(d=o.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.trackId,ssrcGroup:null===(l=o.media)||void 0===l||null===(l=l.video)||void 0===l?void 0:l.ssrcGroup,subSsrcGroup:{ssrc:Lr(),rtxSsrc:Lr()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},wr=function(e,t){var r=e.id,n=e.media,i=n.video,o={};if(n.audio)o.audio={from:r};else if(i){var a;o.video={from:r,format:null===(a=n.video)||void 0===a?void 0:a.format,parameters:t}}return o},Tr=function(){var e=i(x.mark((function e(t,r){var n,o,a,s,c;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,o=[],a={},t.forEach((function(e,t){var n=e.stream,i=e.error,s=e.uid,c=e.resolutionInfo;if(o[t]={stream:n,error:i,uid:s,resolutionInfo:c},!i){var u=new Pr(Sr(Sr({},r),{},{uid:s,resolutionInfo:c,stream:n}));a[n.id]=u}})),c=new Promise((function(e,r){s=function(){var s=i(x.mark((function s(){var c;return x.wrap((function(s){for(;;)switch(s.prev=s.next){case 0:return c=Er(t),s.next=3,Br(n,c,a);case 3:n.signaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:De.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:c}).then(function(){var r=i(x.mark((function r(n){var i,s,c,u,d;return x.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(i=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=4;break}return o.forEach((function(e){e.error=e.error||vr(e.stream,s)})),r.abrupt("return",e(o));case 4:c=yr(i),r.prev=5,d=x.mark((function e(){var r,n,i,s,c,d;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=(r=u.value).id,i=r.msg,c=a[(s=r.origin).id],d=t.findIndex((function(e){return e.stream.id===s.id})),"ok"===i&&c?(c.id=n,o[d].id=n,o[d].subscription=c):"ok"!==i&&(o[d].error=vr(c.stream,i));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(o);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 s.stop()}}),s)})));return function(){return s.apply(this,arguments)}}()})),n.addTask(s),e.abrupt("return",c);case 7:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Or=function(){var e=i(x.mark((function e(t,r){var n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=r.connection,a=new Promise((function(e,r){n=function(){var n=i(x.mark((function n(){var i,a;return x.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return i=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,qr(o,t);case 4:o.signaling.batchUnSubscribe({connectionId:o.id,audio:i,video:a}).then((function(){t.forEach((function(e){e.state=A.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",a);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function Ir(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 Rr(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ir(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ir(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ar(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 Cr(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)?Cr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 Cr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}var _r={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},Dr=0,Mr=0,xr=0,jr=new Set,Lr=function(){if(0==Dr||0==Mr)return 0;var e=Math.min(Mr+1,1e4);do{var t=Dr+(Mr&xr++);if(0!=t&&!jr.has(t))return t}while(--e>0);return 0},Nr=function(t,r){var n,i;if((null===(n=t.rids)||void 0===n?void 0:n.length)>1)return e.Environment.isFirefox()&&(r=Fr(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},Vr=function(){var r=i(x.mark((function r(n,i){var o,a,s,c,u,d,l,p,f,v;return x.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return o=n.pc,a=n.idToTransceiverMap,s=n.remoteSDP,c=new MediaStream(i.map((function(e){return e.getMediaStreamTrack()}))),u=i.map((function(e){var t={direction:"sendonly"};if(e instanceof Ze){var r=Ye(e).filter((function(e){return e.active}));t.sendEncodings=r.map((function(t){return{rid:t.rid||void 0,maxBitrate:1e3*t.maxBitrate,maxFramerate:t.maxFramerate,active:!De.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST}}))}var i=n.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Ze&&i.sender.setParameters){var o=e.optimizationMode,s=i.sender.getParameters();s.degradationPreference=_r[o]||"balanced",i.sender.setParameters(s)}return a.set(e.getTrackId(),i),i})),r.next=5,o.createOffer();case 5:return l=t.parse((d=r.sent).sdp),r.next=9,o.setLocalDescription(d);case 9:n.localSDP=l,s.groups[0].mids=n.localSDP.groups[0].mids,p=Ar(u),r.prev=12,v=x.mark((function t(){var r,n,i,o;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:r=f.value,n=s.media.find((function(e){return e.type===r.sender.track.kind})),e.Environment.isFirefox()&&"video"===n.type&&(delete n.rids,delete n.simulcast),i=Rr(Rr({},n),{},{ext:z(n.ext),mid:r.mid}),o=l.media.find((function(e){return e.mid==r.mid})),Nr(o,i),s.media.push(i);case 7:case"end":return t.stop()}}),t)})),p.s();case 15:if((f=p.n()).done){r.next=19;break}return r.delegateYield(v(),"t0",17);case 17:r.next=15;break;case 19:r.next=24;break;case 21:r.prev=21,r.t1=r.catch(12),p.e(r.t1);case 24:return r.prev=24,p.f(),r.finish(24);case 27:return r.next=29,o.setRemoteDescription({type:"answer",sdp:t.write(s)});case 29:return n.remoteSDP=s,r.abrupt("return",{localSDP:n.localSDP,stream:c});case 31:case"end":return r.stop()}}),r,null,[[12,21,24,27]])})));return function(e,t){return r.apply(this,arguments)}}(),Gr=function(){var e=i(x.mark((function e(r,n){var i,o,a,s;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.pc,o=r.remoteSDP,n.map((function(e){return e.transceiver})).forEach((function(e){if(e){i.removeTrack(e.sender);var t=o.media.find((function(t){return t.mid==(null==e?void 0:e.mid)}));e.direction="inactive",t.direction="inactive"}})),e.next=5,i.createOffer();case 5:return s=t.parse((a=e.sent).sdp),e.next=9,i.setLocalDescription(a);case 9:return r.localSDP=s,o.groups[0].mids=s.groups[0].mids,r.remoteSDP=o,e.next=14,i.setRemoteDescription({type:"answer",sdp:t.write(o)});case 14:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Ur=function(t,r,n){var i=t.ssrc,o=t.rtxSsrc;!function(e){e.ssrc&&jr.add(e.ssrc),e.rtxSsrc&&jr.add(e.rtxSsrc)}(t),r.ssrcGroups=[],o&&r.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(i," ").concat(o)}),r.ssrcs=[],[i,o].filter((function(e){return void 0!==e})).forEach((function(t){r.ssrcs.push({attribute:"msid",value:"".concat(n," v").concat(i),id:t},{attribute:"cname",value:e.createUuid(),id:t})}))},Fr=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},Br=function(){var e=i(x.mark((function e(r,n,i){var o,a,s,c,u,d,l,p,f,v,m,h,y,g,b,S,k,P,E,w,T,O,I,R,A,C,_;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s=r.pc,c=r.idToTransceiverMap,d=r.idToTransceiversMap,l=(u=r.remoteSDP).media.find((function(e){return"video"===e.type})),p=u.media.find((function(e){return"audio"===e.type})),f=null===(o=l.ssrcs)||void 0===o?void 0:o.find((function(e){return"msid"===e.attribute})).value.split(" ")[0],null!==(a=n.audio)&&void 0!==a&&a[0])if(m=null===(v=n.audio)||void 0===v?void 0:v[0],h=m.from,De.audioSFU){if(d.get(h)){y=Ar(d.get(h));try{for(y.s();!(g=y.n()).done;)g.value.direction="recvonly"}catch(e){y.e(e)}finally{y.f()}b=u.media.filter((function(e){return"audio"===e.type})),S=Ar(b);try{for(S.s();!(k=S.n()).done;)k.value.direction="sendonly"}catch(e){S.e(e)}finally{S.f()}}else r.mcuAudioTranceivers=[,,,,,,].fill(0).map((function(e){return r.pc.addTransceiver("audio",{direction:"recvonly"})})),d.set(h,r.mcuAudioTranceivers);i[h].addTransceivers(d.get(h))}else c.get(h)||c.set(h,r.mcuAudioTranceiver),c.get(h).direction="recvonly",p.direction="sendonly",i[h].addTransceiver(c.get(h));P=Ar(n.video),e.prev=6,w=x.mark((function e(){var r,n,o;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=c.get(r=E.value.from)){e.next=7;break}c.set(r,s.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===n.direction){e.next=18;break}return n.direction="inactive",e.next=11,s.createOffer();case 11:return o=e.sent,e.next=14,s.setLocalDescription(o);case 14:return u.media.find((function(e){return e.mid==n.mid})).direction="inactive",e.next=18,s.setRemoteDescription({type:"answer",sdp:t.write(u)});case 18:c.get(r).direction="recvonly";case 19:i[r].addTransceiver(c.get(r));case 20:case"end":return e.stop()}}),e)})),P.s();case 9:if((E=P.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),P.e(e.t1);case 18:return e.prev=18,P.f(),e.finish(18);case 21:return e.next=23,s.createOffer();case 23:return O=t.parse((T=e.sent).sdp),u.groups[0].mids=O.groups[0].mids,e.next=28,s.setLocalDescription(T);case 28:r.localSDP=O,De.audioSFU&&n.audio[0]&&(R=(I=n.audio[0]).ssrcGroup,d.get(I.from).forEach((function(e,t){var r,n=null===(r=R[t])||void 0===r?void 0:r.ssrc,i=u.media.find((function(t){return t.mid==e.mid&&"audio"===t.type}));i||(i=Rr(Rr({},p),{},{mid:e.mid}),u.media.push(i)),i.ssrcs=Hr(n,f),i.direction="sendonly"}))),A=Ar(n.video),e.prev=31,_=x.mark((function e(){var t,r,n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:n=(t=C.value).subSsrcGroup,o=c.get(r=t.from),(a=u.media.find((function(e){return e.mid==o.mid&&"video"===e.type})))||((a=Rr({},l)).mid=o.mid,u.media.push(a)),a.direction="sendonly",i[r].ssrc=null==n?void 0:n.ssrc,Ur(n,a,f);case 8:case"end":return e.stop()}}),e)})),A.s();case 34:if((C=A.n()).done){e.next=38;break}return e.delegateYield(_(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),A.e(e.t3);case 43:return e.prev=43,A.f(),e.finish(43);case 46:return r.remoteSDP=u,e.next=49,s.setRemoteDescription({type:"answer",sdp:t.write(u)});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)}}(),qr=function(){var e=i(x.mark((function e(r,n){var i,o,a,s,c,u,d,l,p,f,v,m;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=r.pc,o=r.remoteSDP,a=[],s=Ar(n);try{for(s.s();!(c=s.n()).done;)l=(u=c.value).transceivers,(d=u.transceiver)?a.push(d):l&&a.push.apply(a,z(l))}catch(e){s.e(e)}finally{s.f()}return a.forEach((function(e){e.direction="inactive"})),e.next=7,i.createOffer();case 7:return p=e.sent,e.next=10,i.setLocalDescription(p);case 10:r.localSDP=t.parse(p.sdp),f=x.mark((function e(){var t;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=m[v],o.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),v=0,m=a;case 13:if(m.length<=v){e.next=18;break}return e.delegateYield(f(),"t0",15);case 15:v++,e.next=13;break;case 18:return r.remoteSDP=o,e.next=21,i.setRemoteDescription({type:"answer",sdp:t.write(o)});case 21:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Hr=function(t,r){return[{attribute:"msid",value:"".concat(r," v").concat(t),id:t},{attribute:"cname",value:e.createUuid(),id:t}]},Yr=function(r,n,i){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"all",a=n.direction,s=n.remoteSDP,c=t.parse(r);"relay"===o&&c.media.forEach((function(t){t.candidates=t.candidates.filter((function(t){return e.isPrivateIP(t.ip)}))})),i&&(c=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]=Rr(Rr({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=Rr(Rr({},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}(s,c));var u=c.media.find((function(e){return"video"===e.type}));if("uplink"===a&&e.Environment.isFirefox()&&De.simulcast&&(u.ext=u.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!u.ssrcs&&"downlink"===a){var d=Lr();u.ssrcs=Hr(d,c.msidSemantic.token)}return n.remoteSDP=c,c},Jr=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=Ar(n);try{for(u.s();!(r=u.n()).done;){var d=r.value,l=d.payload,p=d.config.split(";");c[l]={};var f,v=Ar(p);try{for(v.s();!(f=v.n()).done;){var m=Ie(f.value.split("="),2);c[l][m[0]]=m[1]}}catch(e){v.e(e)}finally{v.f()}}}catch(e){u.e(e)}finally{u.f()}for(var h in c){var y=c[h];(t(y)||s.includes(+y.apt))&&s.push(parseInt(h))}if(s.length){for(var g=n.length-1;g>=0;g--){s.includes(n[g].payload)&&n.splice(g,1)}for(var b=o.length-1;b>=0;b--)s.includes(o[b].payload)&&o.splice(b,1);for(var S=a.length-1;S>=0;S--)s.includes(a[S].payload)&&a.splice(S,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},Wr=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return Jr(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},Qr=function(e){var t=e.media.find((function(e){return"video"===e.type}));return Jr(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};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;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Kr(Object(r),!0).forEach((function(t){j(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 e.length>n?{done:!1,value:e[n++]}:{done:!0}},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);t>r;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=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Zr()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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 s=e.connection,c=e.uid,u=e.tracks,p=void 0===u?[]:u;return r.tracks=p,r.connection=s,r.signaling=s.signaling,r.uid=c,r.reporter=s.reporter,r.state=A.Idle,r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.handleTracEvent=r.handleTracEvent.bind(r),p.forEach((function(e){e.on(B,r.handleTracEvent)})),r.encodings=Ye(p[0]),r.state=A.Processing,r.connection.once("ended",(function(){r.clear()})),r}return f(t,e.EventEmitter),u(t,[{key:"stop",value:function(){var t=this;return this.state!==A.Processing?Promise.resolve():rn([this],{connection:this.connection}).catch((function(r){t.clear(),t.reporter.log.warn("negative ack for unpublish, ".concat(e.tryJsonStringify(r)))}))}},{key:"mute",value:function(){if(this.tracks.length&&this.state===A.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===A.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!==A.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(B,e.handleTracEvent)})),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset(),this.state=A.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===A.Processing){this.feedbackIndex=n;var o,a=0===i,s=this.transceiver,c=!1,u=!1,d=s.sender.getParameters(),l=e.map((function(e){return e.rid})),p=$r(d.encodings);try{for(p.s();!(o=p.n()).done;){var f,v=o.value,m=$r(e);try{var h=function(){var e=f.value,r=t.encodings.find((function(t){return t.rid===e.rid}));if(e.rid!==v.rid&&v.rid||v.active||a||(v.active=!0,v.scaleResolutionDownBy=r.scaleResolutionDownBy,c=!0),e.rid===v.rid&&!a){var n=Math.max(Math.min(e.bitrate,r.maxBitrate),r.minBitrate);n!==Math.round(v.maxBitrate/1e3)&&(v.maxBitrate=1e3*n,u=!0)}};for(m.s();!(f=m.n()).done;)h()}catch(e){m.e(e)}finally{m.f()}!v.active||l.includes(v.rid)&&!a||(v.active=!1,c=!0)}}catch(e){p.e(e)}finally{p.f()}(c||u)&&s.sender.setParameters(d)}}},{key:"updateOptionzationMode",value:function(){var e;if(this.tracks[0]instanceof Ze&&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=_r[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=A.Processing,this.feedbackIndex=-1,this.monitor=new or(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=te(r,o),s=ne(r.bytesSent,o.bytesSent);this.audioStatsMap.set(t,{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})}else if(n){var c,u,d=((null===(c=this.transceiver)||void 0===c||null===(c=c.sender)||void 0===c?void 0:c.getParameters())||{}).encodings,l=void 0===d?[]:d,p=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},f=te(n,p),v=ne(n.totalBytesSent,p.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:l.length,sendLayers:l.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*v/f};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;null===(t=r.monitor)||void 0===t||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(zr({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(zr({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(zr({sessionId:e.id},t))}))}}])}(),tn=function(){var e=i(x.mark((function e(t,r){var n,i,o,a,s,c=arguments;return x.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,Vr(r,t);case 4:return a=(o=e.sent).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 Ze){var c;i.video=i.video||[];var u=e.trackSettings,d=o.ssrcGroups,l=void 0===d?[]:d,p=Ye(e);p.length>1&&(l=p.map((function(){return{semantics:"FID",ssrcs:"".concat(Lr()," ").concat(Lr())}})));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={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),uplinkSsrcGroup:f,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==f||null===(c=f[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(p[p.length-1].maxBitrate),resolution:{width:u.width,height:u.height},framerate:u.frameRate},ssrcParameters:f.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].active,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(v)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),rn=function(){var e=i(x.mark((function e(t,r){var n,o;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=new Promise((function(e,o){n=function(){var n=i(x.mark((function n(){var i,a;return x.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return i=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,Gr(r.connection,t);case 4:r.connection.signaling.batchUnPublish({connectionId:r.connection.id,audio:i,video:a}).then((function(){t.forEach((function(e){e.clear(),e.state=A.End})),e(void 0)})).catch(o);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",o);case 3:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function nn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(nn=function(){return!!e})()}var on={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},an=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,nn()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},on)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return f(t,$t),u(t,[{key:"extractMetrics",value:function(t){var r=Object.assign({},on),n="";return t.forEach((function(t){var i;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===n)e.Environment.networkType=(null!==(i=t.networkType)&&void 0!==i?i:e.Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(t.type)&&"succeeded"===t.state)n=t.localCandidateId,e.Environment.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/",""))}})),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 t=this;if(!this.pc)return Promise.resolve({});if(!this.pc.getStats)throw new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"getStats is not supported");return this.pc.getStats(null).then((function(e){return t.extractMetrics(e)}))}}])}();function sn(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 cn(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)?cn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 cn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function un(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(un=function(){return!!e})()}var dn={uplink:"",downlink:""},ln=function(){function r(t){var n,i,a,s;o(this,r),i=this,a=l(a=r),n=d(i,un()?Reflect.construct(a,[],l(i).constructor):a.apply(i,s)),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pendingTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"state",{enumerable:!0,configurable:!0,writable:!0,value:C.New}),Object.defineProperty(n,"exchangeSdpTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"peerConnectionStats",{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,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"remoteSDP",{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,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(n,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioSfuSsrcs",{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,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){n.reporter.log.debug("ice gathering state: ".concat(e.target.iceGatheringState))}}),n.pc=null;var c=t.direction,u=t.sessionManager;return n.signaling=u.channel.signaling,n.sessionManager=u,n.reporter=u.reporter,n.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;e>r&&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()}}}(),n.direction=c,n.idToTransceiverMap=new Map,n.idToTransceiversMap=new Map,n.createPeerConnection(),n.id="".concat(n.direction,"_").concat(e.createUuid()),n.startSinglePC().then((function(){n.state=C.Idle,n.enquenTask.start()})),n}return f(r,e.EventEmitter),u(r,[{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.remoteSDP,r=e.sessionManager,n=e.mcuAudioTranceiver,i=e.pc,o=e.idToTransceiverMap,a=e.idToTransceiversMap,s=e.direction,c=e.localSDP.media.slice(2),u=z(r.sessions.values());if("downlink"===s){var d=t.media.slice(2),l=u.filter((function(e){return e instanceof Pr})),p=l.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)}));p&&!De.audioSFU&&(o.set(p.id,n),p.addTransceiver(n));var f=[];c.forEach((function(e){var t={direction:e.direction},r=d.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=l.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),a=i.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(o.set(n.stream.id,a),n.addTransceiver(a)):"audio"===e.type&&f.push(a))})),f.length&&p&&(e.mcuAudioTranceivers=f,a.set(p.id,f),p.addTransceivers(f))}else{var v=u.filter((function(e){return e instanceof en}));c.forEach((function(e){var t={direction:e.direction},r=v.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],a=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof Ze){var s=Ye(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:!De.simulcast||n.source===exports.VideoSourceInfo.SCREENCAST}}))}var c=i.addTransceiver(a,t);o.set(n.getTrackId(),c),r.addTransceiver(c)}else i.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("sessionId ".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;"audio"===t.kind?De.audioSFU?this.emit("track",t,e.streams[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==C.Ended&&(this.state=C.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.reporter.log.debug("sessionId ".concat(this.id,": ICE connection state changed to ").concat(e))}},{key:"handleClientReoffer",value:(n=i(x.mark((function t(){return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.state!==C.New){t.next=2;break}return t.abrupt("return",Promise.reject());case 2:return this.reporter.log.debug("sessionId ".concat(this.id,": start client reoffer process")),t.prev=3,t.next=6,this.stopSinglePC(!0);case 6:this.removeAllListeners(),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(3),this.reporter.log.debug("sessionId ".concat(this.id,": client reoffer close failed ").concat(e.tryJsonStringify(t.t0)));case 12:this.closePeerConnection();case 13:case"end":return t.stop()}}),t,this,[[3,9]])}))),function(){return n.apply(this,arguments)})},{key:"addTask",value:function(e){this.enquenTask.add(e)}},{key:"onConnectionStateChange",value:function(){var t=this,r=this.pc.connectionState;this.reporter.trace.connectionsEvent(this.id,r),"failed"===r||"closed"===r?(this.clientFailoverTimer&&e.removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=e.addTimer((function(){t.state!==C.New&&t.emit("reoffer")}),1e4)):"connected"===r&&(this.clientFailoverTimer&&(e.removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=null),this.createPeerConnectionTimer&&(e.removeTimer(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=sn(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.Environment.isFirefox()&&c.splice(4,2),"relay"===dn[this.direction]&&(dn[this.direction]="all",a.iceTransportPolicy="all"),a.iceServers=[{urls:c,username:r,credential:n}]}return dn[this.direction]=a.iceTransportPolicy,this.reporter.log.debug("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var t=this;this.pc?this.reporter.log.warn("sessionId ".concat(this.id,": A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=e.addTimer((function(){var e;"connected"===(null===(e=t.pc)||void 0===e?void 0:e.connectionState)||t.exchangeSdpTask||t.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 an(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&&e.removeTimer(this.createPeerConnectionTimer),this.clientFailoverTimer&&e.removeTimer(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 t=this;return new Promise((function(r,n){t.pendingTask={resolve:r,reject:n},t.exchangeSDP(),e.addTimer((function(){var e;t.pendingTask&&t.state===C.Processing&&(null===(e=t.pendingTask)||void 0===e||e.reject(),t.fireEndedEvent())}),15e3)}))}},{key:"exchangeSDP",value:function(){var r,n=this,o=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return new Promise((function(a,s){n.exchangeSdpTask={resolve:a,reject:s},n.pc.createOffer().then((function(e){var i,a,s;return r=e,o&&(r.sdp=t.write((i=n.localSDP,a=t.parse(r.sdp),s=a.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,a=e.type,c=s.findIndex((function(e){return e.mid==t&&e.type===a}));c>-1&&(s[c]=Rr(Rr({},s[c]),{},{ssrcGroups:n,ssrcs:o}))})),a))),n.pc.setLocalDescription(r).catch((function(e){throw n.reporter.log.error("sessionId ".concat(n.id,": Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){n.reporter.log.debug("sessionId ".concat(n.id,": set local sdp success"));var a=function(r,n){var i=n.direction,o=["uplink"===i,"downlink"===i&&"macOS"===e.Environment.system&&e.Environment.isChrome()],a=t.parse(r);if(o.some((function(e){return e}))&&(a=Wr(a,"64")),e.Environment.isFirefox()&&(a=Qr(a)),"uplink"===i&&e.Environment.isFirefox()&&De.simulcast){var s=a.media.find((function(e){return"video"===e.type}));Fr(s)}return n.localSDP=a,a}(r.sdp,n);r.sdp=t.write(a),n.offerSDP=a,r.sdp=t.write(a);var s,c={direction:"downlink"!==n.direction?"in":"out",sdpOffer:r.sdp,connectionId:n.id,isFailover:o,optionsJsonStr:JSON.stringify({supportCVO:1})};if(o){var u=t.parse(r.sdp);u.media=u.media.slice(0,2),u.groups=[{mids:"0 1",type:"BUNDLE"}],c.sdpOffer=t.write(u)}return function(t){var r=t.fn,n=t.times,o=t.interval,a=void 0===o?0:o,s=t.key,c=ie.get(s),u=function(){c&&(e.removeTimer(c),ie.delete(s),c=null)};u();var d=function(){var t=i(x.mark((function t(){return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,n--,t.next=4,r();case 4:u(),t.next=14;break;case 7:if(t.prev=7,t.t0=t.catch(0),n>0){t.next=12;break}throw u(),t.t0;case 12:c=e.addTimer((function(){d()}),a),ie.set(s,c);case 14:case"end":return t.stop()}}),t,null,[[0,7]])})));return function(){return t.apply(this,arguments)}}();return d()}({key:"createPeerConnection_".concat(n.direction),fn:(s=i(x.mark((function r(){var i;return x.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if("connected"===(null===(i=n.sessionManager)||void 0===i||null===(i=i.channel)||void 0===i||null===(i=i.client)||void 0===i?void 0:i.connectionState)){r.next=2;break}return r.abrupt("return");case 2:if(c.isFailover||!n.prevId){r.next=7;break}return r.next=5,n.stopSinglePC(!0);case 5:n.id="".concat(n.direction,"_").concat(e.createUuid()),c.connectionId=n.id;case 7:return n.prevId=n.id,r.abrupt("return",n.signaling.createPeerConnection(c).then((function(r){var i=Yr(r.sdpAnswer,n,o,dn[n.direction]);n.pc.setRemoteDescription({sdp:t.write(i),type:"answer"}).then((function(){var e;n.reporter.log.debug("sessionId ".concat(n.id,": receive answer success")),null===(e=n.exchangeSdpTask)||void 0===e||e.resolve(),n.exchangeSdpTask=void 0})).catch((function(t){var r,i;n.reporter.log.error("sessionId ".concat(n.id,": Set remote description failed: ").concat(t)),null===(r=n.exchangeSdpTask)||void 0===r||r.reject(t),n.exchangeSdpTask=void 0,null===(i=n.pendingTask)||void 0===i||i.reject(new e.DingRTCError(e.ErrorCode.IceConnectionAnswerFail)),n.fireEndedEvent()}))})));case 9:case"end":return r.stop()}}),r)}))),function(){return s.apply(this,arguments)}),times:3,interval:2e3})})).catch((function(t){var r,i;n.reporter.log.error("sessionId ".concat(n.id,": Failed to create offer or set SDP. Message: ").concat(t.message)),null===(r=n.pendingTask)||void 0===r||r.reject(new e.DingRTCError(e.ErrorCode.IceConnectionSetLocalDescFail)),n.fireEndedEvent(),null===(i=n.exchangeSdpTask)||void 0===i||i.reject(t),n.exchangeSdpTask=void 0}))}))}},{key:"reoffer",value:function(){var e=this;return this.state===C.New?Promise.reject():(this.reporter.log.debug("sessionId ".concat(this.id,": start reoffer process")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=C.New,this.startSinglePC(!0).then((function(){e.state=C.Idle,e.enquenTask.start()})))}}]);var 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;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?pn(Object(r),!0).forEach((function(t){j(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(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 mn(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)?mn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 mn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function hn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(hn=function(){return!!e})()}var yn=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,hn()?Reflect.construct(a,[],l(i).constructor):a.apply(i,s)),Object.defineProperty(n,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),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=e,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 f(t,e.EventEmitter),u(t,[{key:"getOrCreatePeerConnection",value:function(e){var t=this;return"uplink"===e?(this.uplink||(this.uplink=new ln({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 ln({direction:e,sessionManager:this}),this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){t.downlink=null}))),this.downlink)}},{key:"handleRepulish",value:(h=i(x.mark((function t(){var r,n,i,o,a,s,c;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n=z(this.client.localTracks),i=vn(this.sessions.values());try{for(i.s();!(o=i.n()).done;)(a=o.value)instanceof en&&a.state===A.Processing&&(a.clear(),this.sessions.delete(a.id))}catch(e){i.e(e)}finally{i.f()}return this.client.emit("media-reconnect-start",this.client.userId),s=null===(r=this.uplink)||void 0===r?void 0:r.id,t.prev=5,this.reporter.trace.connectionsEvent(s,"clientReofferStart"),t.next=9,null===(c=this.uplink)||void 0===c?void 0:c.handleClientReoffer();case 9:if(this.uplink=null,this.reporter.log.info("".concat(this.client.userId," republish ").concat(n.map((function(e){return e.trackMediaType})).join()," start")),!n.length){t.next=14;break}return t.next=14,this.batchPublish(n);case 14:this.reporter.trace.connectionsEvent(s,"clientReofferSuccess"),this.client.emit("media-reconnect-end",this.client.userId),t.next=24;break;case 18:t.prev=18,t.t0=t.catch(5),this.reporter.log.debug("".concat(this.client.userId," republish failed for ").concat(e.tryJsonStringify(t.t0))),this.reporter.trace.connectionsEvent(s,"clientReofferFailed"),this.client.emit("media-reconnect-end",this.client.userId),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 24:case"end":return t.stop()}}),t,this,[[5,18]])}))),function(){return h.apply(this,arguments)})},{key:"handleResubscribe",value:(m=i(x.mark((function t(){var r,n,i,o,a,s,c,u,d,l,p,f,v,m,h,y=arguments;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:n=y.length>0&&void 0!==y[0]&&y[0],i=[],o=vn(this.sessions.values());try{for(o.s();!(a=o.n()).done;)(s=a.value)instanceof Pr&&s.state===A.Processing&&(i.push({stream:s.stream,uid:s.uid}),s.clear(),this.sessions.delete(s.id))}catch(e){o.e(e)}finally{o.f()}return c=n?"server":"client",u=i.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",u),this.reporter.log.info("resubscribe ".concat(u," start")),d=null===(r=this.downlink)||void 0===r?void 0:r.id,t.prev=9,this.reporter.trace.connectionsEvent(d,"".concat(c,"ReofferStart")),t.next=13,null===(l=this.downlink)||void 0===l?void 0:l.handleClientReoffer();case 13:if(this.downlink=null,!i.length){t.next=20;break}return t.next=17,this.batchSubscribe(i);case 17:p=vn(t.sent);try{for(p.s();!(f=p.n()).done;)h=(v=f.value).error,(m=v.subscription)&&!h&&this.handleSubscribeReoffer(m)}catch(e){p.e(e)}finally{p.f()}case 20:this.reporter.trace.connectionsEvent(d,"".concat(c,"ReofferSuccess")),this.client.emit("media-reconnect-end",u),t.next=30;break;case 24:t.prev=24,t.t0=t.catch(9),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t.t0))),this.reporter.trace.connectionsEvent(d,"".concat(c,"ReofferFailed")),this.client.emit("media-reconnect-end",u),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 30:case"end":return t.stop()}}),t,this,[[9,24]])}))),function(){return m.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)===exports.VideoSourceInfo.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(De.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(t){var r=this;this.reporter.log.debug("serverFailover ".concat(JSON.stringify(t)));var n,i=t.actions,o=vn(void 0===i?[]:i);try{var a=function(){var t,i,o=n.value,a=o.connectionId;if("reoffer"!==o.actionName)return 1;if(a===(null===(t=r.uplink)||void 0===t?void 0:t.id)){var s=r.uplink,c=r.client,u=c.userId,d=c.localTracks;r.client.emit("media-reconnect-start",u),r.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then((function(){r.reporter.log.info("".concat(u," republish ").concat(d.map((function(e){return e.trackMediaType})).join()," success")),r.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),r.client.emit("media-reconnect-end",u)})).catch((function(t){r.reporter.log.debug("".concat(r.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t))),r.reporter.trace.connectionsEvent(a,"serverReofferFailed"),r.channel.signaling.emit("connection-state-change","disconnected",r.client.connectionState,"network_error")}))}else a===(null===(i=r.downlink)||void 0===i?void 0:i.id)&&r.handleResubscribe(!0)};for(o.s();!(n=o.n()).done;)a()}catch(e){o.e(e)}finally{o.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?T.BAD:e>30||t>450?T.POOR:e>20||t>300?T.NORMAL:e>10||t>200?T.GOOD:0>e&&0>t?T.UNKNOWN:T.GREAT}},{key:"checkChannelNetworkQuality",value:(v=i(x.mark((function e(){var t,r=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=z(this.sessions.values())).length){e.next=4;break}return this.emit("network-quality",T.UNKNOWN,T.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",T.DISCONNECTED,T.DISCONNECTED),e.abrupt("return");case 8:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then((function(e){var t=Ie(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 m 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 h=a[m],y=h.camera,g=h.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,E,w=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(0>w&&(w=c),k.totalUplinkPacketsSentForLost=(null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsSentForLost)||0,0!==w){var T;k.totalUplinkPacketsSentForLost=s;var O=s-((null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0);0>O&&(O=s),b=w/O}}if(d){var I,R,A,C=u-((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0);0>C&&(C=u),k.totalDownlinkPacketsRecvForLost=(null===(R=r.lastChannelNetworkQuality)||void 0===R?void 0:R.totalDownlinkPacketsRecvForLost)||0,C&&(u!==((null===(A=r.lastChannelNetworkQuality)||void 0===A?void 0:A.totalDownlinkPacketsLost)||0)&&(k.totalDownlinkPacketsRecvForLost=d),S=C/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 v.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,o=e.labels,a=r.map((function(t){return{publication:new en(zr(zr({},e),{},{tracks:[t]})),track:t}})),s=new Promise((function(e,s){t=function(){var t=i(x.mark((function t(){return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,tn(r,n,o);case 2:return t.abrupt("return",n.signaling.batchPublish({connectionId:n.id,media:t.sent,simulcast:De.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"}).then(function(){var t=i(x.mark((function t(r){var n,i,o,s,c;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=r.detailStatus,"ok"===(i=r.globalStatus)){t.next=4;break}return a.forEach((function(e){e.error=mr(e.track,i)})),t.abrupt("return",e(a));case 4:o=$r(n),t.prev=5,c=x.mark((function e(){var t,r,n,i,o,c;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=(t=s.value).id,n=t.origin,i=t.msg,o=a.findIndex((function(e){return e.track.getTrackId()===n.id})),c=(a[o]||{}).publication,"ok"===i&&c?c.initInner(r):"ok"!==i&&(a[o].error=mr(a[o].track,i));case 4:case"end":return e.stop()}}),e)})),o.s();case 8:if((s=o.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),o.e(t.t1);case 17:return t.prev=17,o.f(),t.finish(17);case 20:e(a);case 21:case"end":return t.stop()}}),t,null,[[5,14,17,20]])})));return function(e){return t.apply(this,arguments)}}()).catch((function(e){s(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),s}({uid:this.client.userId,tracks:e,connection:this.getOrCreatePeerConnection("uplink"),labels:t}).then((function(e){var t,i=vn(e);try{var o=function(){var e=t.value,i=e.publication,o=e.track;e.error?r.reporter.trace.publish(!1,o,"",Date.now()-n):(r.addSession(o.getTrackId(),i),r.reporter.trace.publish(!0,o,i.id,Date.now()-n),r.reporter.trace.publish(!1,o,i.id,Date.now()-n),i.on("ended",(function(){r.removeSession(i.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?rn(e,{connection:this.getOrCreatePeerConnection("uplink")}).then((function(){var r,n=vn(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,o=function(e){return Tr(e,{connection:t.getOrCreatePeerConnection("downlink")}).then(function(){var r=i(x.mark((function r(i){var a,s,c,u;return x.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:for(a=new Map,s=[],c=0;i.length>c;c++)"RoomBusy"===(null===(u=i[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,oe(1);case 7:if("connected"!==t.client.connectionState){r.next=12;break}return r.next=10,o(s);case 10:r.sent.forEach((function(e,t){var r=a.get(t);i[r]=e}));case 12:return r.abrupt("return",i);case 13:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}())};return o(e).then((function(e){var n,i=vn(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:(p=i(x.mark((function e(t){var r,n,i,o=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,a=e.stream,s=e.session;o?r[t]={error:o}:(i[null==a?void 0:a.id]=t,n.push(s))})),e.abrupt("return",Or(n,{connection:this.getOrCreatePeerConnection("downlink")}).then((function(){for(var e=0,t=n;t.length>e;e++)o.removeSession(t[e].id)})));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"clear",value:function(){var t,r,n=this;this.sessions.forEach((function(e){n.removeSession(e.id)})),null===(t=this.uplink)||void 0===t||t.closePeerConnection(),this.uplink=null,null===(r=this.downlink)||void 0===r||r.closePeerConnection(),this.downlink=null,this.streamIdToSessionId.clear(),this.networkQualityInterval&&(e.removeTimer(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 t=this;this.networkQualityInterval=e.addTimer((function(){navigator&&void 0!==navigator.onLine&&!navigator.onLine?t.emit("network-quality",T.DISCONNECTED,T.DISCONNECTED):"connected"!==t.client.connectionState?t.emit("network-quality",T.BAD,T.BAD):"connected"===t.client.connectionState?t.checkChannelNetworkQuality():t.emit("network-quality",T.UNKNOWN,T.UNKNOWN)}),2e3,"interval")}},{key:"getLocalAudioStats",value:(c=i(x.mark((function e(){var t,r,n,i=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=z(this.sessions.values()).filter((function(e){var t,r;return e instanceof en&&"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 c.apply(this,arguments)})},{key:"getLocalVideoStats",value:(s=i(x.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f,v=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=v.length>0&&void 0!==v[0]?v[0]:"network",i=z(this.sessions.values()).filter((function(e){var t;return e instanceof en&&"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:z(new Set(o(a))),downlinkProfile:z(new Set(o(s)))},u=vn(i),e.prev=9,u.s();case 11:if((d=u.n()).done){e.next=21;break}if(p=(l=d.value).videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=l.tracks[0].source===exports.VideoSourceInfo.SCREENCAST,c[f?"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 s.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(a=i(x.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=p.length>0&&void 0!==p[0]?p[0]:"network",r=z(this.sessions.values()).filter((function(e){var t;return e instanceof Pr&&"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=vn(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(c=(s=o.value).uid,u=s.stream,d=s.videoStatsMap.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:l=(null===(a=u.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[c]=fn(fn({},n[c]||{}),{},j({},l,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 a.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(n=i(x.mark((function e(){var t,r,n,i=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>0&&void 0!==i[0]?i[0]:"network",n=z(this.sessions.values()).filter((function(e){var t;return e instanceof Pr&&"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 n.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=i(x.mark((function e(t){var r,n,i,o,a;return x.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=z(this.sessions.values()).filter((function(e){return e instanceof en&&e.state===A.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA})),i=vn(n),e.prev=6,a=x.mark((function e(){var t,n;return x.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 r.apply(this,arguments)})}]);var r,n,a,s,c,p,v,m,h}();function gn(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 bn(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)?bn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 bn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function Sn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Sn=function(){return!!e})()}var kn={name:"name"},Pn=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Sn()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),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=e,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 f(t,e.EventEmitter),u(t,[{key:"joinedIds",get:function(){var e=this.channel.userManager.currentPid,t=new Set;return this.groups.forEach((function(r){var n=r.id;r.participants.some((function(t){return t.pid===e}))&&t.add(n)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.properties,i=e.participants;return{id:e.id,name:(null==n||null===(t=n.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:i.some((function(e){return e.pid===r.channel.userManager.currentPid})),users:i.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(t){var r=t.publishAudioToGroup,n=void 0===r||r,i=t.groupId,o=t.userData;if(this.joinedIds.has(i))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you were in group already");return this.channel.signaling.joinGroup({groupId:i,userData:o,autoJoinGroupAudio:!!n,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(t){var r=t.groupId,n=t.publishAudioToChannel,i=void 0===n||n;if(!this.joinedIds.has(r))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you are not in the group");return this.channel.signaling.leaveGroup({groupId:r,reasonCode:pt.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:i})}},{key:"dismiss",value:function(t){if(!this.groupIds.has(t))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"group not existed");return this.channel.signaling.dismissGroup({groupId:t})}},{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!==pt.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===pt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===pt.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!==pt.OptType.OPT_TYPE_ADD||u){if(s===pt.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(i),this.emit("group","remove",this.parseGroup(u));else if(s===pt.OptType.OPT_TYPE_UPDATE){var d=c.updateAction,l=c.participants;if(u&&(u.ver+1===o||r)){if(d===pt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map((function(e){return e.pid})),v=gn(l);try{for(v.s();!(p=v.n()).done;){var m=p.value;f.includes(m.pid)||(u.participants.push(m),this.emit("group","user-join",i,{userId:m.uid,userData:m.userData}))}}catch(e){v.e(e)}finally{v.f()}}else if(d===pt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var h=l.map((function(e){return e.pid})),y=z(u.participants);u.participants=u.participants.filter((function(e){return!h.includes(e.pid)})),y.forEach((function(e){h.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(d===pt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.channel.reporter.log.debug("group ".concat(i," audioStream lost"));else if(d===pt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.channel.reporter.log.debug("group ".concat(i," audioStream recover"));else if(d===pt.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(kn[e.key]),value:e.value})}));else if(d===pt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var g,b=c.properties.map((function(e){return e.key}));u.properties=null===(g=u.properties)||void 0===g?void 0:g.filter((function(e){return!b.includes(e.key)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(kn[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:pt.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)})),m=a.filter((function(e){return!l.includes(e.pid)})),h=u.filter((function(e){return!p.includes(e.pid)}));m.length&&t.handleGroupEvents({id:e,type:pt.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:pt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:m}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pt.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:pt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:h}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:pt.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:pt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:pt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:pt.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.channel.signaling.syncDataByIds({type:pt.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:pt.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=z(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:pt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:pt.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;r>this.listVer&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);n>(null==i?void 0:i.ver)&&(t.syncGroup(r),i.ver=n)}))}}])}();function En(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(En=function(){return!!e})()}var wn=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,En()?Reflect.construct(a,[],l(i).constructor):a.apply(i,s)),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}),n.userId=e.user,n.videoTrack=null,n.audioTrack=null,n.auxiliaryTrack=null,n.channel=r,n.joinedTime=Date.now(),n.update(e),n}return f(t,e.EventEmitter),u(t,[{key:"relatedStreams",get:function(){var e=this;return z(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)===exports.VideoSourceInfo.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)===exports.VideoSourceInfo.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)===exports.AudioSourceInfo.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)===exports.AudioSourceInfo.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)===exports.VideoSourceInfo.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)===exports.VideoSourceInfo.CAMERA}))}},{key:"updateNetworkOfUser",value:function(t){var r;if(this.properties.SdkType!==e.SdkType.Web&&t){var n=t.split("");n[D.UPLINK]=re(n[D.UPLINK]),n[D.DOWNLINK]=re(n[D.DOWNLINK]),t=n.join("")}t!==(null===(r=this.properties)||void 0===r?void 0:r[F])&&(this.properties[F]=t)}},{key:"update",value:function(e){var t=e.id,r=e.ver,n=JSON.parse(e.propertiesJsonStr||"{}");this.id=t,this.userName=n.__nick,this.version=r,this.properties=n,this.updateNetworkOfUser(n[F])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=hr(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 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 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 e.length>n?{done:!1,value:e[n++]}:{done:!0}},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);t>r;r++)n[r]=e[r];return n}function In(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(In=function(){return!!e})()}var Rn=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,In()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),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=e,r.reporter=e.reporter,r.handleEvent=r.handleEvent.bind(r),r}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){var t=this;return e.uniqBy(z(this.users.values()).sort((function(e,t){return e.joinedTime-t.joinedTime})),"userId").filter((function(e){return e.userId&&e.id!==t.currentPid}))}},{key:"init",value:function(e,t){var r,n=Tn(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new wn(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 wn(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(j({},F,e))})}}])}();function An(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 Cn(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)?Cn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},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 Cn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function _n(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 Dn(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?_n(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):_n(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Mn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Mn=function(){return!!e})()}var xn=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Mn()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),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 s=e.reporter;return r.signaling=e.signaling,r.reporter=s,r.handleEvent=r.handleEvent.bind(r),r.handleSyncEvent=r.handleSyncEvent.bind(r),r.sync=r.sync.bind(r),r}return f(t,e.EventEmitter),u(t,[{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(t){var r,n=t.id,i=t.info.owner,o=t.media,a=o.video,s=o.audio;if(!this.streams.get(n)){var c=null===(r=t.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source,u=z(this.streams.values()).find((function(e){var t;return e.info.owner===i&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===c}));u&&this.remove(u.id),this.reporter.trace.streamsEvent(n,"add"),this.streams.set(t.id,t);var d=(null==a?void 0:a.source)===e.VideoSourceInfo.SCREENCAST;((null==a?void 0:a.source)===e.VideoSourceInfo.CAMERA||d)&&this.emit("stream","add",{id:n,owner:i,mediaType:"video",auxiliary:d}),(null==s?void 0:s.source)!==exports.AudioSourceInfo.MIC&&(null==s?void 0:s.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","add",{id:n,owner:i,mediaType:"audio"})}}},{key:"remove",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.streams.get(t);if(n&&(this.streams.delete(t),r)){this.reporter.trace.streamsEvent(t,"remove");var i=n.media,o=i.video,a=i.audio,s=n.info.owner,c=(null==o?void 0:o.source)===e.VideoSourceInfo.SCREENCAST;((null==o?void 0:o.source)===e.VideoSourceInfo.CAMERA||c)&&this.emit("stream","remove",{id:t,owner:s,mediaType:"video",auxiliary:c}),(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIC&&(null==a?void 0:a.source)!==exports.AudioSourceInfo.MIXED||this.emit("stream","remove",{id:t,owner:s,mediaType:"audio"})}}},{key:"getStreamByTrackId",value:function(e){return z(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(t,r){var n=this,i=t.streamId,o=t.status,a=t.stream,s=t.msg,c=t.totalVer,u={add:[],remove:[],update:["audio.status","video.status","properties"]}[o];u.length&&!u.includes(s.field)||this.reporter.log.debug("streamEvent ".concat(JSON.stringify(t)));var d=this.totalVer;if(c===d+1||c==G||r)if("add"===o){if(!a||!a.media||!a.info)return;this.add(a)}else if("remove"===o)this.remove(i,!0);else if("update"===o){var l=s.field,p=s.streamStatus,f=s.activeStream,v=s.extraValue,m=s.streamVer,h=s.propertiesJsonStr,y=this.streams.get(i);if(y){m!==G&&(y.version=m);var g,b=y.media,S=b.video,k=y.info.owner;if("audio.status"===l||"video.status"===l)"audio.status"===l?(g="audio",b.audio.status=p):"video.status"===l&&(g="video",S.status=p),this.reporter.trace.streamsEvent(i,"".concat(g," ").concat(p)),this.emit("stream","update",{owner:k,id:i,updateStatus:"".concat("active"===p?"unmute":"mute","-").concat(g)});else if("activeInput"===l){var P=[f].concat(v||[]).map((function(e){var t;return null===(t=n.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(P),l),this.emit("stream","volumeActive",{owners:P})}else if("properties"==l){var E,w=JSON.parse(h);y.info.attributesJsonStr=JSON.stringify(Dn(Dn({},JSON.parse(y.info.attributesJsonStr)),w));var T=(null===(E=y.media)||void 0===E||null===(E=E.video)||void 0===E?void 0:E.source)===e.VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:k,id:i,properties:w,auxiliary:T})}}}r||this.totalVer>=c&&c!==G||(c===d+1&&(this.totalVer=c),c>d+1&&!r&&this.sync())}},{key:"sync",value:(r=i(x.mark((function e(){var t,r,n,i,o,a,s,c,u,d,l,p,f,v,m=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=4,this.signaling.getStreamsVer({});case 4:i=(n=e.sent).streamVersions,o=n.totalVer,a=z(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=An(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(l=(u=c.value).streamVer,!(d=u.streamId).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=An(m.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=An(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;m.streams.has(l.id)?m.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;p.length>f;f++){var h=p[f];v.includes(h.id)?m.handleEvent({status:"remove",streamId:h.id,stream:h,totalVer:i},!0):r.includes(h.id)&&m.handleEvent({status:"add",streamId:h.id,stream:h,totalVer:i},!0)}a.clear(),m.totalVer=i}));case 34:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){e.streamsVer>this.totalVer&&this.sync()}}]);var r}();function jn(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 e.length>n?{done:!1,value:e[n++]}:{done:!0}},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);t>r;r++)n[r]=e[r];return n}function Nn(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 Vn(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Nn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Nn(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 Un=function(){function t(n,i){var a,s,c,u;return o(this,t),s=this,c=l(c=t),a=d(s,Gn()?Reflect.construct(c,[],l(s).constructor):c.apply(s,u)),Object.defineProperty(a,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"sessionManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"groupManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"userManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"remoteAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"internalChannel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"roomId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"defaultVideoStreamType",{enumerable:!0,configurable:!0,writable:!0,value:"high"}),Object.defineProperty(a,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"subscribedAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"micMixedGroups",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"iceConfig",{enumerable:!0,configurable:!0,writable:!0,value:{level:0,iceServerList:[]}}),Object.defineProperty(a,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r,n=t.mediaType,i=t.action,o=t.uid,s=t.auxiliary,c=a.getStream(t),u=a.userManager.users.get(o),d=a.groups.some((function(e){return e.joined})),l="mcu"===o?a.remoteAudioTrack:s?null==u?void 0:u.auxiliaryTrack:null==u?void 0:u.videoTrack;return"mcu"===o&&"video"===n||o&&"mcu"!==o&&"audio"===n?r=new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support ".concat(i," mcu audio")):"mcu"===o&&d&&"subscribe"===i?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"cannot subscribe mcu while in group"):"subscribe"===i&&l?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"duplicated subscription"):c&&("unsubscribe"!==i||l)||(a.reporter.log.warn("".concat(o," videoTrack not existed")),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted)),{uid:o,user:u,error:r,stream:c,session:"unsubscribe"===i?a.sessionManager.getSessionByStreamId(c.id):null,resolutionInfo:"video"===n?Ne(a.defaultVideoStreamType,fr(c)):null}}}),Object.defineProperty(a,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,n=t.participants,i=t.groupList,o=t.groupListVer;a.streamManager.init(t.streams,t.streamsVer),De.grouptalk&&a.groupManager.init(i,o),a.userManager.init(n,r),a.streamManager.on("stream",a.handleStreamEvent),a.userManager.on("user",a.handleUserEvent),a.groupManager.on("group",a.handleGroupEvent)}}),a.reporter=i,a.internalChannel=new r.DingRTCChannel({reporter:i,gslb:De.gslb[0],sdkVersion:V}),a.signaling=new Kt(a.internalChannel),a.client=n,a.micMixedGroups=new Set,a.groupManager=new Pn(a),a.userManager=new Rn(a),a.streamManager=new xn(a),a.sessionManager=new yn(n,a),a.subscribedAudioStream="",a.handleStreamEvent=a.handleStreamEvent.bind(a),a.handleUserEvent=a.handleUserEvent.bind(a),a.handleGroupEvent=a.handleGroupEvent.bind(a),a}return f(t,e.EventEmitter),u(t,[{key:"localTracks",get:function(){return z(this.sessionManager.sessions.values()).filter((function(e){return e.state===A.Processing&&e instanceof en})).map((function(e){return e.tracks[0]}))}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map((function(t){return Vn(Vn({},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);if("add"===e&&!(n===this.userManager.currentPid)&&l)this.client.emit("user-published",l,i,o);else if("remove"===e&&l)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 p=o?l.auxiliaryTrack:l.videoTrack;null==p||p.setSourceMirror(c.mirror)}}else if("volumeActive"===e){var f=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",f)}}},{key:"handleGroupEvent",value:function(e,t,r){if("add"===e)this.client.emit("group-add",t);else if("remove"===e)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){this.client.emit("group-info-updated",t,r.key,r.value)}}},{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(t){var r,n=t.groupId,i=t.uid,o=t.auxiliary;if(n){var a,s=this.groupManager.groups.get(n);return null==s||null===(a=s.audioInfo)||void 0===a?void 0:a.audio}var c="mcu"===i?z(this.streamManager.streams.values()):null===(r=this.userManager.users.get(i))||void 0===r?void 0:r.relatedStreams;return c.find("mcu"===i?function(e){return"admin"===e.info.owner&&"mixed"===e.type}:function(t){var r=t.media.video;return(null==r?void 0:r.source)===(o?e.VideoSourceInfo.SCREENCAST:e.VideoSourceInfo.CAMERA)})}},{key:"join",value:(v=i(x.mark((function e(t){var r=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.signaling.join(t,De.gslb[0]).then((function(e){var t,n,i,o=e.joinResponse,a=e.iceConfig;return r.roomId=o.room.id,n=o.room.ssrcClientSequence,i=Math.log2((t=o.room.ssrcMask)+1),n>2147483647>>i||(Mr=t,Dr=(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 v.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList;e.level&&(e.iceServerList=(void 0===t?[]:t).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:(p=i(x.mark((function e(t){var r,n,i;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=[],this.groups.some((function(e){return e.joined}))?i.push.apply(i,z(z(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})))):i.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,i));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"unpublish",value:function(e){var t=this,r=new Set(e.map((function(e){return e.getTrackId()}))),n=z(this.sessionManager.sessions.values()).filter((function(e){var t;return e instanceof en&&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=hr(t.mediaStream,"audio","mcu",this.remoteAudioTrack),i||t.once("audio-first-frame",(function(){r.remoteAudioTrack.emit("first-frame-decoded")})),this.remoteAudioTrack}return n.getRemoteVideoTrack(t,e.auxiliary)}},{key:"subscribe",value:(c=i(x.mark((function e(t){var r,n,i,o,a=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=this.handleSubscribeParam(t),i=r.stream,o=r.resolutionInfo,!(n=r.error)){e.next=3;break}throw n;case 3:return e.abrupt("return",this.sessionManager.batchSubscribe([{stream:i,uid:t.uid,resolutionInfo:o}]).then((function(e){var r=e[0],n=r.error;if(n)throw n;return a.getRemoteTrack(t,r.subscription)})));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"batchSubscribe",value:(s=i(x.mark((function e(t){var r=this;return x.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=i(x.mark((function e(n){var i;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=[],t.forEach((function(e,t){var o=n[t];i.push({uid:e.uid,auxiliary:e.auxiliary,error:o.error,track:r.getRemoteTrack(e,o.subscription)})})),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 s.apply(this,arguments)})},{key:"unsubscribe",value:function(e){var t=this,r=this.getStream(e),n=e.mediaType,i=e.auxiliary,o=this.handleSubscribeParam(e),a=o.user,s=o.stream,c=o.session,u=o.error;if(u)throw u;this.reporter.trace.unsubscribe({sessionId:null==c?void 0:c.id,remoteStreamId:null==r?void 0:r.id,remoteUserId:e.uid});return t.sessionManager.batchUnscribe([{stream:s,session:c,error:u}]).then((function(){"audio"===n?(t.subscribedAudioStream="",t.remoteAudioTrack.stop(),t.remoteAudioTrack=null):i?a.auxiliaryTrack=null:a.videoTrack=null}))}},{key:"batchUnsubscribe",value:function(e){var t,r=this,n=[],i=jn(e);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.handleSubscribeParam(Vn(Vn({},o),{},{action:"unsubscribe"})),s=a.session,c=a.stream,u=a.user;this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:u.userId}),c&&n.push(Vn({stream:c,user:u,session:s},o))}}catch(e){i.e(e)}finally{i.f()}return n.length?this.sessionManager.batchUnscribe(n).then((function(){for(var e=0,t=n;t.length>e;e++){var i,o=t[e],a=o.user,s=o.auxiliary;if("audio"===o.mediaType)null===(i=r.remoteAudioTrack)||void 0===i||i.stop(),r.remoteAudioTrack=null;else if(s){var c;null===(c=a.auxiliaryTrack)||void 0===c||c.stop(),a.auxiliaryTrack=null}else{var u;null===(u=a.videoTrack)||void 0===u||u.stop(),a.videoTrack=null}}})):Promise.resolve()}},{key:"subscribeGroup",value:function(t){var r=this,n=this.getStream({groupId:t});if(!n)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream)throw new e.DingRTCError(e.ErrorCode.InvaildState,"you were subscribed group or channel already");return this.sessionManager.batchSubscribe([{stream:n,uid:t}]).then((function(e){return r.subscribedAudioStream=n.id,r.remoteAudioTrack=hr(e[0].subscription.mediaStream,"audio",t,r.remoteAudioTrack),r.remoteAudioTrack}))}},{key:"unsubscribeGroup",value:function(t){var r=this,n=this.getStream({groupId:t});if(!n)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"cannot find audio info of the group");if(this.subscribedAudioStream!==n.id)throw new e.DingRTCError(e.ErrorCode.InvaildState,"you were not subscribed the group");return this.sessionManager.batchUnscribe([{stream:n,session:this.sessionManager.getSessionByStreamId(n.id)}]).then((function(){n.id===r.subscribedAudioStream&&(r.subscribedAudioStream="",r.remoteAudioTrack.stop(),r.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=Ne(t,fr(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){n&&e.joinGroupAudioSuccess&&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:(a=i(x.mark((function e(t,r){var n,i,o,a=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=2>=a.length||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 a.apply(this,arguments)})},{key:"unpublishFromGroup",value:(n=i(x.mark((function e(t,r){var n,i,o,a=arguments;return x.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,t){return n.apply(this,arguments)})}]);var n,a,s,c,p,v}();function Fn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Fn=function(){return!!e})()}var Bn={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},qn=function(){function e(t){var r,n,a,s,c;return o(this,e),n=this,a=l(a=e),r=d(n,Fn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),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:(c=i(x.mark((function e(){var t,n,i;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,r.client.getLocalAudioStats();case 2:return t=e.sent.audioLevel,e.next=6,r.client.getRemoteAudioStats();case 6:n=e.sent.audioLevel,i={timestamp:Date.now(),maxRecLevel:Math.min(1,t||0),maxPlayLevel:Math.min(1,Math.max(0,n||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:ne(i.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*i.maxPlayLevel),attr_rec_level:Math.round(32767*i.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=i;case 11:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},Bn),r.client=t,r}return f(e,$t),u(e)}();function Hn(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;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Hn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Hn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Jn(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 e.length>n?{done:!1,value:e[n++]}:{done:!0}},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);t>r;r++)n[r]=e[r];return n}function Qn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Qn=function(){return!!e})()}var Kn=function(){function t(){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Qn()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:e.createUuid(6)}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:e.registerReporter(r.id)}),Object.defineProperty(r,"channel",{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,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(r,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),r.channel=new Un(r,r.reporter),r.handleVisibilitychange=r.handleVisibilitychange.bind(r),r.handleNetworkQuality=r.handleNetworkQuality.bind(r),r.handleConnectionChangeEvent=r.handleConnectionChangeEvent.bind(r),r.handlePageUnload=r.handlePageUnload.bind(r),r.init(),r}return f(t,e.EventEmitter),u(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&&(e.removeTimer(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(t){var r=this;return this.addEventListeners(),this.channel.join(t).then((function(n){var i;return r.channelName=t.channel,r.monitor=new qn(r),r.monitor.on("audio-device-buffer",(function(e){r.reporter.metric.audioDeviceBuffer(e)})),r.syncStatTimer=e.addTimer((function(){r.sendClientStatToRemote()}),2e3,"interval"),{remoteUsers:r.remoteUsers,timeLeft:null===(i=n.room)||void 0===i?void 0:i.timeLeft}})).catch((function(e){throw r.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(t){var r=this;if(this.reporter.log.info("publish",(Array.isArray(t)?t:[t]).map((function(e){return e.trackMediaType}))),"connected"!==this.connectionState)return Promise.reject(new e.DingRTCError(e.ErrorCode.PublishNotJoinChannel));var n,i=(Array.isArray(t)?t:[t]).filter((function(e){return e instanceof Xe&&!r.localTracks.includes(e)})),o=i.concat(this.localTracks),a=j(j(j(j({},exports.VideoSourceInfo.CAMERA,0),exports.VideoSourceInfo.SCREENCAST,0),exports.AudioSourceInfo.MIC,0),exports.AudioSourceInfo.MIXED,0),s=Jn(o);try{for(s.s();!(n=s.n()).done;){var c=n.value;if(a[c.source]++,a[c.source]>=2)throw new e.DingRTCError(e.ErrorCode.QuotaLimitExceed,"".concat(c.source," published already"))}}catch(e){s.e(e)}finally{s.f()}if(!i.length)throw new e.DingRTCError(e.ErrorCode.PublishNoStream);return this.channel.publish(i)}},{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=i(x.mark((function t(r,n,i){return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(this.reporter.log.info("subscribe",r,n),"connected"===this.connectionState){t.next=3;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 3:return t.abrupt("return",this.channel.subscribe({uid:r,mediaType:n,action:"subscribe",auxiliary:i}));case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"batchSubscribe",value:function(t){if(Array.isArray(t)&&t.length){if(this.reporter.log.info("batchSubscribe",t),"connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);return this.channel.batchSubscribe(t.map((function(e){return Yn(Yn({},e),{},{action:"subscribe"})})))}}},{key:"unsubscribe",value:(r=i(x.mark((function e(t,r,n){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("unsubscribe",t,r),e.abrupt("return",this.channel.unsubscribe({uid:t,auxiliary:n,mediaType:r,action:"unsubscribe"}));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(t){if(Array.isArray(t)&&t.length)return this.reporter.log.info("batchUnsubscribe",t),"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel)):this.channel.batchUnsubscribe(t.map((function(e){return Yn(Yn({},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;e[t.userId]={downlinkNetworkQuality:Number((null==i||null===(r=i[F])||void 0===r?void 0:r[D.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[F])||void 0===n?void 0:n[D.UPLINK])||0)}})),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.reporter.log.debug("connectionStateChange from ".concat(t," to ").concat(e," ").concat(r||"")),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var e=this.clientStatSync.join("");if(e!==this.currentClientState){var t=re(null,e[D.UPLINK]),r=re(null,this.currentClientState[D.UPLINK]),n=re(null,e[D.DOWNLINK]),i=re(null,this.currentClientState[D.DOWNLINK]);t===r&&n===i||this.channel.userManager.setParticipantProperties(e),this.currentClientState=e}}},{key:"handleVisibilitychange",value:function(){var t="visible"!==document.visibilityState,r=t?e.TraceEvent.APP_BACKGROUND:e.TraceEvent.APP_FOREGROUND;(e.Environment.isAndroid()||e.Environment.isIOS())&&(this.reporter.sender.sendEvent(r),this.clientStatSync[D.BACKGROUND_MODE]=Number(t))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[D.UPLINK]=e,this.clientStatSync[D.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.Environment.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.Environment.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(t){var r=t.userData,n=t.groupId,i=new TextEncoder;if(!n||i.encode(n).length>64)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"join group with invalid groupId");if(r){var o=new TextEncoder;if("string"!=typeof r||o.encode(r).length>64)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"join group with invalid userData")}return this.channel.joinGroup(t)}},{key:"leaveGroup",value:function(e){return this.channel.leaveGroup({groupId:e,publishAudioToChannel:!1})}},{key:"setGroupName",value:function(t,r){var n=new TextEncoder;if(!r||n.encode(r).length>64)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"update group with invalid name");return this.channel.setGroupProperties(t,{key:"name",value:r})}},{key:"subscribeGroup",value:function(e){return this.channel.subscribeGroup(e)}},{key:"unsubscribeGroup",value:function(e){return this.channel.unsubscribeGroup(e)}},{key:"mixAudioToGroup",value:function(t,r,n){if("audio"!==t.trackMediaType)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support publish audio to group");if("connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.PublishNotJoinChannel);if(r){if(this.reporter.log.info("mix audio track:".concat(t.getTrackId()," to group ").concat(n)),null==n&&this.channel.micMixedGroups.size)throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot mix audio to channel while mixing to others group");return this.channel.publishToGroup(t,n,!0)}if(this.reporter.log.info("unmix audio track:".concat(t.getTrackId()," from group ").concat(n)),!this.channel.micMixedGroups.has(n))throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot unmix audio from the unmixed group");return this.channel.unpublishFromGroup(t,n)}},{key:"dismissGroup",value:function(e){return this.channel.dismissGroup(e)}},{key:"register",value:function(e){e.attach(this.channel.internalChannel)}},{key:"ungister",value:function(e){e.detach(this.channel.internalChannel)}}]);var r,n}();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 e.length>n?{done:!1,value:e[n++]}:{done:!0}},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);t>r;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 t(){var e,r,n,a,s;return o(this,t),r=this,n=l(n=t),e=d(r,Xn()?Reflect.construct(n,[],l(r).constructor):n.apply(r,a)),Object.defineProperty(e,"deviceList",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checking",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"checkDeviceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:(s=i(x.mark((function r(){var n;return x.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=2;break}return r.abrupt("return");case 2:return e.checking=!0,r.next=5,t.getDevices();case 5:e.compareDevices(n=r.sent,"audiooutput"),e.compareDevices(n,"videoinput"),e.compareDevices(n,"audioinput"),e.deviceList=n,e.checking=!1;case 11:case"end":return r.stop()}}),r)}))),function(){return s.apply(this,arguments)})}),Object.defineProperty(e,"compareDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(t,r){var n,i=t.filter((function(e){return e.kind===r})),o=e.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){return!s.includes(e.deviceId)})),u=o.filter((function(e){return!a.includes(e.deviceId)})),d={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},l=zn(c);try{for(l.s();!(n=l.n()).done;){e.emit(d[r],{device:n.value,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var p,f=zn(u);try{for(f.s();!(p=f.n()).done;){e.emit(d[r],{device:p.value,state:"inactive"})}}catch(e){f.e(e)}finally{f.f()}}}),t._instance?d(e,t._instance):(e.deviceList=[],Ae.checkSupported()?(t.getDevices().then((function(t){e.deviceList=t,e.addEventListeners()})),e):d(e))}return f(t,e.EventEmitter),u(t,[{key:"addEventListeners",value:function(){"ondevicechange"in navigator.mediaDevices?navigator.mediaDevices.addEventListener("devicechange",this.checkDeviceUpdate):e.addTimer(this.checkDeviceUpdate,1e3,"interval")}}],[{key:"getInstance",value:function(){return t._instance}},{key:"getDevices",value:function(){return new Promise((function(t,r){var n,i;null!==(n=navigator.mediaDevices)&&void 0!==n&&n.enumerateDevices?null===(i=navigator.mediaDevices)||void 0===i||i.enumerateDevices().then((function(e){return t(e.filter((function(e){return e.deviceId})))})).catch(r):r(new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}();Object.defineProperty(Zn,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new Zn}),Object.defineProperty(Zn,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Zn.getDevices().then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}}),Object.defineProperty(Zn,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Zn.getDevices().then((function(e){return e.filter((function(e){return"videoinput"===e.kind}))})).catch((function(t){throw e.parseVideoDeviceError(t)}))}}),Object.defineProperty(Zn,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return Zn.getDevices().then((function(e){return e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}});function ei(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ei=function(){return!!e})()}he();var ti=e.getReporter().log,ri=new(function(){function t(){var r,n,i,a;if(o(this,t),n=this,i=l(i=t),r=d(n,ei()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.VERSION=V,!Ae.checkSupported())return d(r);var s=Zn.getInstance();return s.on("camera-changed",(function(e){r.emit("camera-changed",e)})),s.on("microphone-changed",(function(e){r.emit("microphone-changed",e)})),s.on("playback-device-changed",(function(e){r.emit("playback-device-changed",e)})),e.EventBus.on("autoplay-failed",(function(e){r.emit("autoplay-failed",e)})),r}return f(t,e.EventEmitter),u(t,[{key:"createClient",value:function(){return ti.info("createClient"),new Kn}},{key:"checkSystemRequirements",value:function(){return ti.info("checkSystemRequirements"),Ae.checkSupported()}},{key:"getSupportedCodec",value:function(){return ti.info("getSupportedCodec"),Ae.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return ti.info("createCameraVideoTrack",e),it(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return ti.info("createMicrophoneAudioTrack",e),nt(e)}},{key:"createCustomVideoTrack",value:function(e){return ti.info("createCustomVideoTrack",e),st(e)}},{key:"createCustomAudioTrack",value:function(e){return ti.info("createCustomAudioTrack",e),ct(e)}},{key:"createScreenVideoTrack",value:function(e){return ti.info("createScreenVideoTrack",e),ot(e)}},{key:"createMicrophoneAndCameraTracks",value:(r=i(x.mark((function e(t,r){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return ti.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",at(t,r));case 2:case"end":return e.stop()}}),e)}))),function(e,t){return r.apply(this,arguments)})},{key:"getCameras",value:function(){return ti.info("getCameras"),Zn.getCameras()}},{key:"getDevices",value:function(){return ti.info("getDevices"),Zn.getDevices()}},{key:"getPlaybackDevices",value:function(){return ti.info("getPlaybackDevices"),Zn.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return ti.info("getMicrophones"),Zn.getMicrophones()}},{key:"setLogLevel",value:function(t){e.setLogLevel(t),ti.info("setLogLevel",t)}},{key:"setClientConfig",value:function(e){ti.info("setClientConfig",e),De.setClientConfig(e)}}]);var r}());Object.defineProperty(exports,"ErrorCodeAndMsgMap",{enumerable:!0,get:function(){return e.ErrorCodeAndMsgMap}}),exports.FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},exports.default=ri;