dingrtc 3.8.8 → 3.8.9

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 CHANGED
@@ -1 +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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,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 h={exports:{}},m={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}(m);var y=m.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=t&&t.prototype instanceof S?t:S,o=Object.create(i.prototype),a=new M(n||[]);return s(o,"_invoke",{value:A(e,r,a)}),o}function v(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}i.wrap=f;var h="suspendedStart",m="suspendedYield",y="executing",g="completed",b={};function S(){}function k(){}function P(){}var w={};p(w,u,(function(){return this}));var E=Object.getPrototypeOf,T=E&&E(E(x([])));T&&T!==o&&a.call(T,u)&&(w=T);var O=P.prototype=S.prototype=Object.create(w);function I(e){["next","throw","return"].forEach((function(t){p(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,r){function n(i,o,s,c){var u=v(e[i],e,o);if("throw"!==u.type){var d=u.arg,l=d.value;return l&&"object"==t(l)&&a.call(l,"__await")?r.resolve(l.__await).then((function(e){n("next",e,s,c)}),(function(e){n("throw",e,s,c)})):r.resolve(l).then((function(e){d.value=e,s(d)}),(function(e){return n("throw",e,s,c)}))}c(u.arg)}var i;s(this,"_invoke",{value:function(e,t){function o(){return new r((function(r,i){n(e,t,r,i)}))}return i=i?i.then(o,o):o()}})}function A(e,t,r){var i=h;return function(o,a){if(i===y)throw Error("Generator is already running");if(i===g){if("throw"===o)throw a;return{value:n,done:!0}}for(r.method=o,r.arg=a;;){var s=r.delegate;if(s){var c=C(s,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===h)throw i=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=y;var u=v(e,t,r);if("normal"===u.type){if(i=r.done?g:m,u.arg===b)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=g,r.method="throw",r.arg=u.arg)}}}function 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(o.tryLoc<=this.prev){var c=a.call(o,"catchLoc"),u=a.call(o,"finallyLoc");if(c&&u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&a.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),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}(h);var g=(0,h.exports)(),b=g;try{regeneratorRuntime=g}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=g:Function("r","regeneratorRuntime = r")(g)}var S,k,P,w,E,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,(w=exports.VideoSourceInfo||(exports.VideoSourceInfo={})).CAMERA="camera",w.SCREENCAST="screen-cast",w.MIXED="mixed",function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(E||(E={})),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],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,(L=exports.AudioSourceState||(exports.AudioSourceState={})).Playing="playing",L.Paused="paused",L.Stopped="stopped";var V="3.8.7-beta.3",F=-999,U="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.Environment.browserType,e.Environment.browserVersion,e.Environment.system,e.Environment.systemVersion;var G="onertc_state_sync",B="onertc_internal_track_event",q=e.getReporter().log,H=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),q.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 q.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}()),J=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},n=r.setParameters,i=r.getParameters;return!(!n||!i)&&(!e.Environment.isFirefox()&&(e.Environment.isSafari()?parseInt(e.Environment.browserVersion)>=14:e.Environment.isChrome()?parseInt(e.Environment.browserVersion)>=81:!e.Environment.isAndroid()))};function Y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Q(e,t){if(e){if("string"==typeof e)return Y(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)?Y(e,t):void 0}}function W(e){return function(e){if(Array.isArray(e))return Y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Q(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function K(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(K=function(){return!!e})()}var z=e.getReporter().log,$=function(){function t(){var e,r,n,i;return o(this,t),r=this,n=l(n=t),e=d(r,K()?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:J()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),e}return f(t,e.EventEmitter),u(t,[{key:"setClientConfig",value:function(t){z.info("setClientConfig",t);var r=t||{},n=r.gslb,i=r.simulcast,o=r.audioSFU,a=r.republish,s=r.disableTransportCC;"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&&J()&&(this.simulcast=Boolean(i)),null!=o&&(this.audioSFU=Boolean(o)),null!=s&&(this.disableTransportCC=Boolean(s)),null!=a&&(this.republish=Boolean(a))}}])}(),X=new $,Z=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},ee=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var n=[],i=r.optional,o=r.parameters;return null!=o&&o.resolution&&n.push(o.resolution),null!=i&&null!==(t=i.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&n.push.apply(n,W(i.parameters.resolution)),n.sort(Z),n},te=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},re=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},ne=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?X.audioSFU?n?n.replaceStream(e):i=new Jt(null,r,e):n?n.replaceTrack(a[0]):i=new Jt(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new Yt(o[0],r)),i},ie=function(e){return"object"===a(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function oe(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 ae(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?oe(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):oe(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function se(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 ce(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)?ce(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ce(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ue(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ue=function(){return!!e})()}var de=e.getReporter().log,le=function(){function t(){var e,r,n,a,s;return o(this,t),r=this,n=l(n=t),e=d(r,ue()?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:n=r.sent,e.compareDevices(n,"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){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),d={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},l=se(c);try{for(l.s();!(n=l.n()).done;){var p=n.value;e.emit(d[r],{device:p,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var f,v=se(u);try{for(v.s();!(f=v.n()).done;){var h=f.value;e.emit(d[r],{device:h,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),t._instance?d(e,t._instance):(e.deviceList=[],H.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).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:"getMedias",value:function(e,t){var r,n,i=this;return ie(e)?(de.info("getDisplayMedia with",t),null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t)):(de.info("getUserMedia with",t),null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t})))}},{key:"getDevices",value:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(i,o){var a;if(null!==(a=navigator.mediaDevices)&&void 0!==a&&a.enumerateDevices){var s=!1;r.audio&&r.video?s=t.audioPermitted&&t.videoPermitted:r.audio?s=t.audioPermitted:r.video&&(s=t.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(e){var a=e.filter((function(e){return e.deviceId})),c=a.filter((function(e){return"videoinput"===e.kind})),u=a.filter((function(e){return"audioinput"===e.kind})),d=a.filter((function(e){return"audiooutput"===e.kind})),l=[];r.audio&&(l=l.concat(u,d)),r.video&&(l=l.concat(c)),0!==l.length||s||n?l.length?(r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),i(l)):i(l):(de.info("getUserMedia with",r),navigator.mediaDevices.getUserMedia(r).then((function(e){r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),e.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){i(e)}),o)}),o)),i(a)}))}else o(new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}();Object.defineProperty(le,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(le,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(le,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new le}),Object.defineProperty(le,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return le.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}}),Object.defineProperty(le,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return le.getDevices({video:!0}).then((function(e){return e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return ae(ae({},r),{},{toJSON:function(){return r}})}))})).catch((function(t){throw e.parseVideoDeviceError(t)}))}}),Object.defineProperty(le,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return le.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}});var pe=function(e){return{width:N[e][0],height:N[e][1]}},fe=function(t){var r,n=Object.create({}),i={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(i=navigator.mediaDevices.getSupportedConstraints(),console.log(i));var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.Environment.isSafari()?n.deviceId=t.deviceId:n.deviceId={exact:t.deviceId}),i.autoGainControl&&(n.autoGainControl={ideal:null==a||a}),i.echoCancellation&&(n.echoCancellation={ideal:null==o||o}),i.noiseSuppression&&(n.noiseSuppression={ideal:null==s||s}),n},ve=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(!ie(t)&&"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(ie(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("object"===a(r)&&r.source===exports.AudioSourceInfo.MIC||"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST?i.audio=fe(r):i.audio=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=pe(p)),o&&o.width&&o.height&&(u===exports.VideoSourceInfo.SCREENCAST||e.Environment.isFirefox()?(i.video.width=o.width,i.video.height=o.height):(i.video.width={ideal:o.width,max:o.width},i.video.height={ideal:o.height,max:o.height})),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 le.getMedias(t,i)};function he(){return he="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(arguments.length<3?e:r):i.value}},he.apply(null,arguments)}var me,ye,ge=void 0,be=function(e){if(!e)return{};var t={id:e.id,active:e.active},r=e.getTracks().map((function(e){return function(e){var t={};return e?(t.kind=e.kind,t.label=e.label,t.id=e.id,t.contentHint=e.contentHint,t.enabled=e.enabled,t.muted=e.muted,t.readyState=e.readyState,t.settings=e.getSettings(),t.constraints=e.getConstraints(),t):t}(e)}));return t.trackInfos=r,t},Se=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},ke=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},Pe=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},we=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Ee=function(){var e=i(x.mark((function e(t){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,new Promise((function(e){setTimeout(e,t)}));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),Te=function(t){return new Promise((function(r){e.addTimer(r,1e3*t)}))},Oe=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=null,i=0;return function(){for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];var c=Date.now();c-i>=t&&r?(e.apply(ge,a),i=c):(n&&clearTimeout(n),n=setTimeout((function(){e.apply(ge,a),i=c}),t))}},Ie=e.getReporter().log,Re="rtc-intersecting",Ae="visible",Ce="invisible",_e=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],De=function(e){return"".concat(null==e?void 0:e.getAttribute(U),"-").concat(null==e?void 0:e.rtcPurpose)},Me=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(W(i.mediaElementPool),W(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(De(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=be(r);Ie.debug(n,o),"visible"===document.visibilityState&&Se(r)&&t.load()}if(t.paused){var a=!1;if(i.hasActivated&&"video"===i.mediaKind?function(e){return e&&e.getAttribute(Re)===Ae}(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(De(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(Re),", mediaStream="),c=be(r);Ie.error(s,c),Se(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(De(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=be(r);return Ie.error(o,a),void("visible"===document.visibilityState&&Se(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=be(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Ie.error(r,n,o)}}),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=be(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Ie.debug(r,n,o)}}),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=be(null==t?void 0:t.srcObject);Ie.debug(r,n)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=[].concat(W(i.mediaElementPool),W(i.mediaElementsInUse));if(!i.hasActivated&&(i.hasActivated=!0,t.forEach((function(e){e.load()})),i._activatedListener))try{i._activatedListener()}catch(t){Ie.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(Re,Ae):null===(r=e.target)||void 0===r||r.setAttribute(Re,Ce)}))})));for(var a=0;a<n;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){_e.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}}])}(),xe=function(){return me||Ne(),me},je=function(){return ye||Ne(),ye},Le=e.Environment.isIOS()||e.Environment.isAndroid()?9:25,Ne=function(){me||(me=new Me("audio",2)),ye||(ye=new Me("video",Le))},Ve=new AudioContext,Fe=function(e){var t=e.getAudioTracks(),r=Ve.createMediaStreamDestination();return t.forEach((function(e){Ve.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},Ue=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},Ge=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")},Be=xe(),qe=je(),He=e.getReporter().log,Je=function(){return u((function e(){o(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(t,r,n){var i,o=this,a=t.getTrackId(),s=t.sfuStream||new MediaStream([t.getMediaStreamTrack()]);if("video"===t.trackMediaType){var c,u=this.findDom(r);if(!u)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"wrapper dom not found");var d=n||{},l=d.mirror,p=d.fit;if((i=this.players.find((function(e){return e.container===r})))&&(null===(c=i.track)||void 0===c?void 0:c.getTrackId())!==(null==t?void 0:t.getTrackId()))return this.stop(i.track,r),void this.play(t,r,n);i?(i.element.pause(),!t.sourceMirror!=!l?i.element.style.transform="scaleX(-1)":i.element.style.transform="",p&&(i.element.style.objectFit=p),i.element.srcObject=s,i.element.load()):((i={container:r,track:t,playerConfig:n}).element=function(e,t,r){var n=je().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n}(u,s,{mirror:!t.sourceMirror!=!l,fit:p}),this.players.push(i))}else(i=this.players.find((function(e){var r;return(null===(r=e.track)||void 0===r?void 0:r.getTrackId())===t.getTrackId()})))?(i.element.pause(),i.element.srcObject=s,i.element.load()):((i={track:t}).element=function(e){var t=xe().popElement();return t.srcObject=e,t}(s),this.players.push(i));i.element.paused&&i.element.play().then((function(){i.isPlaying=!0})).catch((function(t){"NotAllowedError"===t.name?(He.error("autoplay failed",e.tryJsonStringify(t)),e.EventBus.emit("autoplay-failed",o)):He.warn("".concat(a," play has exception"),e.tryJsonStringify(t))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?Be.pushElement(t.element):qe.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),Ye=new Je,Qe=function(){return Ye};function We(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(We=function(){return!!e})()}var Ke,ze=e.getReporter(),$e=ze.log,Xe=ze.trace,Ze=Qe(),et=function(){function t(r,n){var i,a,s,c;return o(this,t),a=this,s=l(s=t),i=d(a,We()?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,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:Xe}),Object.defineProperty(i,"sourceNode",{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,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r?(i.trackMediaType=r.kind,i.trackSettings=r.getSettings()):n&&(i.trackMediaType="audio"),"audio"===i.trackMediaType&&(i.audioContext=Ve,i.analyser=i.audioContext.createAnalyser()),i.trackId="".concat(i.trackMediaType,"_").concat(e.createUuid(6)),i.setMediaStreamTrack(r,n),i}return f(t,e.EventEmitter),u(t,[{key:"isPlaying",get:function(){return Ze.isPlaying(this)}},{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=Fe(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){$e.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(B,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{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(e){$e.info("stop paly track ".concat(this.getTrackId())),Ze.stop(this,e)}},{key:"innnerPlay",value:function(t){var r=this,n=t.element,i=t.config;t.updated?Ze.getPlayInfos(this).forEach((function(e){e.container?Ze.findDom(e.container)?Ze.play(r,e.container,e.playerConfig):Ze.stop(r,e.container):Ze.play(r,e.container,e.playerConfig)})):Ze.play(this,n,i);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(t){$e.debug("resume audioContext failed: ".concat(e.tryJsonStringify(t)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function tt(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)||Q(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function rt(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 nt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?rt(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rt(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(Ke||(Ke={}));var it=j(j(j(j(j(j({},Ke.LLD,"lld"),Ke.LD,"ld"),Ke.SD,"sd"),Ke.HD,"hd"),Ke.FHD,"fhd"),Ke.QHD,"qhd"),ot={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},at=function(e){return 2560===e.width&&1440===e.height},st=function(e,t){var r=ut(e,t),n=function(e,t){var r={high:M.QHD,low:M.LD,QHD:M.QHD,FHD:M.FHD,HD:M.HD,SD:M.SD,LD:M.LD},n=r[e]||M.None,i=ot[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(ot).find((function(e){var t=tt(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[tt(a,1)[0]]}return n}(e,t);return{resolution:r,resolutionLevel:n}},ct=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},ut=function(e,t){var r=ot[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&at(i))return i;if(t[0].width*t[0].height>ot.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},dt=[49152,76800,307200,1228800,2764800,4915200],lt=[200,350,1e3,1800,2828,5600],pt=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],ft=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],vt=function(e,t){var r=Ke.FHD,n=e*t;return n<=dt[Ke.LLD]?r=Ke.LLD:n<=dt[Ke.LD]?r=Ke.LD:n<=dt[Ke.SD]?r=Ke.SD:n<=dt[Ke.HD]?r=Ke.HD:n<=dt[Ke.FHD]?r=Ke.FHD:n<=dt[Ke.QHD]&&(r=Ke.QHD),r},ht=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=pt[r][0],o=pt[r][1];else if(4*t==3*e)i=ft[r][0],o=ft[r][1];else{var s=Math.sqrt(1*pt[r][0]*pt[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},mt=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=lt[vt(e,t)];n=Math.round(Math.max(i*o,50))}return n},yt=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=vt(t,r),s=[],c=a>=Ke.HD?3:2,u=function(e){var o=tt(ht(t,r,e,a),2),s=o[0],c=o[1],u=lt[e]/lt[a],d=1/(c/r);return{targetWidth:s,rid:it[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:d}};a>Ke.LLD&&s.push(nt({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,Ke.LLD)===o},u(Ke.LLD))),a>Ke.LD&&s.push(nt({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,Ke.LD)===o},u(Ke.LD))),a>Ke.SD&&s.push(nt({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,Ke.SD)===o},u(Ke.SD))),a===Ke.FHD?(s.push(nt({activeForBitrateMap:!1,activeForRealuse:!1},u(Ke.HD))),s.push(nt({activeForBitrateMap:!0,activeForRealuse:X.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(Ke.FHD)))):s.push(nt({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var d=0,l=0;l<s.length;++l)0!=l&&(s[l].minBitrate=d),d=Math.round(Math.max((s[l].maxBitrate+s[l].minBitrate)/2,s[l].maxBitrate-400));return s.shift(),s},gt=function(e,t){var r=vt(e,t),n=Math.pow(2,r);return console.log(n,r),n},bt=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!X.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST||at({width:i,height:o}),c={resolutionLevel:gt(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:X.republish?c.encodings=yt({width:1920,height:1080,frameRate:30,maxBitrate:mt(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=yt({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function St(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 kt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?St(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):St(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Pt(e,t,r){return t=l(t),d(e,wt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function wt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(wt=function(){return!!e})()}function Et(e,t,r,n){var i=he(l(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var Tt=Qe(),Ot=e.getReporter().log,It=function(){function t(e,r){var n;if(o(this,t),n=Pt(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){var i,a=e.muted;if(n.muted=a,!r)r=null===(i=e.getSettings())||void 0===i?void 0:i.deviceId}return n.enabled=!0,n.deviceId=r,n}return f(t,et),u(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;Et(t,"setMediaStreamTrack",this)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(t){return Ot.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;Ot.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 Ot.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 Ot.debug("gengrate new audioTrack"),new Promise((function(r,n){var i;ve({audio:kt(kt({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){Ot.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 Ot.info("gengrate new videoTrack"),new Promise((function(r,n){var i,o=kt({source:t.source},t.config);t.config.deviceId&&(o.deviceId=t.config.deviceId),t.config.facingMode&&t.config.deviceId&&(Ot.info("ignore did param to create videoTrack because facingMode is",t.config.facingMode),delete o.deviceId),ve({video:o,audio:!1}).then((function(e){i=e.getVideoTracks()[0],r(i)})).catch((function(t){Ot.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,Ot.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(r=i(x.mark((function e(t){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(Ot.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof Ct)||"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(Ot.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(),Rt=function(){function t(e,r,n){var i;if(o(this,t),(i=Pt(this,t,[e,r])).config=n,e){var a=e.getSettings(),s=a.width,c=a.height;i.maxBitrate=mt(s,c,n.frameRate,n.maxBitrate)}return i}return f(t,It),u(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(t){var r=this;Ot.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=kt({frameRate:this.config.frameRate},pe(this.config.dimension)),d=this.getMediaStreamTrack();return null==d?void 0:d.applyConstraints(u).then((function(){var e,t=null===(e=r.getMediaStreamTrack())||void 0===e?void 0:e.getSettings(),n=t.width,i=t.height;r.maxBitrate=mt(n,i,r.config.frameRate,o),console.log(n,i,u,r.maxBitrate),r.emit(B,"republish",r)})).catch((function(t){var n=e.parseVideoDeviceError(t);throw Ot.error("videoTrack ".concat(r.getTrackId()," setEncoderConfiguration error"),n),n}))}},{key:"getCurrentFrameData",value:function(){return Ot.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:Ge(Tt.getElement(this)[0])}},{key:"play",value:function(e,r){return Ot.info("local video play"),Et(t,"play",this)([e,r])}}])}(),At=function(){function e(t,r){return o(this,e),Pt(this,e,[t,r])}return f(e,It),u(e,[{key:"setVolume",value:function(e){Ot.info("setVolume",e),this.isClosed||Tt.getElement(this)[0]&&(Tt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Ot.info("getVolume"),!this.isClosed)return Tt.getElement(this)[0]?Tt.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:Ue(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return Ot.info("local audio play"),Et(e,"play",this)([])}}])}(),Ct=function(){function e(t,r){var n;return o(this,e),(n=Pt(this,e,[t,r.deviceId,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return f(e,Rt),u(e)}(),_t=function(){function e(t,r){var n;return o(this,e),(n=Pt(this,e,[t,(r||{}).deviceId])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=n.audioContext.createAnalyser(),n}return f(e,At),u(e,[{key:"setVolume",value:function(e){Ot.info("setVolume",e),this.isClosed||Tt.getElement(this)[0]&&(Tt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Ot.info("getVolume"),!this.isClosed)return Tt.getElement(this)[0]?Tt.getElement(this)[0].volume:void 0}}])}(),Dt=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d,l,p;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return Ot.info("createMicrophoneAudioTrack",r),n={AEC:!0,AGC:!0,ANS:!0},o=(i=r||n).AEC,a=void 0===o||o,s=i.AGC,c=void 0===s||s,u=i.ANS,d=void 0===u||u,t.prev=3,t.next=6,ve({video:!1,audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:a,AGC:c,ANS:d}});case 6:return l=t.sent,p=l.getAudioTracks()[0],Ot.info("MicrophoneAudioTrack created"),t.abrupt("return",new _t(p,Object.assign({},r,{AEC:a,AGC:c,ANS:d})));case 12:throw t.prev=12,t.t0=t.catch(3),e.parseAudioDeviceError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[3,12]])})));return function(e){return t.apply(this,arguments)}}(),Mt=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 Ot.info("createCameraVideoTrack",r),n=r.deviceId,i=r.facingMode,o=r.dimension,a=void 0===o?"VD_640x480":o,s=r.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(30,r.frameRate||15),t.prev=3,t.next=6,ve({video:{deviceId:n,source:exports.VideoSourceInfo.CAMERA,frameRate:u,dimension:a,facingMode:i},audio:!1});case 6:return d=t.sent,l=d.getVideoTracks()[0],Ot.info("CameraVideoTrack created"),t.abrupt("return",new Ct(l,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c})));case 12:throw t.prev=12,t.t0=t.catch(3),e.parseVideoDeviceError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[3,12]])})));return function(e){return t.apply(this,arguments)}}(),xt=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 Ot.info("createScreenVideoTrack",r),n=r.displaySurface,i=void 0===n?"monitor":n,o=r.dimension,a=void 0===o?"VD_1920x1080":o,s=r.optimizationMode,c=void 0===s?"detail":s,u=Math.min(r.frameRate||5,30),t.prev=3,t.next=6,ve({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:i,frameRate:u,dimension:a},audio:!1});case 6:return d=t.sent,(l=new Rt(d.getVideoTracks()[0],null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.SCREENCAST),Ot.info("ScreenVideoTrack created"),t.abrupt("return",[l]);case 13:throw t.prev=13,t.t0=t.catch(3),e.parseScreenShareError(t.t0);case 16:case"end":return t.stop()}}),t,null,[[3,13]])})));return function(e){return t.apply(this,arguments)}}(),jt=function(){var t=i(x.mark((function t(r,n){var i,o,a,s,c,u,d,l,p,f,v,h,m,y,g,b,S,k,P,w;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return Ot.info("createMicrophoneAndCameraTracks",r,n),i=Math.min(r.frameRate||15,30),o=r.deviceId,a=r.facingMode,s=r.dimension,c=void 0===s?"VD_640x480":s,u=r.optimizationMode,d=void 0===u?"balanced":u,l={AEC:!0,AGC:!0,ANS:!0},f=(p=n||l).AEC,v=void 0===f||f,h=p.AGC,m=void 0===h||h,y=p.ANS,g=void 0===y||y,t.prev=5,t.next=8,ve({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:m,ANS:g}});case 8:return b=t.sent,S=b.getVideoTracks()[0],k=b.getAudioTracks()[0],Ot.info("CameraVideoTrack and MicrophoneTrack created"),P=new Ct(S,Object.assign({},r,{frameRate:i,dimension:c,optimizationMode:d})),w=new _t(k,Object.assign({},Object.assign({},n,{AEC:v,AGC:m,ANS:g}))),t.abrupt("return",[P,w]);case 17:throw t.prev=17,t.t0=t.catch(5),e.parseVideoDeviceError(t.t0);case 20:case"end":return t.stop()}}),t,null,[[5,17]])})));return function(e,r){return t.apply(this,arguments)}}(),Lt=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(Ot.info("createCustomVideoTrack",r),i=(n=r||{}).mediaStreamTrack,o=n.dimension,a=void 0===o?"VD_640x480":o,s=n.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(r.frameRate||15,30),i instanceof MediaStreamTrack&&"video"===i.kind){t.next=5;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 5:return(d=new Rt(i,null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.CAMERA),t.abrupt("return",d);case 8:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),Nt=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(Ot.info("createCustomAudioTrack",r),(n=(r||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){t.next=4;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 4:return(i=new At(n)).setSource(exports.AudioSourceInfo.MIC),t.abrupt("return",i);case 7:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();function Vt(e,t,r,n){var i=he(l(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function Ft(e,t,r){return t=l(t),d(e,Ut()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function Ut(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ut=function(){return!!e})()}var Gt,Bt=e.getReporter().log,qt=Qe(),Ht=function(){function e(t,r,n){var i;return o(this,e),i=Ft(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,et),u(e,[{key:"getUserId",value:function(){return Bt.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)}}])}(),Jt=function(){function t(e,r,n){var i;return o(this,t),i=Ft(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return f(t,Ht),u(t,[{key:"getMediaStreamTrack",value:function(){return X.audioSFU?Fe(this.sfuStream):Vt(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){Bt.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){Bt.info("setVolume",e),qt.getElement(this)[0]&&(qt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Bt.info("getVolume"),qt.getElement(this)[0])return qt.getElement(this)[0].volume}},{key:"setSpeaker",value:function(t){var r=this;return Bt.info("setSpeaker",t),new Promise((function(n,i){var o,a=qt.getElement(r)[0];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 Ue(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return Bt.info("remote audio play"),Vt(t,"innnerPlay",this,3)([{}])}}])}(),Yt=function(){function e(t,r){return o(this,e),Ft(this,e,[t,r])}return f(e,Ht),u(e,[{key:"play",value:function(t,r){return Bt.info("remote video play"),Vt(e,"innnerPlay",this,3)([{element:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(Bt.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&Vt(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return Bt.info("getCurrentFrameData"),this.isPlaying?Ge(qt.getElement(this)[0]):null}}])}();!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(Gt||(Gt={}));var Qt={nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"uint32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}}},Wt=e.getProtobufRoot(Qt),Kt=Wt.lookupType("signal_msg.Response"),zt=Wt.lookupType("signal_msg.BatchNotification"),$t=Wt.lookupType("signal_msg.MediaMessage"),Xt=Wt.lookupType("signal_msg.StreamNotification");Wt.lookupType("signal_msg.ProgressNotification");var Zt=Wt.lookupType("signal_msg.ServerFailoverNotification"),er=Wt.lookupType("signal_msg.PublishRequest"),tr=Wt.lookupType("signal_msg.SoacRequest"),rr=Wt.lookupType("signal_msg.UnpublishRequest"),nr=Wt.lookupType("signal_msg.StreamControlRequest"),ir=Wt.lookupType("signal_msg.SubscribeRequest"),or=Wt.lookupType("signal_msg.SetStreamPropertiesRequest"),ar=Wt.lookupType("signal_msg.UnsubscribeRequest"),sr=Wt.lookupType("signal_msg.SubscriptionControlRequest"),cr=Wt.lookupType("signal_msg.CreatePeerConnectionRequest"),ur=Wt.lookupType("signal_msg.ClosePeerConnectionRequest"),dr=Wt.lookupType("signal_msg.BatchPublishRequest"),lr=Wt.lookupType("signal_msg.BatchUnpublishRequest"),pr=Wt.lookupType("signal_msg.BatchSubscribeRequest"),fr=Wt.lookupType("signal_msg.BatchUnsubscribeRequest"),vr=Wt.lookupType("signal_msg.JoinGroupRequest"),hr=Wt.lookupType("signal_msg.SetGroupPropertiesRequest"),mr=Wt.lookupType("signal_msg.DismissGroupRequest"),yr=Wt.lookupType("signal_msg.LeaveGroupRequest"),gr=Wt.lookupType("signal_msg.SyncDataRequest"),br=Wt.lookupType("signal_msg.SyncDataByIdsRequest"),Sr=Wt.lookupType("signal_msg.GroupChangeLog"),kr=Wt.lookupType("signal_msg.GroupListChangeLog"),Pr=Wt.lookupType("signal_msg.SetParticipantPropertiesRequest"),wr=Wt.lookupType("signal_msg.QueryStreamsVerRequest"),Er=Wt.lookupType("signal_msg.QueryStreamsRequest");function Tr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Tr=function(){return!!e})()}var Or=e.getReporter().log,Ir=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Tr()?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",Xt.decode(t)):"serverFailover"===e?this.emit("serverFailover",Zt.decode(t)):"media-message"===e?this.emit("media-message",$t.decode(t)):"group"===e?this.emit("group",Sr.decode(t)):"group-list"===e&&this.emit("group-list",kr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;zt.decode(e).notificationItem.forEach((function(e){"stream"===e.event?t.emit("stream",e.streamNotification):"serverFailover"===e.event?t.emit("serverFailover",e.serverFailoverNotification):"group"===e.event?t.emit("group",e.groupNotification):"group-list"===e.event&&t.emit("group-list",e.groupListNotification)}))}},{key:"createPeerConnection",value:function(e){var t=cr.encode(e).finish();return Or.info("send create-peer-connection",e),this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=ur.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=pr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=hr.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=fr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){Or.info("send batch-publish",e);var t=dr.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=lr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=er.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){Or.info("send set-participant-properties",e);var t=Pr.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=tr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=rr.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=nr.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=or.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=ir.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=ar.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=sr.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=wr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=Er.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=vr.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=yr.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=mr.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=gr.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=br.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(t,r){var n=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(o,a){var s=n.rpcId++;n.reporter.log.info("rtc rpcId ".concat(s,":").concat(t," param====> ").concat(JSON.stringify(i||""))),n.channel.signaling.rpc(t,r,i).then((function(e){var r=Kt.decode(e);r.code===Gt.Result.Ok?(n.reporter.log.debug("rtc rpcId ".concat(s,":").concat(t," result====> ").concat(JSON.stringify(r))),o(r)):(n.reporter.log.debug("rtc rpcId ".concat(s,":").concat(t," error====> ").concat(JSON.stringify(r))),a(r))})).catch((function(r){n.reporter.log.error("rtc rpcId ".concat(s,":").concat(t," error====> ").concat(e.tryJsonStringify(r))),a(r)}))}))}}])}();function Rr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Rr=function(){return!!e})()}var Ar=function(){function t(){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,"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 Cr(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 _r(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Cr(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Cr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Dr(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 Mr(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)?Mr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Mr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function xr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(xr=function(){return!!e})()}var jr={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},Lr={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},Nr=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,xr()?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({},Lr),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({},jr),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,Ar),u(t,[{key:"extractVideoMetrics",value:function(t){var r=this,n=Object.assign({source:this.source,trackStats:[]},Lr,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=ke(n,this.lastVideoSendInfo);return t.forEach((function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var i=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(i.sendFrameWidth=t.frameWidth||0,i.sendFrameHeight=t.frameHeight||0,i.framesSent=t.framesSent||0,i.framesEncoded=t.framesEncoded||0,i.targetBitrate=t.targetBitrate||0,i.qpSum=t.qpSum||0,i.bytesSent=t.bytesSent||0,i.packetsSent=t.packetsSent||0,i.packetsSentForLost=i.packetsSent||0,i.sentTimestamp=t.timestamp||0,i.totalEncodeTime=t.totalEncodeTime||0,i.keyFramesEncoded=t.keyFramesEncoded||0,i.firCount=t.firCount||0,i.pliCount=t.pliCount||0,i.retransmittedBytesSent=t.retransmittedBytesSent||0,i.retransmittedPacketsSent=t.retransmittedPacketsSent||0,i.qualityLimitationReason=t.qualityLimitationReason||"",i.sendFramesPerSecond=t.framesPerSecond||0,i.sendFrameWidth>n.maxSendFrameWidth){if(n.maxSendFrameWidth=i.sendFrameWidth,!i.sendFramesPerSecond&&o){var a=we(i.framesSent||i.framesEncoded,o.framesSent||o.framesEncoded);i.sendFramesPerSecond=Math.round(a/u)}if(i.framesEncoded){var s=we(i.framesEncoded,null==o?void 0:o.framesEncoded);n.encodeFramesPerSecond=Math.round(s/u)}n.sendFramesPerSecond=i.sendFramesPerSecond}c.set(t.ssrc,i),n.targetBitrate=i.targetBitrate,n.totalBytesSent+=i.bytesSent,n.totalPacketsSent+=i.packetsSent,n.totalEncodedTime+=i.totalEncodeTime,n.totalFramesEncoded+=i.framesEncoded,n.totalFramesSent+=i.framesSent,n.totalQpSum+=i.qpSum,n.maxSendFrameHeight=Math.max(i.sendFrameHeight,n.maxSendFrameHeight),c.set(t.ssrc,i)}else if(/track/i.test(t.type)&&!1===t.remoteSource){if(e.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=Dr(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=tt(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=we(a.framesSent,s.framesSent),u=we(a.framesEncoded,s.framesEncoded),d=we(a.keyFramesEncoded,s.keyFramesEncoded),l=we(a.retransmittedBytesSent,s.retransmittedBytesSent),p=we(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=we(a.firCount,s.firCount),v=we(a.pliCount,s.pliCount),h=we(a.packetsSent,s.packetsSent),m=we(a.packetsSentForLost,s.packetsSentForLost),y=we(a.lostTimestamp,s.lostTimestamp),g=we(a.sentTimestamp,s.sentTimestamp),b=we(a.packetsLost,s.packetsLost),S=we(a.totalEncodeTime,s.totalEncodeTime),k=we(a.qpSum,s.qpSum),P=a.qualityLimitationReason,w=a.sendFrameWidth,E=_r(_r({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:w,qualityLimitationReason:P},a),{},{deltaQbSum:k,deltaPacketsSent:h,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:y,deltaFramesEncoded:u,deltaKeyFramesEncoded:d,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:v,deltaTimestampForSent:g,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:l,deltaRetransmittedPacketsSent:p});r.push(E)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,d=we(e.timestamp,this.lastVideoSendInfo.timestamp),l=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var v=f.deltaFramesEncoded||f.deltaFramesSent;l&&(l=0===v),s.attr_encoded_framerate_sim.push(j({},p,Math.round(1e3*v/d))),s.attr_encode_qp_sim.push(j({},p,Math.round((f.deltaQbSum||0)/(v||Number.EPSILON))));var h=f.deltaTimestampForLost,m=f.deltaTimestampForSent,y=f.deltaPacketsLost,g=f.deltaPacketsSentForLost;if(y&&g&&h&&m){var b=y/h/(g/m);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,k=Object.entries(s);S<k.length;S++){var P=tt(k[S],2),w=P[0],E=P[1];t[w]=E.length?JSON.stringify(E):""}var T=0,O=we(o,this.lastVideoSendInfo.totalFramesEncoded),I=we(a,this.lastVideoSendInfo.totalEncodedTime);O&&I&&(T=Math.round(1e3*I/O));var R=we(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=d,t.attr_bitrate=d>0?Math.min(Math.round(8*R*1e3/d),2e7):0,t.attr_enc_average_elapsed_ms=T,this.videoSendReport=t,l&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:d,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},jr,this.connection.peerConnectionStats);return e.forEach((function(e){if(/outboundrtp|outbound-rtp/i.test(e.type)?(r.timestamp=e.timestamp,r.bytesSent=e.bytesSent||0,r.packetsSent=e.packetsSent):/remote-inbound-rtp|remoteinboundrt/i.test(e.type)?void 0!==e.packetsLost&&(r.packetsLost=e.packetsLost):/media-source/i.test(e.type)&&e.audioLevel&&(r.audioLevel=e.audioLevel),t.track){var n=t.track.getMediaStreamTrack().getSettings(),i=n.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(we(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*we(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/we(e.timestamp,this.lastAudioSendInfo.timestamp))},this.emit("audio-send-stream",Object.assign({},this.audioSendReport))),this.lastAudioSendInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){null!=t&&t.audioMetrics&&e.makeAudioReport(t.audioMetrics),null!=t&&t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"getStats",value:function(){var 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 Vr(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 Fr(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)?Fr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Fr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ur(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ur=function(){return!!e})()}var Gr={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},Br={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},qr=function(){function t(r){var n,i,a,s,c;o(this,t),a=this,s=l(s=t),i=d(a,Ur()?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,h=r.transceivers;return i.connection=u,i.pc=u.pc,i.tranceiver=p,i.tranceivers=h,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({},Br),i.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},i.lastAudioReceiveInfo=Object.assign({},Gr),i.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},i}return f(t,Ar),u(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},Gr,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},Gr,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=Vr(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},Br,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(we(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=we(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=we(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=we(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/n,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*i/(t/1e3))},this.emit("audio-net-eq",{attr_speech_expand_rate:0,attr_duration_ms:this.audioReceiveReport.attr_duration_ms,attr_packet_lossrate:Math.round(Math.min(16384*o,16384))}),this.emit("audio-recv-stream",Object.assign({},this.audioReceiveReport))}this.lastAudioReceiveInfo=e}},{key:"makeVideoReport",value:function(e){var t=this.lastVideoReceiveInfo,r=t.firCount,n=t.pliCount,i=t.timestamp,o=t.freezeCount,a=t.packetsLost,s=t.framesDecoded,c=t.framesDropped,u=t.bytesReceived,d=t.packetsReceivedForLost,l=t.retransmittedBytesReceived,p=t.retransmittedPacketsReceived;if(i>0&&e.timestamp){var f=we(e.timestamp,i);if(e.bytesReceived-u>=0){var v=we(e.packetsLost,a),h=we(e.packetsReceivedForLost,d),m=0;try{m=Math.round(v/h*255)}catch(e){m=0}isNaN(m)&&(m=0);var y=we(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*y/f),attr_dec_frames:y,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:we(e.framesDropped,c),attr_fir_count:we(e.firCount,r),attr_freeze_count:we(e.freezeCount,o),attr_pli_count:we(e.pliCount,n),attr_retx_bytes:we(e.retransmittedBytesReceived,l),attr_retx_packets:we(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*we(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:y,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(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=he(l(t.prototype),r,n))?function(e){return i.apply(n,e)}:i)([]),this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();function Hr(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 Jr(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)?Jr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Jr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Yr(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 Qr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Yr(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Yr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Wr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Wr=function(){return!!e})()}var Kr=e.getReporter().log,zr=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Wr()?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,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=e.connection,c=e.stream,u=e.uid,p=e.resolutionInfo,f=e.userConfigResolution;return r.connection=s,r.resolutionInfo=p,r.userConfigResolution=f,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(X.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=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=$r(this.stream,e),t||(this.userConfigResolution=e),this.signaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==A.End&&(this.reset(),this.state=A.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new qr(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 qr(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=ke(r,o),s=we(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=ke(n,l),f=we(n.bytesReceived,l.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(we(null==n?void 0:n.framesDecoded,l.framesDecoded)/p),receiveFrameRate:Math.round(we(null==n?void 0:n.framesReceived,l.framesReceived)/p),receiveFramesDropped:we(null==n?void 0:n.framesDropped,l.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},h=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),m=(null===(d=this.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.source)===exports.VideoSourceInfo.CAMERA&&f>5e3&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&m?h&&v.receiveFramesDropped>0&&!X.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=m),this.videoStatsMap.set(t,v)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(Qr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(Qr({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(Qr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(),$r=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=ct(n);return st(i,ee(e))}return t},Xr=function(e){var t,r={audio:[],video:[]},n=Hr(e);try{for(n.s();!(t=n.n()).done;){var i=t.value,o=i.stream,a=i.error,s=i.resolutionInfo;if(a)Kr.error("skip subscribe",o,a);else{var c=Zr(o,s),u=c.audio,d=c.video;if(u){var l=Qr(Qr({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:fn()}]});X.audioSFU&&(l.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:fn()}}))),r.audio.push(l)}else if(d){var p,f;r.video.push(Qr(Qr({},d),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:fn(),rtxSsrc:fn()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},Zr=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:$r(e,t)}}return a},en=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 zr(Qr(Qr({},r),{},{uid:s,userConfigResolution:c,resolutionInfo:c&&$r(n,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=Xr(t),s.next=3,Sn(n,c,a);case 3:n.signaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:X.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||te(e.stream,s)})),r.abrupt("return",e(o));case 4:c=Hr(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:r=u.value,n=r.id,i=r.msg,s=r.origin,c=a[s.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=te(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)}}(),tn=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,kn(o,t);case 4:o.signaling.batchUnSubscribe({connectionId:o.id,audio:i,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",a);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function rn(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 nn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?rn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):rn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function on(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 an(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)?an(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function an(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var sn=e.getReporter().log,cn={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},un=0,dn=0,ln=0,pn=new Set,fn=function(){if(0==un||0==dn)return 0;var e=Math.min(dn+1,1e4);do{var t=un+(dn&ln++);if(0!=t&&!pn.has(t))return t}while(--e>0);return 0},vn=function(t,r){var n,i;if((null===(n=t.rids)||void 0===n?void 0:n.length)>1)return e.Environment.isFirefox()&&(r=bn(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},hn=function(){var e=i(x.mark((function e(r){var n,i,o,a,s,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=r.transceiver,o=n.remoteSDP,a=n.pc,e.next=4,a.createOffer();case 4:return s=e.sent,e.next=7,a.setLocalDescription(s);case 7:return n.localSDP=t.parse(s.sdp),c=n.localSDP.media.find((function(e){return e.mid==i.mid})),u=o.media.find((function(e){return e.mid==i.mid})),vn(c,u),e.next=13,a.setRemoteDescription({type:"answer",sdp:t.write(o)});case 13:n.remoteSDP=o;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),mn=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 Rt){var r=bt(e).encodings;t.sendEncodings=r.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var i=n.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Rt&&i.sender.setParameters){var o=e.optimizationMode,s=i.sender.getParameters();s.degradationPreference=cn[o]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(sn.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach((function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,sn.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}}))),sn.info("adjustUplinkSDPWhenPublish setParameters",s),i.sender.setParameters(s)}return a.set(e.getTrackId(),i),i})),r.next=5,o.createOffer();case 5:return d=r.sent,l=t.parse(d.sdp),r.next=9,o.setLocalDescription(d);case 9:n.localSDP=l,s.groups[0].mids=n.localSDP.groups[0].mids,p=on(u),r.prev=12,v=x.mark((function t(){var r,n,i,o,a,c,u;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=nn(nn({},n),{},{ext:W(n.ext),mid:r.mid}),o=l.media.find((function(e){return e.mid==r.mid})),a=new URLSearchParams(location.search).get("startkbs"),c=new URLSearchParams(location.search).get("minkbs"),u=new URLSearchParams(location.search).get("maxkbs"),sn.info("startkbs, minkbs",a,c),i.fmtp.map((function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter((function(e){return!/x-google-start-bitrate/i.test(e)}));a&&t.push("x-google-start-bitrate=".concat(a)),c&&t.push("x-google-min-bitrate=".concat(c)),u&&t.push("x-google-max-bitrate=".concat(u)),e.config=t.join(";")}})),vn(o,i),s.media.push(i);case 12: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 window.remoteSDP=s,r.next=30,o.setRemoteDescription({type:"answer",sdp:t.write(s)});case 30:return n.remoteSDP=s,r.abrupt("return",{localSDP:n.localSDP,stream:c});case 32:case"end":return r.stop()}}),r,null,[[12,21,24,27]])})));return function(e,t){return r.apply(this,arguments)}}(),yn=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 a=e.sent,s=t.parse(a.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)}}(),gn=function(t,r,n){var i=t.ssrc,o=t.rtxSsrc;!function(e){e.ssrc&&pn.add(e.ssrc),e.rtxSsrc&&pn.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})}))},bn=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},Sn=function(){var e=i(x.mark((function e(r,n,i){var o,a,s,c,u,d,l,p,f,v,h,m,y,g,b,S,k,P,w,E,T,O,I,R,A,C,_,D;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s=r.pc,c=r.idToTransceiverMap,u=r.remoteSDP,d=r.idToTransceiversMap,l=u.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(h=null===(v=n.audio)||void 0===v?void 0:v[0],m=h.from,X.audioSFU){if(d.get(m)){y=on(d.get(m));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=on(b);try{for(S.s();!(k=S.n()).done;)k.value.direction="sendonly"}catch(e){S.e(e)}finally{S.f()}}else r.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return r.pc.addTransceiver("audio",{direction:"recvonly"})})),d.set(m,r.mcuAudioTranceivers);i[m].addTransceivers(d.get(m))}else c.get(m)||c.set(m,r.mcuAudioTranceiver),c.get(m).direction="recvonly",p.direction="sendonly",i[m].addTransceiver(c.get(m));P=on(n.video),e.prev=6,E=x.mark((function e(){var r,n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=w.value,n=r.from,o=c.get(n)){e.next=7;break}c.set(n,s.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===o.direction){e.next=18;break}return o.direction="inactive",e.next=11,s.createOffer();case 11:return a=e.sent,e.next=14,s.setLocalDescription(a);case 14:return u.media.find((function(e){return e.mid==o.mid})).direction="inactive",e.next=18,s.setRemoteDescription({type:"answer",sdp:t.write(u)});case 18:c.get(n).direction="recvonly";case 19:i[n].addTransceiver(c.get(n));case 20:case"end":return e.stop()}}),e)})),P.s();case 9:if((w=P.n()).done){e.next=13;break}return e.delegateYield(E(),"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 T=e.sent,O=t.parse(T.sdp),u.groups[0].mids=O.groups[0].mids,e.next=28,s.setLocalDescription(T);case 28:r.localSDP=O,X.audioSFU&&n.audio[0]&&(I=n.audio[0],R=I.ssrcGroup,A=I.from,d.get(A).forEach((function(e,t){var r,n=null===(r=R[t])||void 0===r?void 0:r.ssrc,i=u.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=nn(nn({},p),{},{mid:e.mid}),u.media.push(i)),i.ssrcs=Pn(n,f),i.direction="sendonly"}))),C=on(n.video),e.prev=31,D=x.mark((function e(){var t,r,n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_.value,r=t.from,n=t.subSsrcGroup,o=c.get(r),(a=u.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})))||((a=nn({},l)).mid=o.mid,u.media.push(a)),a.direction="sendonly",i[r].ssrc=null==n?void 0:n.ssrc,gn(n,a,f);case 8:case"end":return e.stop()}}),e)})),C.s();case 34:if((_=C.n()).done){e.next=38;break}return e.delegateYield(D(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),C.e(e.t3);case 43:return e.prev=43,C.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)}}(),kn=function(){var e=i(x.mark((function e(r,n){var i,o,a,s,c,u,d,l,p,f,v,h;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=r.pc,o=r.remoteSDP,a=[],s=on(n);try{for(s.s();!(c=s.n()).done;)u=c.value,d=u.transceiver,l=u.transceivers,d?a.push(d):l&&a.push.apply(a,W(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=h[v],o.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),v=0,h=a;case 13:if(!(v<h.length)){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)}}(),Pn=function(t,r){return[{attribute:"msid",value:"".concat(r," v").concat(t),id:t},{attribute:"cname",value:e.createUuid(),id:t}]},wn=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]=nn(nn({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=nn(nn({},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()&&X.simulcast&&(u.ext=u.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!u.ssrcs&&"downlink"===a){var d=fn(),l=c.msidSemantic.token;u.ssrcs=Pn(d,l)}return n.remoteSDP=c,c},En=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),d=W(n.sessions.values());if("downlink"===c){var l=r.media.slice(2),p=d.filter((function(e){return e instanceof zr})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!X.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var v=[];u.forEach((function(e){var t={direction:e.direction},r=l.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&v.push(i))})),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var h=d.filter((function(e){return e instanceof xn}));u.forEach((function(e){var t={direction:e.direction},r=h.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof Rt){var s=bt(n).encodings;t.sendEncodings=s.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}},Tn=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=on(n);try{for(u.s();!(r=u.n()).done;){var d=r.value,l=d.config,p=d.payload,f=l.split(";");c[p]={};var v,h=on(f);try{for(h.s();!(v=h.n()).done;){var m=tt(v.value.split("="),2),y=m[0],g=m[1];c[p][y]=g}}catch(e){h.e(e)}finally{h.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var k=n.length-1;k>=0;k--){var P=n[k].payload;s.includes(P)&&n.splice(k,1)}for(var w=o.length-1;w>=0;w--)s.includes(o[w].payload)&&o.splice(w,1);for(var E=a.length-1;E>=0;E--)s.includes(a[E].payload)&&a.splice(E,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},On=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return Tn(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},In=function(e){var t=e.media.find((function(e){return"video"===e.type}));return Tn(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function Rn(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 An(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Rn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Rn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Cn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return _n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?_n(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function _n(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Dn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Dn=function(){return!!e})()}var Mn=e.getReporter().log,xn=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Dn()?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),r.applyOptions=r.applyOptions.bind(r),r.applyOptions=Oe(r.applyOptions,1e3,!1),p.forEach((function(e){e.on(B,r.handleTracEvent)})),r.encodings=bt(p[0]).encodings,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():Nn([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:"handleRepublish",value:function(e){var t=this.connection,r=this.transceiver,n=e.getMediaStreamTrack().getSettings(),o=n.width,a=n.height,s=gt(o,a);this.signaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:s});var c=function(e,t){var r=vt(e,t),n=function(n){var i=tt(ht(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(Ke.LD),sd:n(Ke.SD),fhd:n(r)}}(o,a);t.addTask(i(x.mark((function e(){var t;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Mn.info("scales",c),(t=r.sender.getParameters()).encodings.forEach((function(e){e.scaleResolutionDownBy=c[e.rid]})),Mn.info("handleRepublish setParameters",t),e.abrupt("return",r.sender.setParameters(t).then((function(){console.log(r.sender.getParameters().encodings)})));case 5:case"end":return e.stop()}}),e)}))))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){X.republish?n.handleRepublish(t):n.stop().then((function(){n.connection.sessionManager.channel.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==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(this.reporter.log.debug(e),!(n<this.feedbackIndex||this.state!==A.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask((function(){return new Promise((function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map((function(e){return e.rid})),d=Cn(c.encodings);try{for(d.s();!(n=d.n()).done;){var l,p=n.value,f=Cn(e);try{for(f.s();!(l=f.n()).done;){l.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){d.e(e)}finally{d.f()}if(Mn.info("encodings",c.encodings),s)return Mn.info("applyOptions setParameters",c),o.sender.setParameters(c).then((function(){return hn(t).then(r)}));r()}))}))}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof Rt&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask((function(){var e=n.sender.getParameters();return e.degradationPreference=cn[o]||"balanced",Mn.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),hn(t)}))}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=A.Processing,this.feedbackIndex=-1,this.monitor=new Nr(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=ke(r,o),s=we(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===l?[]:l,f=(null===(d=this.metricsMap.get(t))||void 0===d?void 0:d.videoMetrics)||{},v=ke(n,f),h=we(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*h/v};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(An({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(An({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(An({sessionId:e.id},t))}))}}])}(),jn=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,mn(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Rt){var c;i.video=i.video||[];var u=o.ssrcGroups,d=void 0===u?[]:u,l=bt(e),p=l.encodings,f=l.resolutionLevel;p.length>1&&(d=p.map((function(){return{semantics:"FID",ssrcs:"".concat(fn()," ").concat(fn())}})));var v=d.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),h=p[p.length-1],m={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:v,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==v||null===(c=v[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(h.maxBitrate),resolution:{width:h.targetWidth,height:h.targetHeight},framerate:h.maxFramerate},ssrcParameters:v.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}}))};i.video.push(m)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Ln=function(e){var t,r=e.tracks,n=e.connection,o=e.labels,a=r.map((function(t){return{publication:new xn(An(An({},e),{},{tracks:[t]})),track:t}})),s=new Promise((function(e,s){t=function(){var t=i(x.mark((function t(){var c,u;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,jn(r,n,o);case 2:return c=t.sent,u={connectionId:n.id,media:c,simulcast:X.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.signaling.batchPublish(u).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=re(e.track,i)})),t.abrupt("return",e(a));case 4:o=Cn(n),t.prev=5,c=x.mark((function e(){var t,r,n,i,o,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,o=a.findIndex((function(e){return e.track.getTrackId()===n.id})),c=a[o]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(a[o].error=re(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){Mn.info("batchPublishStart error",e),s(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),s},Nn=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,yn(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(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 Vn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Vn=function(){return!!e})()}var Fn={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},Un=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Vn()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},Fn)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return f(t,Ar),u(t,[{key:"extractMetrics",value:function(t){var r=Object.assign({},this.connectionMetrics),n="";return t.forEach((function(t){var i;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===n)e.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/",""),r.sdpFmtpLine=t.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},r),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var 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 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 n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Bn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function qn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(qn=function(){return!!e})()}var Hn={uplink:"",downlink:""},Jn=function(){function r(t){var n,a,s,c,u;o(this,r),a=this,s=l(s=r),n=d(a,qn()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),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,"subSdpFmtpLines",{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,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(u=i(x.mark((function e(){var t,r=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]&&r[0],"uplink"===n.direction?(n.pc.addTransceiver("audio",{direction:"sendonly"}),n.pc.addTransceiver("video",{direction:"sendonly"})):(n.mcuAudioStream=null,n.mcuAudioTranceiver=n.pc.addTransceiver("audio",{direction:"recvonly"}),n.pc.addTransceiver("video",{direction:"recvonly"})),t&&En(n),e.next=5,n.exchangeSDP(t);case 5:n.state=C.Idle,n.enquenTask.start();case 7:case"end":return e.stop()}}),e)}))),function(){return u.apply(this,arguments)})}),Object.defineProperty(n,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;n.reporter.log.info("connectionId:".concat(n.id," ice gathering state: ").concat(t))}}),n.pc=null;var p=t.direction,f=t.sessionManager;return n.signaling=f.channel.signaling,n.sessionManager=f,n.reporter=f.reporter,n.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}}(),n.subSdpFmtpLines=[],n.direction=p,n.idToTransceiverMap=new Map,n.idToTransceiversMap=new Map,n.createPeerConnection(),n.id="".concat(n.direction,"_").concat(e.createUuid()),n}return f(r,e.EventEmitter),u(r,[{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.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?X.audioSFU?this.emit("track",t,r[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.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"clearPcForReoffer",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.info("connectionId:".concat(this.id,": start client reoffer")),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.info("connectionId:".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),this.reporter.log.info("connectionId:".concat(this.id," connection state changed to ").concat(r)),"failed"===r||"closed"===r?(this.clientFailoverTimer&&e.removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=e.addTimer((function(){t.state!==C.New&&(t.reporter.log.info("connectionId:".concat(t.id,": emit reoffer")),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=Gn(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"===Hn[this.direction]&&(Hn[this.direction]="all",a.iceTransportPolicy="all"),a.iceServers=[{urls:c,username:r,credential:n}]}return Hn[this.direction]=a.iceTransportPolicy,this.reporter.log.info("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var t=this;this.pc?this.reporter.log.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=e.addTimer((function(){var e;"connected"===(null===(e=t.pc)||void 0===e?void 0:e.connectionState)||t.exchangeSdpTask||(t.reporter.log.info("connectionId:".concat(t.id,": emit reoffer")),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 Un(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]=nn(nn({},s[c]),{},{ssrcGroups:n,ssrcs:o}))})),a))),n.pc.setLocalDescription(r).catch((function(e){throw n.reporter.log.error("connectionId:".concat(n.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){n.reporter.log.info("connectionId:".concat(n.id," set local sdp success"));var c=function(r,n){var i=n.direction,o=["uplink"===i,X.downlinkForbidHighProfile],a=t.parse(r);if(o.some((function(e){return e}))&&(a=On(a,"64")),X.disableTransportCC&&"uplink"===i&&function(e){e.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!e.uri.includes("transport-wide-cc")})),e.rtcpFb=e.rtcpFb.filter((function(e){return"transport-cc"!==e.type}))}))}(a),"downlink"===i&&!X.downlinkForbidHighProfile){var s=[];a.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&s.push(t)})),n.subSdpFmtpLines=s}if(e.Environment.isFirefox()&&(a=In(a)),"uplink"===i&&e.Environment.isFirefox()&&X.simulcast){var c=a.media.find((function(e){return"video"===e.type}));bn(c)}return n.localSDP=a,a}(r.sdp,n);r.sdp=t.write(c),n.offerSDP=c,r.sdp=t.write(c);var u,d={direction:"downlink"!==n.direction?"in":"out",sdpOffer:r.sdp,connectionId:n.id,isFailover:o,optionsJsonStr:JSON.stringify({supportCVO:1})};if(o){var l=t.parse(r.sdp);l.media=l.media.slice(0,2),l.groups=[{mids:"0 1",type:"BUNDLE"}],d.sdpOffer=t.write(l)}!function(e){var t=e.fn,r=e.times,n=e.interval,o=void 0===n?0:n,a=e.resolve,s=e.reject;if(!(r>0))throw new Error("invalid params times");var c=function(){var e=i(x.mark((function e(){var n,i;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=0;case 1:if(!(i<r)){e.next=22;break}return e.prev=2,e.next=5,t();case 5:return n=e.sent,null==a||a(n),e.abrupt("break",22);case 10:if(e.prev=10,e.t0=e.catch(2),i!==r-1){e.next=17;break}return null==s||s(e.t0),e.abrupt("return",e.t0);case 17:return e.next=19,Ee(o);case 19:i++,e.next=1;break;case 22:return e.abrupt("return",n);case 23:case"end":return e.stop()}}),e,null,[[2,10]])})));return function(){return e.apply(this,arguments)}}();c()}({key:"createPeerConnection_".concat(n.direction),fn:(u=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(d.isFailover||!n.prevId){r.next=7;break}return r.next=5,n.stopSinglePC(!0);case 5:n.id="".concat(n.direction,"_").concat(e.createUuid()),d.connectionId=n.id;case 7:return n.prevId=n.id,r.abrupt("return",n.signaling.createPeerConnection(d).then((function(r){var i=r.sdpAnswer,a=wn(i,n,o,Hn[n.direction]);n.pc.setRemoteDescription({sdp:t.write(a),type:"answer"}).then((function(){var e;n.reporter.log.info("connectionId:".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("connectionId:".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 u.apply(this,arguments)}),times:3,interval:2e3,reject:s,resolve:a})})).catch((function(t){var r,i;n.reporter.log.error("connectionId:".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(){return this.state===C.New?Promise.reject():(this.reporter.log.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=C.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){X.downlinkForbidHighProfile=!0,this.reporter.log.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.reporter.log.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var n}();function Yn(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 Qn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Yn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Yn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Wn(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 Kn(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)?Kn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Kn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function zn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(zn=function(){return!!e})()}var $n=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,zn()?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:(k=i(x.mark((function e(t){var r=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=10;break}if(this.uplink){e.next=7;break}return this.uplink=new Jn({direction:t,sessionManager:this}),e.next=5,this.uplink.startSinglePC();case 5:this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){r.uplink=null}));case 7:return e.abrupt("return",this.uplink);case 10:if(this.downlink){e.next=16;break}return this.downlink=new Jn({direction:t,sessionManager:this}),e.next=14,this.downlink.startSinglePC();case 14:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){r.downlink=null}));case 16:return e.abrupt("return",this.downlink);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return k.apply(this,arguments)})},{key:"handleRepulish",value:(S=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:if("disconnected"!==this.channel.internalChannel.connectionState){t.next=2;break}return t.abrupt("return");case 2:n=W(this.client.localTracks),i=Wn(this.sessions.values());try{for(i.s();!(o=i.n()).done;)(a=o.value)instanceof xn&&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=7,this.reporter.trace.connectionsEvent(s,"clientReofferStart"),t.next=11,null===(c=this.uplink)||void 0===c?void 0:c.clearPcForReoffer();case 11: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=17;break}return t.next=16,this.batchPublish(n);case 16:this.reporter.log.info("".concat(this.client.userId," batchPublish finished for republish"));case 17:this.reporter.trace.connectionsEvent(s,"clientReofferSuccess"),this.reporter.log.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),t.next=28;break;case 22:t.prev=22,t.t0=t.catch(7),this.reporter.log.error("".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 28:case"end":return t.stop()}}),t,this,[[7,22]])}))),function(){return S.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(b=i(x.mark((function t(r){var n,i,o,a,s,c,u,d,l,p,f;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){t.next=2;break}return t.abrupt("return");case 2:n=[],i=Wn(r);try{for(i.s();!(o=i.n()).done;)(a=o.value)instanceof zr&&a.state===A.Processing&&(n.push({stream:a.stream,uid:a.uid,resolutionInfo:a.userConfigResolution,session:a,profileFallback:!0}),this.removeSession(a.id))}catch(e){i.e(e)}finally{i.f()}return s=n.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",s),this.reporter.log.info("resubscribe ".concat(s," start")),t.prev=8,t.next=11,this.batchUnscribe(n);case 11:return t.next=13,this.batchSubscribe(n);case 13:c=t.sent,u=Wn(c);try{for(u.s();!(d=u.n()).done;)l=d.value,p=l.subscription,f=l.error,p&&!f&&this.handleSubscribeReoffer(p)}catch(e){u.e(e)}finally{u.f()}this.client.emit("media-reconnect-end",s),t.next=24;break;case 19:t.prev=19,t.t0=t.catch(8),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t.t0))),this.client.emit("media-reconnect-end",s),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 24:case"end":return t.stop()}}),t,this,[[8,19]])}))),function(e){return b.apply(this,arguments)})},{key:"handleResubscribe",value:(g=i(x.mark((function t(){var r,n,i,o,a,s,c,u,d,l,p,f,v,h,m,y,g=arguments;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=g.length>0&&void 0!==g[0]&&g[0],"disconnected"!==this.channel.internalChannel.connectionState){t.next=3;break}return t.abrupt("return");case 3:i=n?"server":"client",o=[],a=Wn(this.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof zr&&c.state===A.Processing&&(o.push({stream:c.stream,uid:c.uid}),this.removeSession(c.id))}catch(e){a.e(e)}finally{a.f()}return u=o.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=11,this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferStart")),t.next=15,null===(l=this.downlink)||void 0===l?void 0:l.clearPcForReoffer();case 15:if(this.downlink=null,!o.length){t.next=22;break}return t.next=19,this.batchSubscribe(o);case 19:p=t.sent,f=Wn(p);try{for(f.s();!(v=f.n()).done;)h=v.value,m=h.subscription,y=h.error,m&&!y&&this.handleSubscribeReoffer(m)}catch(e){f.e(e)}finally{f.f()}case 22:this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferSuccess")),this.reporter.log.debug("".concat(this.client.userId," resubscribe ").concat(u," success")),this.client.emit("media-reconnect-end",u),t.next=33;break;case 27:t.prev=27,t.t0=t.catch(11),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t.t0))),this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferFailed")),this.client.emit("media-reconnect-end",u),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 33:case"end":return t.stop()}}),t,this,[[11,27]])}))),function(){return g.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(X.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=Wn(void 0===i?[]:i);try{var a=function(){var t,i,o=n.value,a=o.actionName,s=o.connectionId;if("reoffer"!==a)return 1;if(s===(null===(t=r.uplink)||void 0===t?void 0:t.id)){var c=r.uplink,u=r.client,d=u.userId,l=u.localTracks;r.client.emit("media-reconnect-start",d),r.reporter.trace.connectionsEvent(s,"serverReofferStart"),c.reoffer().then((function(){r.reporter.log.info("".concat(d," republish ").concat(l.map((function(e){return e.trackMediaType})).join()," success")),r.reporter.trace.connectionsEvent(s,"serverReofferSuccess"),r.client.emit("media-reconnect-end",d)})).catch((function(t){r.reporter.log.debug("".concat(r.client.userId," republish failed for ").concat(e.tryJsonStringify(t))),r.reporter.trace.connectionsEvent(s,"serverReofferFailed"),r.channel.signaling.emit("connection-state-change","disconnected",r.client.connectionState,"network_error")}))}else s===(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:e>=0||t>=0?T.GREAT:T.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(y=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=W(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=tt(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,d=0,l=0,p=0;if(n){var f=n.camera,v=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,l=Math.max(l,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,l=Math.max(l,v.rtt||0))}for(var h in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,l=Math.max(l,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,d+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[h],y=m.camera,g=m.auxiliary;y&&(u+=y.receivePacketsLost,d+=y.receivePackets,p=Math.max(p,y.rtt||0)),g&&(u+=g.receivePacketsLost,d+=g.receivePackets,p=Math.max(p,g.rtt||0))}var b=-1,S=-1,k={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:d};if(s){var P,w,E=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(E<0&&(E=c),k.totalUplinkPacketsSentForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalUplinkPacketsSentForLost)||0,0!==E){var T;k.totalUplinkPacketsSentForLost=s;var O=s-((null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0);O<0&&(O=s),b=E/O}}if(d){var I,R,A,C,_=u-((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0);_<0&&(_=u),k.totalDownlinkPacketsRecvForLost=(null===(R=r.lastChannelNetworkQuality)||void 0===R?void 0:R.totalDownlinkPacketsRecvForLost)||0,null===(A=r.lastChannelNetworkQuality)||void 0===A||A.totalDownlinkPacketsRecvForLost,_&&(u!==((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalDownlinkPacketsLost)||0)&&(k.totalDownlinkPacketsRecvForLost=d),S=_/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 y.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:(m=i(x.mark((function e(t,r){var n,i,o=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return i=e.sent,e.abrupt("return",Ln({uid:this.client.userId,tracks:t,connection:i,labels:r}).then((function(e){var t,r=Wn(e);try{var i=function(){var e=t.value,r=e.error,i=e.publication,a=e.track;r?o.reporter.trace.publish(!1,a,"",Date.now()-n):(o.addSession(a.getTrackId(),i),o.reporter.trace.publish(!0,a,i.id,Date.now()-n),o.reporter.trace.publish(!1,a,i.id,Date.now()-n),i.on("ended",(function(){o.removeSession(i.id)})))};for(r.s();!(t=r.n()).done;)i()}catch(e){r.e(e)}finally{r.f()}})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return m.apply(this,arguments)})},{key:"batchUnPublish",value:(h=i(x.mark((function e(t){var r,n=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return",Promise.resolve());case 2:return e.next=4,this.getOrCreatePeerConnection("uplink");case 4:return r=e.sent,e.abrupt("return",Nn(t,{connection:r}).then((function(){var e,r=Wn(t);try{for(r.s();!(e=r.n()).done;){var i,o,a,s=e.value;n.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)),n.removeSession(s.id)}}catch(e){r.e(e)}finally{r.f()}})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,o=function(){var e=i(x.mark((function e(r){var a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getOrCreatePeerConnection("downlink");case 2:return a=e.sent,e.abrupt("return",en(r,{connection:a}).then(function(){var e=i(x.mark((function e(i){var a,s,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<i.length;c++)"RoomBusy"===(null===(u=i[c].error)||void 0===u?void 0:u.message)&&(s.push(r[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){e.next=12;break}return n++,e.next=7,Te(1);case 7:if("connected"!==t.client.connectionState){e.next=12;break}return e.next=10,o(s);case 10:e.sent.forEach((function(e,t){var r=a.get(t);i[r]=e}));case 12:return e.abrupt("return",i);case 13:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();return o(e).then((function(e){var n,i=Wn(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.log.error("batchSubscribe error",s,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:(v=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:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.reporter.log.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))})),e.next=6,this.getOrCreatePeerConnection("downlink");case 6:return o=e.sent,e.abrupt("return",tn(n,{connection:o}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r})));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return v.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:(p=i(x.mark((function e(){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return this.uplink=e.sent,e.next=6,this.getOrCreatePeerConnection("downlink");case 6:this.downlink=e.sent,this.channel.signaling.on("media-message",this.handleMediaMessage),this.channel.signaling.on("serverFailover",this.handleServerFailover);case 9:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{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=W(this.sessions.values()).filter((function(e){var t,r;return e instanceof xn&&"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,h=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=h.length>0&&void 0!==h[0]?h[0]:"network",i=W(this.sessions.values()).filter((function(e){var t;return e instanceof xn&&"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:W(new Set(o(a))),downlinkProfile:W(new Set(o(s)))},u=Wn(i),e.prev=9,u.s();case 11:if((d=u.n()).done){e.next=21;break}if(l=d.value,p=l.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=l.tracks,v=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return 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,f=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=W(this.sessions.values()).filter((function(e){var t;return e instanceof zr&&"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=Wn(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,d=s.stream,l=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=d.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=Qn(Qn({},n[u]||{}),{},j({},p,l));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return 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=W(this.sessions.values()).filter((function(e){var t;return e instanceof zr&&"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=W(this.sessions.values()).filter((function(e){return e instanceof xn&&e.state===A.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA})),i=Wn(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,h,m,y,g,b,S,k}();function Xn(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 Zn(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)?Zn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Zn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ei(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ei=function(){return!!e})()}var ti={name:"name"},ri=function(){function t(e){var r,n,i,a;return 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,"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.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.channel.userManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.channel.signaling.on("group-list",this.handleGroupListEvents),this.channel.signaling.on("group",this.handleGroupEvents),this.channel.signaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.channel.signaling.off("group",this.handleGroupEvents),this.channel.signaling.off("group-list",this.handleGroupListEvents),this.channel.signaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(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:Gt.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!==Gt.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===Gt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===Gt.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!==Gt.OptType.OPT_TYPE_ADD||u){if(s===Gt.OptType.OPT_TYPE_REMOVE&&u){var d,l=null==u||null===(d=u.audioInfo)||void 0===d||null===(d=d.audio)||void 0===d?void 0:d.id;this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),l)}else if(s===Gt.OptType.OPT_TYPE_UPDATE){var p=c.updateAction,f=c.participants;if(u&&(u.ver+1===o||r)){if(p===Gt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var v,h=u.participants.map((function(e){return e.pid})),m=Xn(f);try{for(m.s();!(v=m.n()).done;){var y=v.value;h.includes(y.pid)||(u.participants.push(y),this.emit("group","user-join",i,{userId:y.uid,userData:y.userData}))}}catch(e){m.e(e)}finally{m.f()}}else if(p===Gt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=f.map((function(e){return e.pid})),b=W(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),b.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(p===Gt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.channel.reporter.log.debug("group ".concat(i," audioStream lost"));else if(p===Gt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.channel.reporter.log.debug("group ".concat(i," audioStream recover"));else if(p===Gt.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(ti[e.key]),value:e.value})}));else if(p===Gt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var S,k=c.properties.map((function(e){return e.key}));u.properties=null===(S=u.properties)||void 0===S?void 0:S.filter((function(e){var t=e.key;return!k.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(ti[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:Gt.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],d=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),l=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==d[e.key]})),v=c.filter((function(e){return!d.has(e.key)})),h=a.filter((function(e){return!l.includes(e.pid)})),m=u.filter((function(e){return!p.includes(e.pid)}));h.length&&t.handleGroupEvents({id:e,type:Gt.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:Gt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:h}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:Gt.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:Gt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:Gt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:Gt.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:Gt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:Gt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:Gt.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.channel.signaling.syncDataByIds({type:Gt.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:Gt.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=W(e.groupIds).filter((function(e){return!o.includes(e)}));a.length&&a.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:Gt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:Gt.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}();function ni(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ni=function(){return!!e})()}var ii=function(){function t(e,r){var n,i,a,s;o(this,t),i=this,a=l(a=t),n=d(i,ni()?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});var c=e.user;return n.userId=c,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 W(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]=Pe(n[D.UPLINK]),n[D.DOWNLINK]=Pe(n[D.DOWNLINK]),t=n.join("")}t!==(null===(r=this.properties)||void 0===r?void 0:r[G])&&(this.properties[G]=t)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[G])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=ne(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 oi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ai(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ai(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ai(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function si(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(si=function(){return!!e})()}var ci=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,si()?Reflect.construct(a,[],l(i).constructor):a.apply(i,s)),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentPid",{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,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.channel=e,n.reporter=e.reporter,n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){var t=this;return e.uniqBy(W(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=oi(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new ii(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,r){var n=this;if(this.reporter.log.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new ii(t,this.channel);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map((function(e){return e.id})));W(this.streamManager.streams.values()).filter((function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)})).map((function(e){return e.id})).forEach((function(e){return n.streamManager.remove(e,!0)}));var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new ii(t,this.channel);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.channel.signaling.setParticipantProperties({participantId:this.currentPid,roomId:this.channel.roomId,propertiesJsonStr:JSON.stringify(j({},G,e))})}}])}();function ui(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 di(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)?di(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function di(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function li(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function pi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?li(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):li(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function fi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(fi=function(){return!!e})()}var vi=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,fi()?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.signaling,c=e.reporter;return r.signaling=s,r.reporter=c,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=W(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 W(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","highestResolutionLevel"]}[o];u.length&&!u.includes(s.field)||this.reporter.log.info("streamEvent ".concat(JSON.stringify(t)));var d=this.totalVer;if(c===d+1||c==F||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,h=s.streamVer,m=s.propertiesJsonStr,y=s.highestResolutionLevel,g=this.streams.get(i);if(g){h!==F&&(g.version=h);var b=g.media,S=b.audio,k=b.video,P=g.info.owner;if("audio.status"===l||"video.status"===l){var w;"audio.status"===l?(w="audio",S.status=p):"video.status"===l&&(w="video",k.status=p),this.reporter.trace.streamsEvent(i,"".concat(w," ").concat(p));var E="active"===p?"unmute":"mute";this.emit("stream","update",{owner:P,id:i,updateStatus:"".concat(E,"-").concat(w)})}else if("activeInput"===l){var T=[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(T),l),this.emit("stream","volumeActive",{owners:T})}else if("properties"==l){var O,I=JSON.parse(m);g.info.attributesJsonStr=JSON.stringify(pi(pi({},JSON.parse(g.info.attributesJsonStr)),I));var R=(null===(O=g.media)||void 0===O||null===(O=O.video)||void 0===O?void 0:O.source)===e.VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:P,id:i,properties:I,auxiliary:R})}else"highestResolutionLevel"===l&&(g.media.video.highestResolutionLevel=y,this.emit("stream","update",{owner:P,id:i,highestResolutionLevel:y}))}}r||c<=this.totalVer&&c!==F||(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=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:n=e.sent,i=n.streamVersions,o=n.totalVer,a=W(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=ui(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,d=u.streamId,l=u.streamVer,!d.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(d))?p&&p.version!==l&&t.push(d):(r.push(d),t.push(d));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),a.filter((function(e){return!f.includes(e)})).forEach((function(e){v.handleEvent({status:"remove",streamId:e,stream:v.streams.get(e),totalVer:o},!0)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=34;break}return e.abrupt("return");case 34:this.signaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=ui(v.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=ui(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;v.streams.has(l.id)?v.streams.set(l.id,l.stream):a.set(l.id,l.stream)}}catch(e){d.e(e)}finally{d.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var h=p[f];r.includes(h.id)&&v.handleEvent({status:"add",streamId:h.id,stream:h,totalVer:i},!0)}a.clear(),v.totalVer=i}));case 35:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}();function hi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return mi(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)?mi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function mi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function yi(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 gi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?yi(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):yi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function bi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(bi=function(){return!!e})()}var Si=function(){function t(n,i){var a,s,c,u;return o(this,t),s=this,c=l(c=t),a=d(s,bi()?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?st(a.defaultVideoStreamType,ee(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.streams,o=t.streamsVer,s=t.groupList,c=t.groupListVer;a.streamManager.init(i,o),a.groupManager.init(s,c),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,sdkVersion:V}),a.signaling=new Ir(a.internalChannel),a.client=n,a.micMixedGroups=new Set,a.groupManager=new ri(a),a.streamManager=new vi(a),a.userManager=new ci(a,a.streamManager),a.sessionManager=new $n(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 W(this.sessionManager.sessions.values()).filter((function(e){return e.state===A.Processing&&e instanceof xn})).map((function(e){return e.tracks[0]}))}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map((function(t){return gi(gi({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})}))}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=t.highestResolutionLevel,d=this.internalChannel.userManager.participants,l=d.get(n),p=this.userManager.users.get(null==l?void 0:l.user),f=n===this.userManager.currentPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,i,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stop(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stop(),p.videoTrack=null)),this.client.emit("user-unpublished",p,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.userManager.currentUid,s);else if(null!=(null==c?void 0:c.mirror)){var v=o?p.auxiliaryTrack:p.videoTrack;null==v||v.setSourceMirror(c.mirror)}else if(null!=u){var h=this.sessionManager.getSessionByStreamId(r);if(!h)return;h.stream.media.video.highestResolutionLevel=u;var m=h.userConfigResolution,y=h.resolutionInfo;if(u>=m.resolutionLevel&&m.resolutionLevel>y.resolutionLevel)h.applyOptions(m,!0);else if(u<m.resolutionLevel){var g=st(ct(u),ee(h.stream));h.applyOptions(g,!0)}}}else if("volumeActive"===e){var b=a.map((function(e){return d.get(e)})).map((function(e){return null==e?void 0:e.user})).filter((function(e){return!!e}));this.client.emit("volume-indicator",b)}}},{key:"handleGroupEvent",value:function(e,t,r){if("add"===e)this.client.emit("group-add",t);else if("remove"===e)this.micMixedGroups.delete(t.id),r===this.subscribedAudioStream&&(this.remoteAudioTrack.stop(),this.remoteAudioTrack=null,this.updateSubscribedAudioStream(!1,r)),this.client.emit("group-remove",t);else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var n=r.key,i=r.value;this.client.emit("group-info-updated",t,n,i)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e&&this.client.emit("user-left",t)}},{key:"getStream",value:function(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?W(this.streamManager.streams.values()):null===(r=this.userManager.users.get(i))||void 0===r?void 0:r.relatedStreams;return"mcu"===i?c.find((function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r})):c.find((function(t){var r=t.media.video;return(null==r?void 0:r.source)===(o?e.VideoSourceInfo.SCREENCAST:e.VideoSourceInfo.CAMERA)}))}},{key:"join",value:(p=i(x.mark((function e(t){var r,n,i,o,a,s;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("dingrtc channel join",t,X.gslb[0]),e.next=3,this.signaling.join(t,X.gslb[0]);case 3:return n=e.sent,i=n.joinResponse,o=n.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(X.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=i.room.id,c=i.room.ssrcMask,u=i.room.ssrcClientSequence,d=void 0,d=Math.log2(c+1),u>2147483647>>d||(dn=c,un=(u<<d|2147483648)>>>0),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:i.id}),o&&o.uis&&this.setIceConfig(o.uis),e.next=13,this.sessionManager.start();case 13:return this.handleJoinResponse(i),e.abrupt("return",i);case 15:case"end":return e.stop()}var c,u,d}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter((function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)})),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.userManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stop(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.userManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.signaling.leave()}},{key:"publish",value:(c=i(x.mark((function e(t){var r,n,i,o;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some((function(e){return e.joined}))?o.push.apply(o,W(W(r).map((function(e){var t;return null===(t=n.groups.get(e))||void 0===t||null===(t=t.audioInfo)||void 0===t?void 0:t.label})).filter((function(e){return!!e})))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"unpublish",value:function(e){var t=this,r=new Set(e.map((function(e){return e.getTrackId()}))),n=W(this.sessionManager.sessions.values()).filter((function(e){var t;return e instanceof xn&&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=ne(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",(function(){r.remoteAudioTrack.emit("first-frame-decoded")})),this.remoteAudioTrack}return n.getRemoteVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(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=e.auxiliary,a=e.uid,s=n[t],c=s.error,u=s.subscription;i.push({uid:a,auxiliary:o,error:c,track:r.getRemoteTrack(e,u)})})),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){var t,r=this,n=[],i=hi(e);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.handleSubscribeParam(gi(gi({},o),{},{action:"unsubscribe"})),s=a.session,c=a.stream,u=a.user,d=a.uid;this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:d}),c&&n.push(gi({stream:c,user:u,session:s},o))}}catch(e){i.e(e)}finally{i.f()}return n.length?this.sessionManager.batchUnscribe(n).then((function(e){for(var t=0,i=n;t<i.length;t++){var o,a=i[t],s=a.mediaType,c=a.user,u=a.auxiliary;if("audio"===s)r.updateSubscribedAudioStream(!1,""),null===(o=r.remoteAudioTrack)||void 0===o||o.stop(),r.remoteAudioTrack=null;else if(u){var d;null===(d=c.auxiliaryTrack)||void 0===d||d.stop(),c.auxiliaryTrack=null}else{var l;null===(l=c.videoTrack)||void 0===l||l.stop(),c.videoTrack=null}}return e})):Promise.resolve()}},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(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.updateSubscribedAudioStream(!0,n.id),r.remoteAudioTrack=ne(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.updateSubscribedAudioStream(!1,""),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=st(t,ee(n));return i.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then((function(e){var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)}))}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then((function(){t.micMixedGroups.delete(r)}))}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then((function(){t.micMixedGroups.delete(e)}))}},{key:"mixGroupAudio",value:function(e,t,r){return this.signaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(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=!(a.length>2&&void 0!==a[2])||a[2],i=[],null!=r&&i.push(this.groupManager.groups.get(r).audioInfo.label),!this.localTracks.includes(t)){e.next=18;break}if(o=this.streamManager.getStreamByTrackId(t.getTrackId()),null==r){e.next=14;break}return e.next=8,this.mixGroupAudio(o.id,i[0],"mix");case 8:if(this.micMixedGroups.add(r),!n){e.next=12;break}return e.next=12,this.mixGroupAudio(o.id,"common","unmix");case 12:e.next=16;break;case 14:return e.next=16,this.mixGroupAudio(o.id,"common","mix");case 16:e.next=22;break;case 18:return n||i.push("common"),e.next=21,this.sessionManager.batchPublish([t],i);case 21:this.micMixedGroups.add(r);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t){return 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}();function ki(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ki=function(){return!!e})()}var Pi={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},wi=function(){function e(t){var r,n,a,s,c;return o(this,e),n=this,a=l(a=e),r=d(n,ki()?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,o,a;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,n=t.audioLevel,e.next=6,r.client.getRemoteAudioStats();case 6:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:we(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 11:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},Pi),r.client=t,r}return f(e,Ar),u(e)}();function Ei(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ti(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ei(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ei(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Oi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Ii(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)?Ii(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Ii(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ri=function(){return!!e})()}var Ai=function(){function t(){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Ri()?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 Si(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.reporter.log.info("join",t),this.addEventListeners(),this.channel.join(t).then((function(n){var i;return r.channelName=t.channel,r.monitor=new wi(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 It&&!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=Oi(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){this.reporter.log.info("unpublish",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,i),"connected"===this.connectionState){t.next=3;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 3:return t.abrupt("return",this.channel.batchSubscribe([{uid:r,mediaType:n,action:"subscribe",auxiliary:i}]).then((function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n})));case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"batchSubscribe",value:function(t){if(this.reporter.log.info("batchSubscribe",t),Array.isArray(t)&&t.length){if("connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);return this.channel.batchSubscribe(t.map((function(e){return Ti(Ti({},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.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r,action:"unsubscribe"}]).then((function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(t){if(this.reporter.log.info("batchUnsubscribe",t),Array.isArray(t)&&t.length)return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel)):this.channel.batchUnsubscribe(t.map((function(e){return Ti(Ti({},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,r);var i=this.remoteUsers.find((function(t){return t.userId===e}));return null!=i&&i.relatedStreams?this.channel.setRemoteStreamType(e,t,r).then((function(){n.emit("stream-type-changed",e,t,r)})):(this.reporter.log.warn("".concat(e," videoTrack not existed")),Promise.reject("viedoTrack doesnt exiested"))}},{key:"getRemoteVideoStats",value:function(){return this.channel.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.channel.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach((function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[G])||void 0===r?void 0:r[D.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[G])||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||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var t=this,r=this.clientStatSync.join("");if(r!==this.currentClientState){var n=Pe(null,r[D.UPLINK]),i=Pe(null,this.currentClientState[D.UPLINK]),o=Pe(null,r[D.DOWNLINK]),a=Pe(null,this.currentClientState[D.DOWNLINK]);n===i&&o===a||this.channel.userManager.setParticipantProperties(r).catch((function(r){t.reporter.log.debug("setParticipantProperties error ".concat(e.tryJsonStringify(r)))})),this.currentClientState=r}}},{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){this.reporter.log.info("joinGroup",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.reporter.log.info("leaveGroup",e),this.channel.leaveGroup({groupId:e,publishAudioToChannel:!1})}},{key:"setGroupName",value:function(t,r){this.reporter.log.info("setGroupName",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.reporter.log.info("subscribeGroup",e),this.channel.subscribeGroup(e)}},{key:"unsubscribeGroup",value:function(e){return this.reporter.log.info("unsubscribeGroup",e),this.channel.unsubscribeGroup(e)}},{key:"mixAudioToGroup",value:function(t,r,n){if(this.reporter.log.info("mixAudioToGroup",t,r,n),"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.reporter.log.info("dismissGroup",e),this.channel.dismissGroup(e)}},{key:"register",value:function(e){this.reporter.log.info("register",e),e.attach(this.channel.internalChannel,this.channel)}},{key:"ungister",value:function(e){this.reporter.log.info("ungister",e),e.detach(this.channel.internalChannel)}}]);var r,n}(),Ci=function(){var e=i(x.mark((function e(t){var r;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:window.addEventListener("offline",(function(){t.info("browser offline event")})),window.addEventListener("online",(function(){t.info("browser online event")})),r=function(){"visible"===document.visibilityState?t.info("page changed to visible"):t.info("page changed to invisible")},document.addEventListener("visibilitychange",r),window.addEventListener("blur",(function(){t.info("page blurred")})),window.addEventListener("focus",(function(){t.info("page focused")}));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function _i(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(_i=function(){return!!e})()}Ne();var Di=e.getReporter().log;Di.info("sdk version",V),Di.info("userAgent",navigator.userAgent),Di.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),Ci(Di);var Mi=function(){function t(){var r,n,i,a;if(o(this,t),n=this,i=l(i=t),r=d(n,_i()?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,!H.checkSupported())return d(r);var s=le.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 Di.info("createClient"),new Ai}},{key:"checkSystemRequirements",value:function(){return Di.info("checkSystemRequirements"),H.checkSupported()}},{key:"getSupportedCodec",value:function(){return Di.info("getSupportedCodec"),H.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return Di.info("createCameraVideoTrack",e),Mt(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return Di.info("createMicrophoneAudioTrack",e),Dt(e)}},{key:"createCustomVideoTrack",value:function(e){return Di.info("createCustomVideoTrack",e),Lt(e)}},{key:"createCustomAudioTrack",value:function(e){return Di.info("createCustomAudioTrack",e),Nt(e)}},{key:"createScreenVideoTrack",value:function(e){return Di.info("createScreenVideoTrack",e),xt(e)}},{key:"createMicrophoneAndCameraTracks",value:(n=i(x.mark((function e(t,r){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Di.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",jt(t,r));case 2:case"end":return e.stop()}}),e)}))),function(e,t){return n.apply(this,arguments)})},{key:"getCameras",value:function(){return Di.info("getCameras"),le.getCameras()}},{key:"getDevices",value:(r=i(x.mark((function e(){var t;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return Di.info("start getDevices"),e.prev=1,e.next=4,le.getDevices();case 4:return t=e.sent,Di.info("getDevices suc",t),e.abrupt("return",t);case 9:return e.prev=9,e.t0=e.catch(1),Di.info("error getDevices ",e.t0),e.abrupt("return",e.t0);case 13:case"end":return e.stop()}}),e,null,[[1,9]])}))),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return Di.info("getPlaybackDevices"),le.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return Di.info("getMicrophones"),le.getMicrophones()}},{key:"setLogLevel",value:function(t){e.setLogLevel(t),Di.info("setLogLevel",t)}},{key:"setClientConfig",value:function(e){Di.info("setClientConfig",e),X.setClientConfig(e)}}]);var r,n}(),xi=new Mi;Object.defineProperty(exports,"ErrorCodeAndMsgMap",{enumerable:!0,get:function(){return e.ErrorCodeAndMsgMap}}),exports.FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},exports.default=xi;
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;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,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 h={exports:{}},m={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}(m);var y=m.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=t&&t.prototype instanceof S?t:S,o=Object.create(i.prototype),a=new M(n||[]);return s(o,"_invoke",{value:A(e,r,a)}),o}function v(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}i.wrap=f;var h="suspendedStart",m="suspendedYield",y="executing",g="completed",b={};function S(){}function k(){}function P(){}var w={};p(w,u,(function(){return this}));var E=Object.getPrototypeOf,T=E&&E(E(x([])));T&&T!==o&&a.call(T,u)&&(w=T);var O=P.prototype=S.prototype=Object.create(w);function I(e){["next","throw","return"].forEach((function(t){p(e,t,(function(e){return this._invoke(t,e)}))}))}function R(e,r){function n(i,o,s,c){var u=v(e[i],e,o);if("throw"!==u.type){var d=u.arg,l=d.value;return l&&"object"==t(l)&&a.call(l,"__await")?r.resolve(l.__await).then((function(e){n("next",e,s,c)}),(function(e){n("throw",e,s,c)})):r.resolve(l).then((function(e){d.value=e,s(d)}),(function(e){return n("throw",e,s,c)}))}c(u.arg)}var i;s(this,"_invoke",{value:function(e,t){function o(){return new r((function(r,i){n(e,t,r,i)}))}return i=i?i.then(o,o):o()}})}function A(e,t,r){var i=h;return function(o,a){if(i===y)throw Error("Generator is already running");if(i===g){if("throw"===o)throw a;return{value:n,done:!0}}for(r.method=o,r.arg=a;;){var s=r.delegate;if(s){var c=C(s,r);if(c){if(c===b)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(i===h)throw i=g,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i=y;var u=v(e,t,r);if("normal"===u.type){if(i=r.done?g:m,u.arg===b)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(i=g,r.method="throw",r.arg=u.arg)}}}function 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(o.tryLoc<=this.prev){var c=a.call(o,"catchLoc"),u=a.call(o,"finallyLoc");if(c&&u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!u)throw Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&a.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var i=n;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,b):this.complete(o)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),b},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),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}(h);var g=(0,h.exports)(),b=g;try{regeneratorRuntime=g}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=g:Function("r","regeneratorRuntime = r")(g)}var S,k,P,w,E,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 L(){return L="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(arguments.length<3?e:r):i.value}},L.apply(null,arguments)}!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,(w=exports.VideoSourceInfo||(exports.VideoSourceInfo={})).CAMERA="camera",w.SCREENCAST="screen-cast",w.MIXED="mixed",function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(E||(E={})),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 N,V="3.8.9",F={VD_120x120:[120,120],VD_160x120:[160,120],VD_180x180:[180,180],VD_240x180:[240,180],VD_320x180:[320,180],VD_240x240:[240,240],VD_320x240:[320,240],VD_424x240:[424,240],VD_360x360:[360,360],VD_480x360:[480,360],VD_640x360:[640,360],VD_480x480:[480,480],VD_640x480:[640,480],VD_840x480:[840,480],VD_960x540:[960,540],VD_960x720:[960,720],VD_1280x720:[1280,720],VD_1920x1080:[1920,1080],VD_2560x1440:[2560,1440]};exports.AudioSourceState=void 0,(N=exports.AudioSourceState||(exports.AudioSourceState={})).Playing="playing",N.Paused="paused",N.Stopped="stopped";var U=V,G=-999,B="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.Environment.browserType,e.Environment.browserVersion,e.Environment.system,e.Environment.systemVersion;var q="onertc_state_sync",H="onertc_internal_track_event",J=e.getReporter().log,Y=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),J.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 J.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}()),Q=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},n=r.setParameters,i=r.getParameters;return!(!n||!i)&&(!e.Environment.isFirefox()&&(e.Environment.isSafari()?parseInt(e.Environment.browserVersion)>=14:e.Environment.isChrome()?parseInt(e.Environment.browserVersion)>=81:!e.Environment.isAndroid()))};function W(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function K(e,t){if(e){if("string"==typeof e)return W(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)?W(e,t):void 0}}function z(e){return function(e){if(Array.isArray(e))return W(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.")}()}function $(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return($=function(){return!!e})()}var X=e.getReporter().log,Z=function(){function t(){var e,r,n,i;return o(this,t),r=this,n=l(n=t),e=d(r,$()?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:Q()}),Object.defineProperty(e,"audioSFU",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"republish",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(e,"disableTransportCC",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),e}return f(t,e.EventEmitter),u(t,[{key:"setClientConfig",value:function(t){X.info("setClientConfig",t);var r=t||{},n=r.gslb,i=r.simulcast,o=r.audioSFU,a=r.republish,s=r.disableTransportCC;"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&&Q()&&(this.simulcast=Boolean(i)),null!=o&&(this.audioSFU=Boolean(o)),null!=s&&(this.disableTransportCC=Boolean(s)),null!=a&&(this.republish=Boolean(a))}}])}(),ee=new Z,te=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},re=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(te),n},ne=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},ie=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},oe=function(e,t,r,n){var i=n,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?ee.audioSFU?n?n.replaceStream(e):i=new Qt(null,r,e):n?n.replaceTrack(a[0]):i=new Qt(a[0],r):"video"===t&&o.length&&(n?n.replaceTrack(o[0]):i=new Wt(o[0],r)),i},ae=function(e){return"object"===a(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function se(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ce(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?se(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):se(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function ue(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return de(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?de(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function de(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function le(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(le=function(){return!!e})()}var pe=e.getReporter().log,fe=function(){function t(){var e,r,n,a,s;return o(this,t),r=this,n=l(n=t),e=d(r,le()?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:n=r.sent,e.compareDevices(n,"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){var t=e.deviceId;return!s.includes(t)})),u=o.filter((function(e){var t=e.deviceId;return!a.includes(t)})),d={audioinput:"microphone-changed",audiooutput:"playback-device-changed",videoinput:"camera-changed"},l=ue(c);try{for(l.s();!(n=l.n()).done;){var p=n.value;e.emit(d[r],{device:p,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var f,v=ue(u);try{for(v.s();!(f=v.n()).done;){var h=f.value;e.emit(d[r],{device:h,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),t._instance?d(e,t._instance):(e.deviceList=[],Y.checkSupported()?(t.getDevices({audio:!0,video:!0},!0).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:"getMedias",value:function(e,t){var r,n,i=this;return ae(e)?(pe.info("getDisplayMedia with",t),null===(r=navigator.mediaDevices)||void 0===r?void 0:r.getDisplayMedia(t)):(pe.info("getUserMedia with",t),null===(n=navigator.mediaDevices)||void 0===n?void 0:n.getUserMedia(t).then((function(t){return e.audio&&(i.audioPermitted=!0),e.video&&(i.videoPermitted=!0),t})))}},{key:"getDevices",value:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(i,o){var a;if(null!==(a=navigator.mediaDevices)&&void 0!==a&&a.enumerateDevices){var s=!1;r.audio&&r.video?s=t.audioPermitted&&t.videoPermitted:r.audio?s=t.audioPermitted:r.video&&(s=t.videoPermitted),navigator.mediaDevices.enumerateDevices().then((function(e){var a=e.filter((function(e){return e.deviceId})),c=a.filter((function(e){return"videoinput"===e.kind})),u=a.filter((function(e){return"audioinput"===e.kind})),d=a.filter((function(e){return"audiooutput"===e.kind})),l=[];r.audio&&(l=l.concat(u,d)),r.video&&(l=l.concat(c)),0!==l.length||s||n?l.length?(r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),i(l)):i(l):(pe.info("getUserMedia with",r),navigator.mediaDevices.getUserMedia(r).then((function(e){r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),e.getTracks().forEach((function(e){e.stop()})),navigator.mediaDevices.enumerateDevices().then((function(e){i(e)}),o)}),o)),i(a)}))}else o(new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))}))}}])}();Object.defineProperty(fe,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(fe,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(fe,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new fe}),Object.defineProperty(fe,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return fe.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audiooutput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}}),Object.defineProperty(fe,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return fe.getDevices({video:!0}).then((function(e){return e.filter((function(e){return"videoinput"===e.kind})).map((function(e,t){var r={deviceId:e.deviceId,kind:e.kind,groupId:e.groupId,label:e.label||"camera ".concat(t)};return ce(ce({},r),{},{toJSON:function(){return r}})}))})).catch((function(t){throw e.parseVideoDeviceError(t)}))}}),Object.defineProperty(fe,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return fe.getDevices({audio:!0}).then((function(e){return e.filter((function(e){return"audioinput"===e.kind}))})).catch((function(t){throw e.parseAudioDeviceError(t)}))}});var ve,he,me=function(e){return{width:F[e][0],height:F[e][1]}},ye=function(t){var r,n=Object.create({}),i={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(i=navigator.mediaDevices.getSupportedConstraints(),console.log(i));var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.Environment.isSafari()?n.deviceId=t.deviceId:n.deviceId={exact:t.deviceId}),i.autoGainControl&&(n.autoGainControl={ideal:null==a||a}),i.echoCancellation&&(n.echoCancellation={ideal:null==o||o}),i.noiseSuppression&&(n.noiseSuppression={ideal:null==s||s}),n},ge=function(t){if(!e.isObject(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,n=t.video;if(!ae(t)&&"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(ae(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("object"===a(r)&&r.source===exports.AudioSourceInfo.MIC||"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST?i.audio=ye(r):i.audio=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=me(p)),o&&o.width&&o.height&&(u===exports.VideoSourceInfo.SCREENCAST||e.Environment.isFirefox()?(i.video.width=o.width,i.video.height=o.height):(i.video.width={ideal:o.width,max:o.width},i.video.height={ideal:o.height,max:o.height})),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 fe.getMedias(t,i)},be=void 0,Se=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},ke=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},Pe=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},we=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},Ee=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Te=function(){var e=i(x.mark((function e(t){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,new Promise((function(e){setTimeout(e,t)}));case 2:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),Oe=function(t){return new Promise((function(r){e.addTimer(r,1e3*t)}))},Ie=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50,r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],n=null,i=0;return function(){for(var o=arguments.length,a=new Array(o),s=0;s<o;s++)a[s]=arguments[s];var c=Date.now();c-i>=t&&r?(e.apply(be,a),i=c):(n&&clearTimeout(n),n=setTimeout((function(){e.apply(be,a),i=c}),t))}},Re=e.getReporter().log,Ae="rtc-intersecting",Ce="visible",_e="invisible",De=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],Me=function(e){return"".concat(null==e?void 0:e.getAttribute(B),"-").concat(null==e?void 0:e.rtcPurpose)},xe=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(Me(t)," has error, error=").concat(t.error,",doc.visibilityState=").concat(document.visibilityState,", mediaStream="),o=Se(r);Re.debug(n,o),"visible"===document.visibilityState&&ke(r)&&t.load()}if(t.paused){var a=!1;if(i.hasActivated&&"video"===i.mediaKind?function(e){return e&&e.getAttribute(Ae)===Ce}(t)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(t).visibility&&(a=!0):a=!0,a){var s="".concat(e,": ").concat(Me(t)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(t.getAttribute(Ae),", mediaStream="),c=Se(r);Re.error(s,c),ke(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(Me(t)," currentTime stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(t.currentTime,", mediaStream="),a=Se(r);return Re.error(o,a),void("visible"===document.visibilityState&&ke(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=Se(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Re.error(r,n,o)}}),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=Se(null==t?void 0:t.srcObject),o=null==t?void 0:t.error;Re.debug(r,n,o)}}),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=Se(null==t?void 0:t.srcObject);Re.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){Re.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(Ae,Ce):null===(r=e.target)||void 0===r||r.setAttribute(Ae,_e)}))})));for(var a=0;a<n;a++){var s,c=this._createElement();null===(s=this.observer)||void 0===s||s.observe(c),this.addAtttribute(c),c.setAttribute(B,"".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(B,"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}}])}(),je=function(){return ve||Ve(),ve},Le=function(){return he||Ve(),he},Ne=e.Environment.isIOS()||e.Environment.isAndroid()?9:25,Ve=function(){ve||(ve=new xe("audio",2)),he||(he=new xe("video",Ne))},Fe=new AudioContext,Ue=function(e){var t=e.getAudioTracks(),r=Fe.createMediaStreamDestination();return t.forEach((function(e){Fe.createMediaStreamSource(new MediaStream([e])).connect(r)})),r.stream.getAudioTracks()[0]},Ge=function(e,t,r){"running"!==e.state&&e.resume(),r.connect(t),t.fftSize=2048,t.smoothingTimeConstant=.4;var n=new Float32Array(t.fftSize);if(t.getFloatTimeDomainData)t.getFloatTimeDomainData(n);else{var i=new Uint8Array(t.fftSize);t.getByteTimeDomainData(i);for(var o=0;o<n.length;++o)n[o]=i[o]/128-1}for(var a=0,s=0;s<n.length;s++)a+=n[s]*n[s];return Math.max(10*Math.log10(a/n.length)+100,0)/100},Be=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")},qe=je(),He=Le(),Je=e.getReporter().log,Ye=function(){return u((function e(){o(this,e),Object.defineProperty(this,"players",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.players=[]}),[{key:"getElement",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()})).map((function(e){return e.element}))}},{key:"getPlayInfos",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}))}},{key:"play",value:function(t,r,n){var i,o=this,a=t.getTrackId(),s=t.sfuStream||new MediaStream([t.getMediaStreamTrack()]);if("video"===t.trackMediaType){var c,u=this.findDom(r);if(!u)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"wrapper dom not found");var d=n||{},l=d.mirror,p=d.fit;if((i=this.players.find((function(e){return e.container===r})))&&(null===(c=i.track)||void 0===c?void 0:c.getTrackId())!==(null==t?void 0:t.getTrackId()))return this.stop(i.track,r),void this.play(t,r,n);i?(i.element.pause(),!t.sourceMirror!=!l?i.element.style.transform="scaleX(-1)":i.element.style.transform="",p&&(i.element.style.objectFit=p),i.element.srcObject=s,i.element.load()):((i={container:r,track:t,playerConfig:n}).element=function(e,t,r){var n=Le().popElement();n.style.width="100%",n.style.height="100%";var i=r.mirror,o=r.fit;return!0===i&&(n.style.transform="scaleX(-1)"),o&&(n.style.objectFit=o),e.appendChild(n),n.pause(),n.srcObject=t,n.load(),n}(u,s,{mirror:!t.sourceMirror!=!l,fit:p}),this.players.push(i))}else(i=this.players.find((function(e){var r;return(null===(r=e.track)||void 0===r?void 0:r.getTrackId())===t.getTrackId()})))?(i.element.pause(),i.element.srcObject=s,i.element.load()):((i={track:t}).element=function(e){var t=je().popElement();return t.srcObject=e,t}(s),this.players.push(i));i.element.paused&&i.element.play().then((function(){i.isPlaying=!0})).catch((function(t){"NotAllowedError"===t.name?(Je.error("autoplay failed",e.tryJsonStringify(t)),e.EventBus.emit("autoplay-failed",o)):Je.warn("".concat(a," play has exception"),e.tryJsonStringify(t))}))}},{key:"isPlaying",value:function(e){return this.players.filter((function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===(null==e?void 0:e.getTrackId())})).some((function(e){return e.isPlaying}))}},{key:"stop",value:function(e,t){var r=this,n=this.players.filter((function(r){var n;return t?r.container===t:(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())}));if(n.length){n.forEach((function(t){var n;t.element.pause(),null===(n=r.findDom(t.container))||void 0===n||n.removeChild(t.element),t.element.srcObject=null,"audio"===e.trackMediaType?qe.pushElement(t.element):He.pushElement(t.element)}));for(var i=this.players.length-1;i>=0;i--)n.includes(this.players[i])&&this.players.splice(i,1)}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}(),Qe=new Ye,We=function(){return Qe};function Ke(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ke=function(){return!!e})()}var ze,$e=e.getReporter(),Xe=$e.log,Ze=$e.trace,et=Xe,tt=We(),rt=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,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:Ze}),Object.defineProperty(i,"sourceNode",{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,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r?(i.trackMediaType=r.kind,i.trackSettings=r.getSettings()):n&&(i.trackMediaType="audio"),"audio"===i.trackMediaType&&(i.audioContext=Fe,i.analyser=i.audioContext.createAnalyser()),i.trackId="".concat(i.trackMediaType,"_").concat(e.createUuid(6)),i.setMediaStreamTrack(r,n),i}return f(t,e.EventEmitter),u(t,[{key:"isPlaying",get:function(){return tt.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return et.info.apply(et,["track emit event",e].concat(n)),(o=t,a="emit",s=this,u=L(l(1&(c=3)?o.prototype:o),a,s),2&c&&"function"==typeof u?function(e){return u.apply(s,e)}:u)([e].concat(n));var o,a,s,c,u}},{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=Ue(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){Xe.info("replaceTrack",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(H,"replace",this),(this.isPlaying||r)&&this.innnerPlay({updated:!0})}},{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(e){Xe.info("stop paly track ".concat(this.getTrackId())),tt.stop(this,e)}},{key:"innnerPlay",value:function(t){var r=this,n=t.element,i=t.config;t.updated?tt.getPlayInfos(this).forEach((function(e){e.container?tt.findDom(e.container)?tt.play(r,e.container,e.playerConfig):tt.stop(r,e.container):tt.play(r,e.container,e.playerConfig)})):tt.play(this,n,i);if("audio"===this.trackMediaType)try{"running"!==this.audioContext.state&&this.audioContext.resume()}catch(t){Xe.debug("resume audioContext failed: ".concat(e.tryJsonStringify(t)))}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function nt(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.")}()}function it(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function ot(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?it(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):it(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(ze||(ze={}));var at=j(j(j(j(j(j({},ze.LLD,"lld"),ze.LD,"ld"),ze.SD,"sd"),ze.HD,"hd"),ze.FHD,"fhd"),ze.QHD,"qhd"),st={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},ct=function(e){return 2560===e.width&&1440===e.height},ut=function(e,t){var r=lt(e,t),n=function(e,t){var r={high:M.QHD,low:M.LD,QHD:M.QHD,FHD:M.FHD,HD:M.HD,SD:M.SD,LD:M.LD},n=r[e]||M.None,i=st[e],o=t[t.length-1].width*t[t.length-1].height;if(o<i[0]){var a=Object.entries(st).find((function(e){var t=nt(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]}));n=r[nt(a,1)[0]]}return n}(e,t);return{resolution:r,resolutionLevel:n}},dt=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},lt=function(e,t){var r=st[e],n=t.length,i=t[t.length-1];if(("FHD"===e||"high"===e)&&ct(i))return i;if(t[0].width*t[0].height>st.FHD[1])return t[0];for(var o=0;n>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=n-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},pt=[49152,76800,307200,1228800,2764800,4915200],ft=[200,350,1e3,1800,2828,5600],vt=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],ht=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],mt=function(e,t){var r=ze.FHD,n=e*t;return n<=pt[ze.LLD]?r=ze.LLD:n<=pt[ze.LD]?r=ze.LD:n<=pt[ze.SD]?r=ze.SD:n<=pt[ze.HD]?r=ze.HD:n<=pt[ze.FHD]?r=ze.FHD:n<=pt[ze.QHD]&&(r=ze.QHD),r},yt=function(e,t,r,n){var i=0,o=0;if(n<=r)return[i=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)i=vt[r][0],o=vt[r][1];else if(4*t==3*e)i=ht[r][0],o=ht[r][1];else{var s=Math.sqrt(1*vt[r][0]*vt[r][1]/e/t);s=1*(i=(i=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[i,o]},gt=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!n){var i=1;30!==r&&(i=Math.sqrt(r/30));var o=ft[mt(e,t)];n=Math.round(Math.max(i*o,50))}return n},bt=function(e){var t=e.width,r=e.height,n=e.frameRate,i=e.maxBitrate,o=e.resolutionLevel,a=mt(t,r),s=[],c=a>=ze.HD?3:2,u=function(e){var o=nt(yt(t,r,e,a),2),s=o[0],c=o[1],u=ft[e]/ft[a],d=1/(c/r);return{targetWidth:s,rid:at[e],targetHeight:c,minBitrate:50,maxFramerate:n,maxBitrate:Math.round(Math.max(30,i*u)),scaleResolutionDownBy:d}};a>ze.LLD&&s.push(ot({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,ze.LLD)===o},u(ze.LLD))),a>ze.LD&&s.push(ot({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,ze.LD)===o},u(ze.LD))),a>ze.SD&&s.push(ot({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,ze.SD)===o},u(ze.SD))),a===ze.FHD?(s.push(ot({activeForBitrateMap:!1,activeForRealuse:!1},u(ze.HD))),s.push(ot({activeForBitrateMap:!0,activeForRealuse:ee.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(ze.FHD)))):s.push(ot({activeForBitrateMap:!0,activeForRealuse:Math.pow(2,a)===o},u(a)));for(var d=0,l=0;l<s.length;++l)0!=l&&(s[l].minBitrate=d),d=Math.round(Math.max((s[l].maxBitrate+s[l].minBitrate)/2,s[l].maxBitrate-400));return s.shift(),s},St=function(e,t){var r=mt(e,t),n=Math.pow(2,r);return console.log(n,r),n},kt=function(e){var t,r=e.getMaxBitrate(),n=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==n?void 0:n.width)||e.trackSettings.width,o=(null==n?void 0:n.height)||e.trackSettings.height,a=(null==n?void 0:n.frameRate)||e.trackSettings.frameRate,s=!ee.simulcast||e.source===exports.VideoSourceInfo.SCREENCAST||ct({width:i,height:o}),c={resolutionLevel:St(i,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:i,targetHeight:o}]:ee.republish?c.encodings=bt({width:1920,height:1080,frameRate:30,maxBitrate:gt(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=bt({width:i,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function Pt(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 wt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Pt(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Pt(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Et(e,t,r){return t=l(t),d(e,Tt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function Tt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Tt=function(){return!!e})()}function Ot(e,t,r,n){var i=L(l(e.prototype),t,r);return"function"==typeof i?function(e){return i.apply(r,e)}:i}var It=We(),Rt=e.getReporter().log,At=function(){function t(e,r){var n;if(o(this,t),n=Et(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){var i,a=e.muted;if(n.muted=a,!r)r=null===(i=e.getSettings())||void 0===i?void 0:i.deviceId}return n.enabled=!0,n.deviceId=r,n}return f(t,rt),u(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;Ot(t,"setMediaStreamTrack",this)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stop(),r.close&&r.close(),r.emit("track-ended")})}},{key:"play",value:function(e,t){this.innnerPlay({element:e,config:t})}},{key:"setEnabled",value:function(t){return Rt.info("setEnabled",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.enabled=t,this.emit(H,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;Rt.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stop(),this.emit(H,"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 Rt.info("setMuted",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.muted=t,this.mediaStreamTrack.enabled=!t,this.emit(H,t?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var t=this;return Rt.debug("gengrate new audioTrack"),new Promise((function(r,n){var i;ge({audio:wt(wt({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){Rt.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 Rt.info("gengrate new videoTrack"),new Promise((function(r,n){var i,o=wt({source:t.source},t.config);t.config.deviceId&&(o.deviceId=t.config.deviceId),t.config.facingMode&&t.config.deviceId&&(Rt.info("ignore did param to create videoTrack because facingMode is",t.config.facingMode),delete o.deviceId),ge({video:o,audio:!1}).then((function(e){i=e.getVideoTracks()[0],r(i)})).catch((function(t){Rt.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,Rt.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):"video"===this.trackMediaType?this.getVideoTrack().then((function(t){return e.replaceTrackInner(t,null,!0)})):void 0}},{key:"setDevice",value:(r=i(x.mark((function e(t){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(Rt.info("setDevice",t),!this.isClosed){e.next=3;break}return e.abrupt("return");case 3:if(!(this instanceof Dt)||"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(Rt.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(),Ct=function(){function t(e,r,n){var i;if(o(this,t),(i=Et(this,t,[e,r])).config=n,e){var a=e.getSettings(),s=a.width,c=a.height;i.maxBitrate=gt(s,c,n.frameRate,n.maxBitrate)}return i}return f(t,At),u(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:function(t){var r=this;Rt.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&&!F[n])return Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid dimension"));!s!=!this.config.mirror&&(this.emit(H,"mirror",s),this.config.mirror=s),a&&a!==this.optimizationMode&&(this.config.optimizationMode=a,this.emit(H,"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=wt({frameRate:this.config.frameRate},me(this.config.dimension)),d=this.getMediaStreamTrack();return null==d?void 0:d.applyConstraints(u).then((function(){var e,t=null===(e=r.getMediaStreamTrack())||void 0===e?void 0:e.getSettings(),n=t.width,i=t.height;r.maxBitrate=gt(n,i,r.config.frameRate,o),console.log(n,i,u,r.maxBitrate),r.emit(H,"republish",r)})).catch((function(t){var n=e.parseVideoDeviceError(t);throw Rt.error("videoTrack ".concat(r.getTrackId()," setEncoderConfiguration error"),n),n}))}},{key:"getCurrentFrameData",value:function(){return Rt.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:Be(It.getElement(this)[0])}},{key:"play",value:function(e,r){return Rt.info("local video play"),Ot(t,"play",this)([e,r])}}])}(),_t=function(){function e(t,r){return o(this,e),Et(this,e,[t,r])}return f(e,At),u(e,[{key:"setVolume",value:function(e){Rt.info("setVolume",e),this.isClosed||It.getElement(this)[0]&&(It.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Rt.info("getVolume"),!this.isClosed)return It.getElement(this)[0]?It.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:Ge(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return Rt.info("local audio play"),Ot(e,"play",this)([])}}])}(),Dt=function(){function e(t,r){var n;return o(this,e),(n=Et(this,e,[t,r.deviceId,r])).setSource(exports.VideoSourceInfo.CAMERA),n}return f(e,Ct),u(e)}(),Mt=function(){function e(t,r){var n;return o(this,e),(n=Et(this,e,[t,(r||{}).deviceId])).config=r,n.setSource(exports.AudioSourceInfo.MIC),n.analyser=n.audioContext.createAnalyser(),n}return f(e,_t),u(e,[{key:"setVolume",value:function(e){Rt.info("setVolume",e),this.isClosed||It.getElement(this)[0]&&(It.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Rt.info("getVolume"),!this.isClosed)return It.getElement(this)[0]?It.getElement(this)[0].volume:void 0}}])}(),xt=function(){var t=i(x.mark((function t(r){var n,i,o,a,s,c,u,d,l,p;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return Rt.info("createMicrophoneAudioTrack",r),n={AEC:!0,AGC:!0,ANS:!0},o=(i=r||n).AEC,a=void 0===o||o,s=i.AGC,c=void 0===s||s,u=i.ANS,d=void 0===u||u,t.prev=3,t.next=6,ge({video:!1,audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:a,AGC:c,ANS:d}});case 6:return l=t.sent,p=l.getAudioTracks()[0],Rt.info("MicrophoneAudioTrack created"),t.abrupt("return",new Mt(p,Object.assign({},r,{AEC:a,AGC:c,ANS:d})));case 12:throw t.prev=12,t.t0=t.catch(3),e.parseAudioDeviceError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[3,12]])})));return function(e){return t.apply(this,arguments)}}(),jt=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 Rt.info("createCameraVideoTrack",r),n=r.deviceId,i=r.facingMode,o=r.dimension,a=void 0===o?"VD_640x480":o,s=r.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(30,r.frameRate||15),t.prev=3,t.next=6,ge({video:{deviceId:n,source:exports.VideoSourceInfo.CAMERA,frameRate:u,dimension:a,facingMode:i},audio:!1});case 6:return d=t.sent,l=d.getVideoTracks()[0],Rt.info("CameraVideoTrack created"),t.abrupt("return",new Dt(l,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c})));case 12:throw t.prev=12,t.t0=t.catch(3),e.parseVideoDeviceError(t.t0);case 15:case"end":return t.stop()}}),t,null,[[3,12]])})));return function(e){return t.apply(this,arguments)}}(),Lt=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 Rt.info("createScreenVideoTrack",r),n=r.displaySurface,i=void 0===n?"monitor":n,o=r.dimension,a=void 0===o?"VD_1920x1080":o,s=r.optimizationMode,c=void 0===s?"detail":s,u=Math.min(r.frameRate||5,30),t.prev=3,t.next=6,ge({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:i,frameRate:u,dimension:a},audio:!1});case 6:return d=t.sent,(l=new Ct(d.getVideoTracks()[0],null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.SCREENCAST),Rt.info("ScreenVideoTrack created"),t.abrupt("return",[l]);case 13:throw t.prev=13,t.t0=t.catch(3),e.parseScreenShareError(t.t0);case 16:case"end":return t.stop()}}),t,null,[[3,13]])})));return function(e){return t.apply(this,arguments)}}(),Nt=function(){var t=i(x.mark((function t(r,n){var i,o,a,s,c,u,d,l,p,f,v,h,m,y,g,b,S,k,P,w;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return Rt.info("createMicrophoneAndCameraTracks",r,n),i=Math.min(r.frameRate||15,30),o=r.deviceId,a=r.facingMode,s=r.dimension,c=void 0===s?"VD_640x480":s,u=r.optimizationMode,d=void 0===u?"balanced":u,l={AEC:!0,AGC:!0,ANS:!0},f=(p=n||l).AEC,v=void 0===f||f,h=p.AGC,m=void 0===h||h,y=p.ANS,g=void 0===y||y,t.prev=5,t.next=8,ge({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:m,ANS:g}});case 8:return b=t.sent,S=b.getVideoTracks()[0],k=b.getAudioTracks()[0],Rt.info("CameraVideoTrack and MicrophoneTrack created"),P=new Dt(S,Object.assign({},r,{frameRate:i,dimension:c,optimizationMode:d})),w=new Mt(k,Object.assign({},Object.assign({},n,{AEC:v,AGC:m,ANS:g}))),t.abrupt("return",[P,w]);case 17:throw t.prev=17,t.t0=t.catch(5),e.parseVideoDeviceError(t.t0);case 20:case"end":return t.stop()}}),t,null,[[5,17]])})));return function(e,r){return t.apply(this,arguments)}}(),Vt=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(Rt.info("createCustomVideoTrack",r),i=(n=r||{}).mediaStreamTrack,o=n.dimension,a=void 0===o?"VD_640x480":o,s=n.optimizationMode,c=void 0===s?"balanced":s,u=Math.min(r.frameRate||15,30),i instanceof MediaStreamTrack&&"video"===i.kind){t.next=5;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 5:return(d=new Ct(i,null,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c}))).setSource(exports.VideoSourceInfo.CAMERA),t.abrupt("return",d);case 8:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),Ft=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(Rt.info("createCustomAudioTrack",r),(n=(r||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){t.next=4;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 4:return(i=new _t(n)).setSource(exports.AudioSourceInfo.MIC),t.abrupt("return",i);case 7:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}();function Ut(e,t,r,n){var i=L(l(1&n?e.prototype:e),t,r);return 2&n&&"function"==typeof i?function(e){return i.apply(r,e)}:i}function Gt(e,t,r){return t=l(t),d(e,Bt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function Bt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Bt=function(){return!!e})()}var qt,Ht=e.getReporter().log,Jt=We(),Yt=function(){function e(t,r,n){var i;return o(this,e),i=Gt(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,rt),u(e,[{key:"getUserId",value:function(){return Ht.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)}}])}(),Qt=function(){function t(e,r,n){var i;return o(this,t),i=Gt(this,t,[e,r,n]),Object.defineProperty(i,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.deviceId="",i}return f(t,Yt),u(t,[{key:"getMediaStreamTrack",value:function(){return ee.audioSFU?Ue(this.sfuStream):Ut(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){Ht.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stop(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){Ht.info("setVolume",e),Jt.getElement(this)[0]&&(Jt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Ht.info("getVolume"),Jt.getElement(this)[0])return Jt.getElement(this)[0].volume}},{key:"setSpeaker",value:function(t){var r=this;return Ht.info("setSpeaker",t),new Promise((function(n,i){var o,a=Jt.getElement(r)[0];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 Ge(this.audioContext,this.analyser,this.sourceNode)}},{key:"play",value:function(){return Ht.info("remote audio play"),Ut(t,"innnerPlay",this,3)([{}])}}])}(),Wt=function(){function e(t,r){return o(this,e),Gt(this,e,[t,r])}return f(e,Yt),u(e,[{key:"play",value:function(t,r){return Ht.info("remote video play"),Ut(e,"innnerPlay",this,3)([{element:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(Ht.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&Ut(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return Ht.info("getCurrentFrameData"),this.isPlaying?Be(Jt.getElement(this)[0]):null}}])}();!function(e){var t,r,n,i,o,a,s,c;(t=e.DataType||(e.DataType={}))[t.DATA_TYPE_STREAM=0]="DATA_TYPE_STREAM",t[t.DATA_TYPE_PARTICIPANTS=1]="DATA_TYPE_PARTICIPANTS",t[t.DATA_TYPE_CONFERENCE=2]="DATA_TYPE_CONFERENCE",t[t.DATA_TYPE_GROUP_LIST=3]="DATA_TYPE_GROUP_LIST",t[t.DATA_TYPE_GROUP=4]="DATA_TYPE_GROUP",(r=e.OptType||(e.OptType={}))[r.OPT_TYPE_ADD=0]="OPT_TYPE_ADD",r[r.OPT_TYPE_REMOVE=1]="OPT_TYPE_REMOVE",r[r.OPT_TYPE_UPDATE=2]="OPT_TYPE_UPDATE",(n=e.SyncResponseCode||(e.SyncResponseCode={}))[n.SYNC_OK=0]="SYNC_OK",n[n.SYNC_PART_SUC=10]="SYNC_PART_SUC",n[n.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",n[n.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",n[n.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",n[n.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",n[n.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(i=e.GroupUpdate||(e.GroupUpdate={}))[i.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",i[i.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",i[i.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",i[i.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",i[i.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",i[i.GROUP_UPDATE_REMOVE_PROPERTIES=5]="GROUP_UPDATE_REMOVE_PROPERTIES",(o=e.GroupListUpdate||(e.GroupListUpdate={}))[o.GROUP_LIST_UPDATE_ADD_ID=0]="GROUP_LIST_UPDATE_ADD_ID",o[o.GROUP_LIST_UPDATE_REMOVE_ID=1]="GROUP_LIST_UPDATE_REMOVE_ID",(a=e.LEAVE_GROUP_REASON_CODE||(e.LEAVE_GROUP_REASON_CODE={}))[a.NORMAL_LEAVE=0]="NORMAL_LEAVE",(s=e.DismissGroupReasonCode||(e.DismissGroupReasonCode={}))[s.NORMAL_DISMISS=0]="NORMAL_DISMISS",(c=e.Result||(e.Result={}))[c.Ok=0]="Ok",c[c.Error=1]="Error"}(qt||(qt={}));var Kt={nested:{signal_msg:{nested:{AudioSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2}}},VideoSsrcSpec:{fields:{ssrc:{type:"uint32",id:1},rtxSsrc:{type:"uint32",id:2},fecSsrc:{type:"uint32",id:3}}},MultiPcAdaptRequestInfo:{fields:{audioSsrcSpec:{rule:"repeated",type:"AudioSsrcSpec",id:1},videoSsrcSpec:{rule:"repeated",type:"VideoSsrcSpec",id:2}}},AudioStreamFormat:{fields:{codec:{type:"string",id:1},sampleRate:{type:"int64",id:2},channelNum:{type:"int64",id:3}}},AudioFormatPreference:{fields:{preferred:{type:"AudioStreamFormat",id:1},optional:{rule:"repeated",type:"AudioStreamFormat",id:2}}},AudioStreamOptional:{fields:{format:{rule:"repeated",type:"AudioStreamFormat",id:1}}},VideoStreamFormat:{fields:{codec:{type:"string",id:1},profile:{type:"string",id:2}}},VideoFormatPreference:{fields:{preferred:{type:"VideoStreamFormat",id:1},optional:{rule:"repeated",type:"VideoStreamFormat",id:2}}},FormatPreference:{fields:{audio:{type:"AudioFormatPreference",id:1},video:{type:"VideoFormatPreference",id:2}}},Resolution:{fields:{width:{type:"uint32",id:1},height:{type:"uint32",id:2}}},VideoSsrcParameters:{fields:{ssrc:{type:"uint32",id:1},framerate:{type:"int32",id:2},resolution:{type:"Resolution",id:3},maxBitrate:{type:"int32",id:4},minBitrate:{type:"int32",id:5},active:{type:"bool",id:6},bitrate:{type:"int64",id:7},tlayer:{type:"int64",id:8},multiSlice:{type:"int64",id:9},keyFrameInterval:{type:"int64",id:10},constantPpsid:{type:"int64",id:11},rid:{type:"string",id:12}}},VideoParameters:{oneofs:{_resolutionLevel:{oneof:["resolutionLevel"]}},fields:{ssrc:{type:"uint32",id:1},resolution:{type:"Resolution",id:2},framerate:{type:"int32",id:3},bitrate:{type:"string",id:4},multiSlice:{type:"int32",id:5},keyFrameInterval:{type:"int64",id:6},constantPpsid:{type:"int64",id:7},resolutionLevel:{type:"uint32",id:8,options:{proto3_optional:!0}}}},GroupVersion:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},StreamInfo:{fields:{type:{type:"string",id:1},owner:{type:"string",id:2},attributesJsonStr:{type:"string",id:3},label:{type:"string",id:4},createTime:{type:"int64",id:7}}},StreamVideoParameters:{fields:{resolution:{type:"Resolution",id:1},framerate:{type:"int64",id:2},bitrate:{type:"int64",id:3},keyFrameInterval:{type:"int64",id:4},multiSlice:{type:"int64",id:5},constantPpsid:{type:"int64",id:6}}},VideoStreamPara:{fields:{specs:{rule:"repeated",type:"string",id:1},resolution:{rule:"repeated",type:"Resolution",id:2},framerate:{rule:"repeated",type:"int32",id:3},bitrate:{rule:"repeated",type:"string",id:4},keyFrameInterval:{rule:"repeated",type:"int32",id:5}}},VideoStreamOptional:{fields:{format:{rule:"repeated",type:"VideoStreamFormat",id:1},parameters:{type:"VideoStreamPara",id:2}}},StreamAudioDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},format:{type:"AudioStreamFormat",id:4},source:{type:"string",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:7},optional:{type:"AudioStreamOptional",id:8}}},StreamVideoDesc:{fields:{trackId:{type:"string",id:1},msid:{type:"string",id:2},status:{type:"string",id:3},source:{type:"string",id:4},format:{type:"VideoStreamFormat",id:5},ssrc:{rule:"repeated",type:"uint32",id:6},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:7},parameters:{type:"StreamVideoParameters",id:8},optional:{type:"VideoStreamOptional",id:9},highestResolutionLevel:{type:"uint32",id:10}}},StreamMediaDesc:{fields:{audio:{type:"StreamAudioDesc",id:1},video:{type:"StreamVideoDesc",id:2}}},Stream:{fields:{id:{type:"string",id:1},type:{type:"string",id:2},media:{type:"StreamMediaDesc",id:3},info:{type:"StreamInfo",id:4},version:{type:"int64",id:5}}},OriginMsg:{fields:{type:{type:"string",id:1},id:{type:"string",id:2}}},ErrorMsg:{fields:{id:{type:"string",id:1},code:{type:"int32",id:2},msg:{type:"string",id:3},origin:{type:"OriginMsg",id:4}}},ErrorMsgs:{fields:{globalStatus:{type:"string",id:1},detailStatus:{rule:"repeated",type:"ErrorMsg",id:2}}},DataType:{values:{DATA_TYPE_STREAM:0,DATA_TYPE_PARTICIPANTS:1,DATA_TYPE_CONFERENCE:2,DATA_TYPE_GROUP_LIST:3,DATA_TYPE_GROUP:4}},OptType:{values:{OPT_TYPE_ADD:0,OPT_TYPE_REMOVE:1,OPT_TYPE_UPDATE:2}},SyncResponseCode:{values:{SYNC_OK:0,SYNC_PART_SUC:10,SYNC_DATA_SIZE_LIMITED:11,SYNC_NOT_SUPPORT_TYPE:12,SYNC_NOT_FOUND:13,SYNC_CHANNEL_NOT_EXIST:14,SYNC_INTERNAL_ERROR:15}},GroupParticipant:{fields:{uid:{type:"string",id:1},pid:{type:"string",id:2},userData:{type:"string",id:3}}},GroupAudioInfo:{fields:{label:{type:"string",id:1},audio:{type:"Stream",id:2}}},GroupInfo:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2},participants:{rule:"repeated",type:"GroupParticipant",id:3},audioInfo:{type:"GroupAudioInfo",id:4},properties:{rule:"repeated",type:"GroupProperty",id:5}}},GroupProperty:{fields:{key:{type:"string",id:1},value:{type:"string",id:2}}},SyncFullData:{oneofs:{_ver:{oneof:["ver"]},_totalPages:{oneof:["totalPages"]},_pagingSeq:{oneof:["pagingSeq"]}},fields:{ver:{type:"int64",id:1,options:{proto3_optional:!0}},totalPages:{type:"int32",id:2,options:{proto3_optional:!0}},pagingSeq:{type:"int64",id:3,options:{proto3_optional:!0}},groupData:{type:"GroupPagingData",id:10},groupListData:{type:"GroupListPagingData",id:11}}},GroupPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupInfos:{rule:"repeated",type:"GroupInfo",id:3}}},GroupListPagingData:{fields:{pagingSeq:{type:"int64",id:1},curPage:{type:"int32",id:2},groupIds:{rule:"repeated",type:"string",id:3}}},SyncChangeLog:{fields:{groupListChangeLogs:{rule:"repeated",type:"GroupListChangeLog",id:1},groupChangeLogs:{rule:"repeated",type:"GroupChangeLog",id:2}}},SyncDataRequest:{oneofs:{_id:{oneof:["id"]}},fields:{type:{type:"DataType",id:1},id:{type:"string",id:2,options:{proto3_optional:!0}},ver:{type:"int64",id:3},forceFullSync:{type:"bool",id:4},supportPagingSync:{type:"bool",id:5}}},SyncDataResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},fullSync:{type:"SyncFullData",id:3},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:4}}},SyncIds:{fields:{id:{type:"string",id:1},ver:{type:"int64",id:2}}},SyncDataByIdsRequest:{fields:{type:{type:"DataType",id:1},ids:{rule:"repeated",type:"SyncIds",id:2},forceFullSync:{type:"bool",id:3},supportPagingSync:{type:"bool",id:4}}},SyncDataByIdsResponse:{fields:{code:{type:"SyncResponseCode",id:1},errMsg:{type:"string",id:2},notFoundIds:{rule:"repeated",type:"string",id:3},fullSync:{type:"SyncFullData",id:4},changeLogs:{rule:"repeated",type:"SyncChangeLog",id:5}}},GroupUpdate:{values:{GROUP_UPDATE_AUDIO_STREAM_LOST:0,GROUP_UPDATE_AUDIO_STREAM_RECOVER:1,GROUP_UPDATE_ADD_PARTICIPANTS:2,GROUP_UPDATE_REMOVE_PARTICIPANTS:3,GROUP_UPDATE_SET_PROPERTIES:4,GROUP_UPDATE_REMOVE_PROPERTIES:5}},GroupUpdateOpt:{fields:{updateAction:{type:"GroupUpdate",id:1},participants:{rule:"repeated",type:"GroupParticipant",id:2},properties:{rule:"repeated",type:"GroupProperty",id:3}}},GroupChangeLog:{oneofs:{_groupInfo:{oneof:["groupInfo"]},_updateOpt:{oneof:["updateOpt"]},_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},id:{type:"string",id:3},groupInfo:{type:"GroupInfo",id:4,options:{proto3_optional:!0}},updateOpt:{type:"GroupUpdateOpt",id:5,options:{proto3_optional:!0}},msgId:{type:"string",id:6,options:{proto3_optional:!0}}}},GroupListUpdate:{values:{GROUP_LIST_UPDATE_ADD_ID:0,GROUP_LIST_UPDATE_REMOVE_ID:1}},GroupListUpdateOpt:{fields:{updateAction:{type:"GroupListUpdate",id:1},id:{type:"string",id:2}}},GroupListChangeLog:{oneofs:{_msgId:{oneof:["msgId"]}},fields:{ver:{type:"int64",id:1},type:{type:"OptType",id:2},updateOpt:{type:"GroupListUpdateOpt",id:3},msgId:{type:"string",id:4,options:{proto3_optional:!0}}}},JoinGroupRequest:{fields:{groupId:{type:"string",id:1},userData:{type:"string",id:2},autoJoinGroupAudio:{type:"bool",id:3},autoLeaveChannelAudio:{type:"bool",id:4}}},JoinGroupResponse:{oneofs:{_joinGroupAudioSuccess:{oneof:["joinGroupAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},group:{type:"GroupInfo",id:3},joinGroupAudioSuccess:{type:"bool",id:4,options:{proto3_optional:!0}}}},LEAVE_GROUP_REASON_CODE:{values:{NORMAL_LEAVE:0}},LeaveGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"LEAVE_GROUP_REASON_CODE",id:2},autoJoinChannelAudio:{type:"bool",id:3}}},LeaveGroupResponse:{oneofs:{_joinChannelAudioSuccess:{oneof:["joinChannelAudioSuccess"]}},fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2},joinChannelAudioSuccess:{type:"bool",id:3,options:{proto3_optional:!0}}}},DismissGroupReasonCode:{values:{NORMAL_DISMISS:0}},DismissGroupRequest:{fields:{groupId:{type:"string",id:1},reasonCode:{type:"DismissGroupReasonCode",id:2}}},DismissGroupResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},ObserveAllGroupsRequest:{fields:{}},ObserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},UnobserveAllGroupsRequest:{fields:{}},UnobserveAllGroupsResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},properties:{rule:"repeated",type:"GroupProperty",id:2}}},SetGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},RemoveGroupPropertiesRequest:{fields:{groupId:{type:"string",id:1},keys:{rule:"repeated",type:"string",id:2}}},RemoveGroupPropertiesResponse:{fields:{code:{type:"int32",id:1},errMsg:{type:"string",id:2}}},SetParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},RemoveParticipantPropertiesRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},Result:{values:{Ok:0,Error:1}},Response:{oneofs:{data:{oneof:["reason","createPeerConnectionResponse","errorMsg","queryStreamsVerResponse","queryStreamsResponse","publishResponse","subscribeResponse","joinGroupResponse","leaveGroupResponse","dismissGroupResponse","observeAllGroupsResponse","unobserveAllGroupsResponse","syncDataResponse","syncDataByIdsResponse","setGroupPropertiesResponse","removeGroupPropertiesResponse"]}},fields:{result:{type:"Result",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3},code:{type:"int32",id:4},reason:{type:"string",id:11},createPeerConnectionResponse:{type:"CreatePeerConnectionResponse",id:15},errorMsg:{type:"ErrorMsgs",id:16},queryStreamsVerResponse:{type:"QueryStreamsVerResponse",id:17},queryStreamsResponse:{type:"QueryStreamsResponse",id:18},publishResponse:{type:"PublishResponse",id:21},subscribeResponse:{type:"SubscribeResponse",id:22},joinGroupResponse:{type:"JoinGroupResponse",id:24},leaveGroupResponse:{type:"LeaveGroupResponse",id:25},dismissGroupResponse:{type:"DismissGroupResponse",id:26},observeAllGroupsResponse:{type:"ObserveAllGroupsResponse",id:27},unobserveAllGroupsResponse:{type:"UnobserveAllGroupsResponse",id:28},syncDataResponse:{type:"SyncDataResponse",id:29},syncDataByIdsResponse:{type:"SyncDataByIdsResponse",id:30},setGroupPropertiesResponse:{type:"SetGroupPropertiesResponse",id:31},removeGroupPropertiesResponse:{type:"RemoveGroupPropertiesResponse",id:32}}},NotificationItem:{oneofs:{notification:{oneof:["streamNotification","serverFailoverNotification","progressNotification","groupNotification","groupListNotification"]}},fields:{event:{type:"string",id:1},streamNotification:{type:"StreamNotification",id:11},serverFailoverNotification:{type:"ServerFailoverNotification",id:13},progressNotification:{type:"ProgressNotification",id:14},groupNotification:{type:"GroupChangeLog",id:17},groupListNotification:{type:"GroupListChangeLog",id:18}}},BatchNotification:{fields:{notificationItem:{rule:"repeated",type:"NotificationItem",id:1},tid:{type:"string",id:2},traceId:{type:"string",id:3}}},MediaMessage:{fields:{payload:{type:"string",id:1}}},AudioStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},uplinkSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:5},format:{type:"AudioStreamFormat",id:6},autoMix:{rule:"repeated",type:"string",id:7},attributesJsonString:{type:"string",id:8}}},VideoStreamTrackDesc:{fields:{streamId:{type:"string",id:1},trackId:{type:"string",id:2},msid:{type:"string",id:3},source:{type:"string",id:4},logicSsrc:{rule:"repeated",type:"uint32",id:5},uplinkSsrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:6},ssrcParameters:{rule:"repeated",type:"VideoSsrcParameters",id:7},streamParameters:{type:"VideoParameters",id:8},attributesJsonString:{type:"string",id:9},forwardOnly:{type:"bool",id:10},mid:{type:"string",id:11},highestResolutionLevel:{type:"int32",id:12}}},MediaStreamTrackDesc:{fields:{audio:{rule:"repeated",type:"AudioStreamTrackDesc",id:1},video:{rule:"repeated",type:"VideoStreamTrackDesc",id:2}}},StreamVersion:{fields:{streamId:{type:"string",id:1},streamVer:{type:"int64",id:2}}},StreamData:{fields:{id:{type:"string",id:1},stream:{type:"Stream",id:2}}},AudioPubOptions:{fields:{source:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2},autoMix:{rule:"repeated",type:"string",id:3}}},VideoPubOptions:{fields:{source:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3},forwardOnly:{type:"bool",id:4}}},MediaPubOptionsSpecify:{fields:{audio:{type:"AudioPubOptions",id:1},video:{type:"VideoPubOptions",id:2}}},BatchPublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},type:{type:"string",id:4},simulcast:{type:"bool",id:5},simulcastVersion:{type:"string",id:6},supportTemporalLayer:{type:"bool",id:7},clientType:{type:"string",id:8},clientVersion:{type:"string",id:9},media:{type:"MediaStreamTrackDesc",id:10},event:{type:"string",id:11},tid:{type:"string",id:12},traceId:{type:"string",id:13}}},BatchUnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},QueryStreamsVerRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsVerResponse:{fields:{streamVersions:{rule:"repeated",type:"StreamVersion",id:1},totalVer:{type:"int32",id:2},msg:{type:"string",id:3}}},StreamControlRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},operation:{type:"string",id:4},data:{type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},highestResolutionLevel:{type:"int32",id:8}}},QueryStreamsRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamIds:{rule:"repeated",type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},QueryStreamsResponse:{fields:{totalVer:{type:"int64",id:1},msg:{type:"string",id:2},streams:{rule:"repeated",type:"StreamData",id:3}}},SetStreamPropertiesRequest:{fields:{roomId:{type:"string",id:1},streamId:{type:"string",id:2},propertiesJsonStr:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},PublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},type:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaPubOptionsSpecify",id:5},attributesJsonStr:{type:"string",id:6},tid:{type:"string",id:7},traceId:{type:"string",id:8}}},PublishResponse:{fields:{id:{type:"string",id:1}}},UnpublishRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},streamId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},NetworkHealth:{fields:{receiving:{type:"bool",id:1},lossRate:{type:"int32",id:2},timestamp:{type:"int64",id:3},cutoff:{type:"bool",id:4},tid:{type:"string",id:5}}},StreamMsg:{oneofs:{value:{oneof:["networkHealth","streamStatus","stream","activeStream","propertiesJsonStr","highestResolutionLevel"]}},fields:{field:{type:"string",id:1},streamVer:{type:"int64",id:2},expiredMs:{type:"int64",id:3},extraValue:{rule:"repeated",type:"string",id:4},tid:{type:"string",id:5},networkHealth:{type:"NetworkHealth",id:10},streamStatus:{type:"string",id:11},stream:{type:"Stream",id:12},activeStream:{type:"string",id:13},propertiesJsonStr:{type:"string",id:14},highestResolutionLevel:{type:"int32",id:15}}},StreamNotification:{oneofs:{data:{oneof:["stream","msg"]}},fields:{streamId:{type:"string",id:1},status:{type:"string",id:2},totalVer:{type:"int64",id:3},msgId:{type:"string",id:4},ts:{type:"int64",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7},stream:{type:"Stream",id:10},msg:{type:"StreamMsg",id:11}}},Candidate:{fields:{candidate:{type:"string",id:1},sdpMlineIndex:{type:"int32",id:2},sdpMid:{type:"string",id:3}}},SessionSignaling:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2},candidate:{type:"Candidate",id:3},optionsJsonStr:{type:"string",id:4}}},SignalingData:{fields:{type:{type:"string",id:1},sdp:{type:"string",id:2}}},CreatePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},tid:{type:"string",id:4},event:{type:"string",id:5},direction:{type:"string",id:6},sdpOffer:{type:"string",id:7},type:{type:"string",id:8},isOca:{type:"bool",id:9},isFailover:{type:"bool",id:10},multiPcAdaptInfo:{type:"MultiPcAdaptRequestInfo",id:11},pcFormatPreference:{type:"FormatPreference",id:12},optionsJsonStr:{type:"string",id:13},traceId:{type:"string",id:14},sfuSsrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:15}}},CreatePeerConnectionResponse:{fields:{connectionId:{type:"string",id:1},sdpAnswer:{type:"string",id:2}}},ClosePeerConnectionRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},direction:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},SoacRequest:{fields:{id:{type:"string",id:1},signaling:{type:"SessionSignaling",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},NotifyAction:{fields:{actionName:{type:"string",id:1},connectionId:{type:"string",id:2},traceId:{type:"string",id:3}}},ServerFailoverNotification:{fields:{actions:{rule:"repeated",type:"NotifyAction",id:1},msgId:{type:"string",id:2},tid:{type:"string",id:3},traceId:{type:"string",id:4}}},ProgressNotification:{fields:{id:{type:"string",id:1},status:{type:"string",id:2},data:{type:"SignalingData",id:3},msgId:{type:"string",id:4},tid:{type:"string",id:5},traceId:{type:"string",id:6}}},AudioBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"AudioSsrcSpec",id:4},format:{type:"AudioStreamFormat",id:5}}},VideoBatchSubOptions:{fields:{subscriptionId:{type:"string",id:1},from:{type:"string",id:2},trackId:{type:"string",id:3},ssrcGroup:{rule:"repeated",type:"VideoSsrcSpec",id:4},parameters:{type:"VideoParameters",id:5},format:{type:"VideoStreamFormat",id:6},subSsrcGroup:{type:"VideoSsrcSpec",id:7}}},MediaBatchSubOptions:{fields:{audio:{rule:"repeated",type:"AudioBatchSubOptions",id:1},video:{rule:"repeated",type:"VideoBatchSubOptions",id:2}}},Audio:{fields:{from:{type:"string",id:1}}},Video:{fields:{from:{type:"string",id:1},params:{type:"VideoParameters",id:2}}},MediaUpdateDesc:{fields:{audio:{type:"Audio",id:1},video:{type:"Video",id:2}}},AudioSubOptions:{fields:{from:{type:"string",id:1},format:{type:"AudioStreamFormat",id:2}}},VideoSubOptions:{fields:{from:{type:"string",id:1},format:{type:"VideoStreamFormat",id:2},parameters:{type:"VideoParameters",id:3}}},MediaSubOptionsSpecify:{fields:{audio:{type:"AudioSubOptions",id:1},video:{type:"VideoSubOptions",id:2}}},SubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},tid:{type:"string",id:3},event:{type:"string",id:4},media:{type:"MediaSubOptionsSpecify",id:5},type:{type:"string",id:6},propertiesJsonStr:{type:"string",id:7},traceId:{type:"string",id:8}}},SubscribeResponse:{fields:{id:{type:"string",id:1}}},UnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},tid:{type:"string",id:4},traceId:{type:"string",id:5}}},BatchSubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},supportTemporalLayer:{type:"bool",id:4},clientType:{type:"string",id:5},clientVersion:{type:"string",id:6},media:{type:"MediaBatchSubOptions",id:7},tid:{type:"string",id:8},type:{type:"string",id:9},event:{type:"string",id:10},propertiesJsonStr:{type:"string",id:11},traceId:{type:"string",id:12}}},BatchUnsubscribeRequest:{fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},connectionId:{type:"string",id:3},audio:{rule:"repeated",type:"string",id:4},video:{rule:"repeated",type:"string",id:5},tid:{type:"string",id:6},traceId:{type:"string",id:7}}},SubscriptionControlRequest:{oneofs:{data:{oneof:["updateDesc","track"]}},fields:{roomId:{type:"string",id:1},participantId:{type:"string",id:2},subscriptionId:{type:"string",id:3},operation:{type:"string",id:4},updateDesc:{type:"MediaUpdateDesc",id:6},track:{type:"string",id:7},tid:{type:"string",id:8},traceId:{type:"string",id:9}}}}}}},zt=e.getProtobufRoot(Kt),$t=zt.lookupType("signal_msg.Response"),Xt=zt.lookupType("signal_msg.BatchNotification"),Zt=zt.lookupType("signal_msg.MediaMessage"),er=zt.lookupType("signal_msg.StreamNotification");zt.lookupType("signal_msg.ProgressNotification");var tr=zt.lookupType("signal_msg.ServerFailoverNotification"),rr=zt.lookupType("signal_msg.PublishRequest"),nr=zt.lookupType("signal_msg.SoacRequest"),ir=zt.lookupType("signal_msg.UnpublishRequest"),or=zt.lookupType("signal_msg.StreamControlRequest"),ar=zt.lookupType("signal_msg.SubscribeRequest"),sr=zt.lookupType("signal_msg.SetStreamPropertiesRequest"),cr=zt.lookupType("signal_msg.UnsubscribeRequest"),ur=zt.lookupType("signal_msg.SubscriptionControlRequest"),dr=zt.lookupType("signal_msg.CreatePeerConnectionRequest"),lr=zt.lookupType("signal_msg.ClosePeerConnectionRequest"),pr=zt.lookupType("signal_msg.BatchPublishRequest"),fr=zt.lookupType("signal_msg.BatchUnpublishRequest"),vr=zt.lookupType("signal_msg.BatchSubscribeRequest"),hr=zt.lookupType("signal_msg.BatchUnsubscribeRequest"),mr=zt.lookupType("signal_msg.JoinGroupRequest"),yr=zt.lookupType("signal_msg.SetGroupPropertiesRequest"),gr=zt.lookupType("signal_msg.DismissGroupRequest"),br=zt.lookupType("signal_msg.LeaveGroupRequest"),Sr=zt.lookupType("signal_msg.SyncDataRequest"),kr=zt.lookupType("signal_msg.SyncDataByIdsRequest"),Pr=zt.lookupType("signal_msg.GroupChangeLog"),wr=zt.lookupType("signal_msg.GroupListChangeLog"),Er=zt.lookupType("signal_msg.SetParticipantPropertiesRequest"),Tr=zt.lookupType("signal_msg.QueryStreamsVerRequest"),Or=zt.lookupType("signal_msg.QueryStreamsRequest");function Ir(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ir=function(){return!!e})()}var Rr=e.getReporter().log,Ar=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Ir()?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",er.decode(t)):"serverFailover"===e?this.emit("serverFailover",tr.decode(t)):"media-message"===e?this.emit("media-message",Zt.decode(t)):"group"===e?this.emit("group",Pr.decode(t)):"group-list"===e&&this.emit("group-list",wr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;Xt.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=dr.encode(e).finish();return Rr.info("send create-peer-connection",e),this.rpc("create-peer-connection",t,e).then((function(e){return e.createPeerConnectionResponse}))}},{key:"closePeerConnection",value:function(e){var t=lr.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=vr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then((function(e){return e.errorMsg}))}},{key:"setGroupProperties",value:function(e){var t=yr.encode(e).finish();return this.rpc("set-group-properties",t,e).then((function(e){return e.setGroupPropertiesResponse}))}},{key:"batchUnSubscribe",value:function(e){var t=hr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){Rr.info("send batch-publish",e);var t=pr.encode(e).finish();return this.rpc("batch-publish",t,e).then((function(e){return e.errorMsg}))}},{key:"batchUnPublish",value:function(e){var t=fr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=rr.encode(e).finish();return this.rpc("publish",t,e).then((function(e){return e.publishResponse}))}},{key:"setParticipantProperties",value:function(e){Rr.info("send set-participant-properties",e);var t=Er.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=nr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=ir.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=or.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=sr.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=ar.encode(e).finish();return this.rpc("subscribe",t,e).then((function(e){return e.subscribeResponse}))}},{key:"unsubscribe",value:function(e){var t=cr.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=ur.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=Tr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then((function(e){return e.queryStreamsVerResponse}))}},{key:"getStreams",value:function(e){var t=Or.encode(e).finish();return this.rpc("query-streams",t,e).then((function(e){return e.queryStreamsResponse}))}},{key:"joinGroup",value:function(e){var t=mr.encode(e).finish();return this.rpc("join-group",t,e).then((function(e){return e.joinGroupResponse}))}},{key:"leaveGroup",value:function(e){var t=br.encode(e).finish();return this.rpc("leave-group",t,e).then((function(e){return e.leaveGroupResponse}))}},{key:"dismissGroup",value:function(e){var t=gr.encode(e).finish();return this.rpc("dismiss-group",t,e).then((function(e){return e.dismissGroupResponse}))}},{key:"syncData",value:function(e){var t=Sr.encode(e).finish();return this.rpc("sync-data",t,e).then((function(e){return e.syncDataResponse}))}},{key:"syncDataByIds",value:function(e){var t=kr.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(t,r){var n=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise((function(o,a){var s=n.rpcId++;n.reporter.log.info("rtc rpcId ".concat(s,":").concat(t," param====> ").concat(JSON.stringify(i||""))),n.channel.signaling.rpc(t,r,i).then((function(e){var r=$t.decode(e);r.code===qt.Result.Ok?(n.reporter.log.debug("rtc rpcId ".concat(s,":").concat(t," result====> ").concat(JSON.stringify(r))),o(r)):(n.reporter.log.debug("rtc rpcId ".concat(s,":").concat(t," error====> ").concat(JSON.stringify(r))),a(r))})).catch((function(r){n.reporter.log.error("rtc rpcId ".concat(s,":").concat(t," error====> ").concat(e.tryJsonStringify(r))),a(r)}))}))}}])}();function Cr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Cr=function(){return!!e})()}var _r=function(){function t(){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Cr()?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 Dr(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 Mr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Dr(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Dr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function xr(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 jr(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)?jr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function jr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Lr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Lr=function(){return!!e})()}var Nr={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},Vr={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},Fr=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,Lr()?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({},Vr),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,_r),u(t,[{key:"extractVideoMetrics",value:function(t){var r=this,n=Object.assign({source:this.source,trackStats:[]},Vr,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=Pe(n,this.lastVideoSendInfo);return t.forEach((function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var i=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(i.sendFrameWidth=t.frameWidth||0,i.sendFrameHeight=t.frameHeight||0,i.framesSent=t.framesSent||0,i.framesEncoded=t.framesEncoded||0,i.targetBitrate=t.targetBitrate||0,i.qpSum=t.qpSum||0,i.bytesSent=t.bytesSent||0,i.packetsSent=t.packetsSent||0,i.packetsSentForLost=i.packetsSent||0,i.sentTimestamp=t.timestamp||0,i.totalEncodeTime=t.totalEncodeTime||0,i.keyFramesEncoded=t.keyFramesEncoded||0,i.firCount=t.firCount||0,i.pliCount=t.pliCount||0,i.retransmittedBytesSent=t.retransmittedBytesSent||0,i.retransmittedPacketsSent=t.retransmittedPacketsSent||0,i.qualityLimitationReason=t.qualityLimitationReason||"",i.sendFramesPerSecond=t.framesPerSecond||0,i.sendFrameWidth>n.maxSendFrameWidth){if(n.maxSendFrameWidth=i.sendFrameWidth,!i.sendFramesPerSecond&&o){var a=Ee(i.framesSent||i.framesEncoded,o.framesSent||o.framesEncoded);i.sendFramesPerSecond=Math.round(a/u)}if(i.framesEncoded){var s=Ee(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=xr(e.trackStats.entries());try{for(n.s();!(t=n.n()).done;){var i=nt(t.value,2),o=i[0],a=i[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=Ee(a.framesSent,s.framesSent),u=Ee(a.framesEncoded,s.framesEncoded),d=Ee(a.keyFramesEncoded,s.keyFramesEncoded),l=Ee(a.retransmittedBytesSent,s.retransmittedBytesSent),p=Ee(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=Ee(a.firCount,s.firCount),v=Ee(a.pliCount,s.pliCount),h=Ee(a.packetsSent,s.packetsSent),m=Ee(a.packetsSentForLost,s.packetsSentForLost),y=Ee(a.lostTimestamp,s.lostTimestamp),g=Ee(a.sentTimestamp,s.sentTimestamp),b=Ee(a.packetsLost,s.packetsLost),S=Ee(a.totalEncodeTime,s.totalEncodeTime),k=Ee(a.qpSum,s.qpSum),P=a.qualityLimitationReason,w=a.sendFrameWidth,E=Mr(Mr({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:w,qualityLimitationReason:P},a),{},{deltaQbSum:k,deltaPacketsSent:h,deltaPacketsLost:b,deltaFramesSent:c,deltaTimestampForLost:y,deltaFramesEncoded:u,deltaKeyFramesEncoded:d,deltaFirCount:f,deltaEncodedTime:S,deltaPliCount:v,deltaTimestampForSent:g,deltaPacketsSentForLost:m,deltaRetransmittedBytesSent:l,deltaRetransmittedPacketsSent:p});r.push(E)}}catch(e){n.e(e)}finally{n.f()}return{tracksStatInfo:r,totalBytesSent:e.totalBytesSent,totalFramesEncoded:e.totalFramesEncoded||e.totalFramesSent,totalPacketsSent:e.totalPacketsSent,totalEncodedTime:e.totalEncodedTime,totalQpSum:e.totalQpSum,totalPacketsLost:e.totalPacketsLost}}},{key:"makeVideoReport",value:function(e){var t={attr_capture_frames:Math.round(e.captureFramesPerSecond),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.captureFrameWidth,"*").concat(e.captureFrameHeight,"/")};if(this.lastVideoSendInfo.timestamp){var r=this.getLayersMetricInfo(e),n=r.tracksStatInfo,i=r.totalBytesSent,o=r.totalFramesEncoded,a=r.totalEncodedTime;n.length>1&&(t.attr_stream_options+="sim:".concat(n.length,"/"));for(var s={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},c=[],u=0,d=Ee(e.timestamp,this.lastVideoSendInfo.timestamp),l=!0,p=0;p<n.length;p++){var f=n[p];s.attr_enc_key_frames_sim.push(f.deltaKeyFramesEncoded),s.attr_fir_count_sim.push(f.deltaFirCount),s.attr_pli_count_sim.push(f.deltaPliCount),s.attr_quality_limitation_reason_sim.push(f.qualityLimitationReason),s.attr_retx_bytes_sim.push(f.deltaRetransmittedBytesSent),s.attr_retx_packets_sim.push(f.deltaRetransmittedPacketsSent),s.attr_resolution_sim.push({count:f.deltaFramesSent||f.deltaFramesEncoded,index:p,resolution:"".concat(f.sendFrameWidth,"*").concat(f.sendFrameHeight)});var v=f.deltaFramesEncoded||f.deltaFramesSent;l&&(l=0===v),s.attr_encoded_framerate_sim.push(j({},p,Math.round(1e3*v/d))),s.attr_encode_qp_sim.push(j({},p,Math.round((f.deltaQbSum||0)/(v||Number.EPSILON))));var h=f.deltaTimestampForLost,m=f.deltaTimestampForSent,y=f.deltaPacketsLost,g=f.deltaPacketsSentForLost;if(y&&g&&h&&m){var b=y/h/(g/m);c.push(Math.max(Math.min(b,1),0))}}for(var S=0,k=Object.entries(s);S<k.length;S++){var P=nt(k[S],2),w=P[0],E=P[1];t[w]=E.length?JSON.stringify(E):""}var T=0,O=Ee(o,this.lastVideoSendInfo.totalFramesEncoded),I=Ee(a,this.lastVideoSendInfo.totalEncodedTime);O&&I&&(T=Math.round(1e3*I/O));var R=Ee(i,this.lastVideoSendInfo.totalBytesSent);t.attr_duration_ms=d,t.attr_bitrate=d>0?Math.min(Math.round(8*R*1e3/d),2e7):0,t.attr_enc_average_elapsed_ms=T,this.videoSendReport=t,l&&(t.attr_resolution_sim="null",t.attr_encoded_framerate_sim="null"),this.emit("video-send-stream",Object.assign({},this.videoSendReport)),c.length&&(u=Math.min(Math.round(c.reduce((function(e,t){return t+e}),0)/c.length*255),255)),this.bweReport={attr_duration_ms:d,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:u},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},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.channelCount,o=n.sampleRate;r.channels=i,r.sampleRate=o}})),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(Ee(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*Ee(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/Ee(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 Ur(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 n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Gr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Br(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Br=function(){return!!e})()}var qr={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},Hr={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},Jr=function(){function t(r){var n,i,a,s,c;o(this,t),a=this,s=l(s=t),i=d(a,Br()?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,h=r.transceivers;return i.connection=u,i.pc=u.pc,i.tranceiver=p,i.tranceivers=h,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({},Hr),i.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},i.lastAudioReceiveInfo=Object.assign({},qr),i.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},i}return f(t,_r),u(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=Object.assign({},qr,this.connection.peerConnectionStats);return n.timestamp=Date.now(),e.forEach((function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(n.bytesReceived=e.bytesReceived||0,n.packetsReceived=e.packetsReceived||0,r||(n.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0),n.packetsLost=e.packetsLost||0,n.audioLevel=e.audioLevel||0,n.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(n.audioLevel=e.audioLevel))})),n}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map((function(e){return t.extractAudioMetrics(e,!0)})),n=Object.assign({},qr,this.connection.peerConnectionStats);n.timestamp=Date.now();var i,o=Ur(r);try{for(o.s();!(i=o.n()).done;){var a=i.value;n.bytesReceived+=a.bytesReceived||0,n.packetsLost+=a.packetsLost||0,n.packetsReceived+=a.packetsReceived||0,n.audioLevel=Math.max(n.audioLevel,a.audioLevel||0),n.decodingNormal=Math.max(n.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return n.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?n.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:n.packetsReceivedForLost=n.packetsReceived||0,n}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},Hr,this.connection.peerConnectionStats);return r.timestamp=Date.now(),e.forEach((function(e){if(!e.isRemote)if(/inboundrtp|inbound-rtp/i.test(e.type))r.framesDecoded=e.framesDecoded,r.packetsReceived=e.packetsReceived||0,r.framesReceived=e.framesReceived,r.keyFramesDecoded=e.keyFramesDecoded||0,r.packetsLost=e.packetsLost||0,r.packetsLost===(t.lastVideoReceiveInfo.packetsLost||0)?r.packetsReceivedForLost=t.lastVideoReceiveInfo.packetsReceived||0:r.packetsReceivedForLost=r.packetsReceived||0,r.bytesReceived=e.bytesReceived||0,r.firCount=e.firCount||0,r.pliCount=e.pliCount||0,r.freezeCount=e.freezeCount||0,r.retransmittedBytesReceived=e.retransmittedBytesReceived||0,r.retransmittedPacketsReceived=e.retransmittedPacketsReceived||0,void 0!==e.frameHeight&&(r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0);else if(/track/i.test(e.type))r.frameWidth=e.frameWidth||0,r.frameHeight=e.frameHeight||0;else if(/codec/i.test(e.type)){var n;null!==(n=e.mimeType)&&void 0!==n&&n.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}})),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(Ee(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=Ee(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),n=Ee(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),i=Ee(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=Ee(e.timestamp,i);if(e.bytesReceived-u>=0){var v=Ee(e.packetsLost,a),h=Ee(e.packetsReceivedForLost,d),m=0;try{m=Math.round(v/h*255)}catch(e){m=0}isNaN(m)&&(m=0);var y=Ee(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:Ee(e.framesDropped,c),attr_fir_count:Ee(e.firCount,r),attr_freeze_count:Ee(e.freezeCount,o),attr_pli_count:Ee(e.pliCount,n),attr_retx_bytes:Ee(e.retransmittedBytesReceived,l),attr_retx_packets:Ee(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*Ee(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(m,255)),attr_resolution:JSON.stringify([{count:y,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},e.frameWidth&&e.frameHeight&&this.emit("video-recv-stream",Object.assign({},this.videoReceiveReport))}}this.lastVideoReceiveInfo=e}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){t.audioMetrics&&e.makeAudioReport(t.audioMetrics),t.videoMetrics&&e.makeVideoReport(t.videoMetrics)}))}},{key:"makeFirstReport",value:function(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=L(l(t.prototype),r,n))?function(e){return i.apply(n,e)}:i)([]),this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();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 Qr(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)?Qr(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Qr(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Wr(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 Kr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Wr(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Wr(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function zr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(zr=function(){return!!e})()}var $r=e.getReporter().log,Xr=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,"stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"resolutionInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"ssrc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:Date.now()}),Object.defineProperty(r,"uid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"userConfigResolution",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"signaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"_stream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"stucked",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(r,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"metricsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"audioStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"videoStatsMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"transceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var s=e.connection,c=e.stream,u=e.uid,p=e.resolutionInfo,f=e.userConfigResolution;return r.connection=s,r.resolutionInfo=p,r.userConfigResolution=f,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(ee.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=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.stream.id;return this.resolutionInfo=Zr(this.stream,e),t||(this.userConfigResolution=e),this.signaling.subscriptionControl({subscriptionId:this.id,operation:"update",updateDesc:{video:{from:r,params:this.resolutionInfo}}})}},{key:"reset",value:function(){this.connection.off("track",this.handleStreamAdd),this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.connection.reset()}},{key:"clear",value:function(){this.state!==A.End&&(this.reset(),this.state=A.End,this.emit("ended"))}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.monitor=new Jr(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 Jr(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=Pe(r,o),s=Ee(r.bytesReceived,o.bytesReceived),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,receiveBytes:r.bytesReceived,receivePackets:r.packetsReceived,receivePacketsLost:r.packetsLost,rtt:r.roundTripTime,audioLevel:Math.max(r.audioLevel,0),timestamp:r.timestamp,receiveBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=Pe(n,l),f=Ee(n.bytesReceived,l.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||n.codec,receiveResolution:{width:n.frameWidth,height:n.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(Ee(null==n?void 0:n.framesDecoded,l.framesDecoded)/p),receiveFrameRate:Math.round(Ee(null==n?void 0:n.framesReceived,l.framesReceived)/p),receiveFramesDropped:Ee(null==n?void 0:n.framesDropped,l.framesDropped),receiveBytes:n.bytesReceived,receivePackets:n.packetsReceived,receivePacketsLost:n.packetsLost,rtt:n.roundTripTime,timestamp:n.timestamp},h=this.connection.subSdpFmtpLines.some((function(e){return e.includes("64")})),m=(null===(d=this.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.source)===exports.VideoSourceInfo.CAMERA&&f>5e3&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&m?h&&v.receiveFramesDropped>0&&!ee.downlinkForbidHighProfile?this.connection.handleHighProfileFallback():this.connection.handleVideoSubStucked(this):this.stucked=m),this.videoStatsMap.set(t,v)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;null===(t=r.monitor)||void 0===t||t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;"mcu"===this.uid?(this.monitor.on("audio-net-eq",(function(t){e.reporter.metric.audioNetEQ(Kr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})),this.monitor.on("audio-recv-stream",(function(t){e.reporter.metric.audioRecvStream(Kr({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(Kr({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))})))}}])}(),Zr=function(e,t){if(!t)return null;var r=t.resolutionLevel,n=e.media.video.highestResolutionLevel;if(n&&n<r){var i=dt(n);return ut(i,re(e))}return t},en=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,a=i.error,s=i.resolutionInfo;if(a)$r.error("skip subscribe",o,a);else{var c=tn(o,s),u=c.audio,d=c.video;if(u){var l=Kr(Kr({},u),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:hn()}]});ee.audioSFU&&(l.ssrcGroup=new Array(6).fill(0).map((function(){return{ssrc:hn()}}))),r.audio.push(l)}else if(d){var p,f;r.video.push(Kr(Kr({},d),{},{trackId:null===(p=o.media)||void 0===p||null===(p=p.video)||void 0===p?void 0:p.trackId,ssrcGroup:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.ssrcGroup,subSsrcGroup:{ssrc:hn(),rtxSsrc:hn()}}))}}}}catch(e){n.e(e)}finally{n.f()}return r},tn=function(e,t){var r=e.id,n=e.media,i=n.audio,o=n.video,a={};if(i)a.audio={from:r};else if(o){var s;a.video={from:r,format:null===(s=n.video)||void 0===s?void 0:s.format,parameters:Zr(e,t)}}return a},rn=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 Xr(Kr(Kr({},r),{},{uid:s,userConfigResolution:c,resolutionInfo:c&&Zr(n,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=en(t),s.next=3,Pn(n,c,a);case 3:n.signaling.batchSubscribe({connectionId:n.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:ee.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||ne(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:r=u.value,n=r.id,i=r.msg,s=r.origin,c=a[s.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=ne(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)}}(),nn=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,wn(o,t);case 4:o.signaling.batchUnSubscribe({connectionId:o.id,audio:i,video:a}).then((function(){t.forEach((function(e){e.clear()})),e(void 0)})).catch(r);case 5:case"end":return n.stop()}}),n)})));return function(){return n.apply(this,arguments)}}()})),r.connection.addTask(n),e.abrupt("return",a);case 4:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}();function on(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 an(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?on(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):on(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return 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 n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function cn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var un=e.getReporter().log,dn={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},ln=0,pn=0,fn=0,vn=new Set,hn=function(){if(0==ln||0==pn)return 0;var e=Math.min(pn+1,1e4);do{var t=ln+(pn&fn++);if(0!=t&&!vn.has(t))return t}while(--e>0);return 0},mn=function(t,r){var n,i;if((null===(n=t.rids)||void 0===n?void 0:n.length)>1)return e.Environment.isFirefox()&&(r=kn(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},yn=function(){var e=i(x.mark((function e(r){var n,i,o,a,s,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.connection,i=r.transceiver,o=n.remoteSDP,a=n.pc,e.next=4,a.createOffer();case 4:return s=e.sent,e.next=7,a.setLocalDescription(s);case 7:return n.localSDP=t.parse(s.sdp),c=n.localSDP.media.find((function(e){return e.mid==i.mid})),u=o.media.find((function(e){return e.mid==i.mid})),mn(c,u),e.next=13,a.setRemoteDescription({type:"answer",sdp:t.write(o)});case 13:n.remoteSDP=o;case 14:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),gn=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 Ct){var r=kt(e).encodings;t.sendEncodings=r.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var i=n.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Ct&&i.sender.setParameters){var o=e.optimizationMode,s=i.sender.getParameters();s.degradationPreference=dn[o]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(un.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach((function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,un.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}}))),un.info("adjustUplinkSDPWhenPublish setParameters",s),i.sender.setParameters(s)}return a.set(e.getTrackId(),i),i})),r.next=5,o.createOffer();case 5:return d=r.sent,l=t.parse(d.sdp),r.next=9,o.setLocalDescription(d);case 9:n.localSDP=l,s.groups[0].mids=n.localSDP.groups[0].mids,p=sn(u),r.prev=12,v=x.mark((function t(){var r,n,i,o,a,c,u;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=an(an({},n),{},{ext:z(n.ext),mid:r.mid}),o=l.media.find((function(e){return e.mid==r.mid})),a=new URLSearchParams(location.search).get("startkbs"),c=new URLSearchParams(location.search).get("minkbs"),u=new URLSearchParams(location.search).get("maxkbs"),un.info("startkbs, minkbs",a,c),i.fmtp.map((function(e){if(/profile-level-id/i.test(e.config)){var t=e.config.split(";").filter((function(e){return!/x-google-start-bitrate/i.test(e)}));a&&t.push("x-google-start-bitrate=".concat(a)),c&&t.push("x-google-min-bitrate=".concat(c)),u&&t.push("x-google-max-bitrate=".concat(u)),e.config=t.join(";")}})),mn(o,i),s.media.push(i);case 12: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 window.remoteSDP=s,r.next=30,o.setRemoteDescription({type:"answer",sdp:t.write(s)});case 30:return n.remoteSDP=s,r.abrupt("return",{localSDP:n.localSDP,stream:c});case 32:case"end":return r.stop()}}),r,null,[[12,21,24,27]])})));return function(e,t){return r.apply(this,arguments)}}(),bn=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 a=e.sent,s=t.parse(a.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)}}(),Sn=function(t,r,n){var i=t.ssrc,o=t.rtxSsrc;!function(e){e.ssrc&&vn.add(e.ssrc),e.rtxSsrc&&vn.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})}))},kn=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},Pn=function(){var e=i(x.mark((function e(r,n,i){var o,a,s,c,u,d,l,p,f,v,h,m,y,g,b,S,k,P,w,E,T,O,I,R,A,C,_,D;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s=r.pc,c=r.idToTransceiverMap,u=r.remoteSDP,d=r.idToTransceiversMap,l=u.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(h=null===(v=n.audio)||void 0===v?void 0:v[0],m=h.from,ee.audioSFU){if(d.get(m)){y=sn(d.get(m));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=sn(b);try{for(S.s();!(k=S.n()).done;)k.value.direction="sendonly"}catch(e){S.e(e)}finally{S.f()}}else r.mcuAudioTranceivers=new Array(6).fill(0).map((function(e){return r.pc.addTransceiver("audio",{direction:"recvonly"})})),d.set(m,r.mcuAudioTranceivers);i[m].addTransceivers(d.get(m))}else c.get(m)||c.set(m,r.mcuAudioTranceiver),c.get(m).direction="recvonly",p.direction="sendonly",i[m].addTransceiver(c.get(m));P=sn(n.video),e.prev=6,E=x.mark((function e(){var r,n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=w.value,n=r.from,o=c.get(n)){e.next=7;break}c.set(n,s.addTransceiver("video",{direction:"recvonly"})),e.next=19;break;case 7:if("inactive"===o.direction){e.next=18;break}return o.direction="inactive",e.next=11,s.createOffer();case 11:return a=e.sent,e.next=14,s.setLocalDescription(a);case 14:return u.media.find((function(e){return e.mid==o.mid})).direction="inactive",e.next=18,s.setRemoteDescription({type:"answer",sdp:t.write(u)});case 18:c.get(n).direction="recvonly";case 19:i[n].addTransceiver(c.get(n));case 20:case"end":return e.stop()}}),e)})),P.s();case 9:if((w=P.n()).done){e.next=13;break}return e.delegateYield(E(),"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 T=e.sent,O=t.parse(T.sdp),u.groups[0].mids=O.groups[0].mids,e.next=28,s.setLocalDescription(T);case 28:r.localSDP=O,ee.audioSFU&&n.audio[0]&&(I=n.audio[0],R=I.ssrcGroup,A=I.from,d.get(A).forEach((function(e,t){var r,n=null===(r=R[t])||void 0===r?void 0:r.ssrc,i=u.media.find((function(t){var r=t.mid,n=t.type;return r==e.mid&&"audio"===n}));i||(i=an(an({},p),{},{mid:e.mid}),u.media.push(i)),i.ssrcs=En(n,f),i.direction="sendonly"}))),C=sn(n.video),e.prev=31,D=x.mark((function e(){var t,r,n,o,a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=_.value,r=t.from,n=t.subSsrcGroup,o=c.get(r),(a=u.media.find((function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r})))||((a=an({},l)).mid=o.mid,u.media.push(a)),a.direction="sendonly",i[r].ssrc=null==n?void 0:n.ssrc,Sn(n,a,f);case 8:case"end":return e.stop()}}),e)})),C.s();case 34:if((_=C.n()).done){e.next=38;break}return e.delegateYield(D(),"t2",36);case 36:e.next=34;break;case 38:e.next=43;break;case 40:e.prev=40,e.t3=e.catch(31),C.e(e.t3);case 43:return e.prev=43,C.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)}}(),wn=function(){var e=i(x.mark((function e(r,n){var i,o,a,s,c,u,d,l,p,f,v,h;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=r.pc,o=r.remoteSDP,a=[],s=sn(n);try{for(s.s();!(c=s.n()).done;)u=c.value,d=u.transceiver,l=u.transceivers,d?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=h[v],o.media.find((function(e){return e.mid==t.mid})).direction="inactive";case 3:case"end":return e.stop()}}),e)})),v=0,h=a;case 13:if(!(v<h.length)){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)}}(),En=function(t,r){return[{attribute:"msid",value:"".concat(r," v").concat(t),id:t},{attribute:"cname",value:e.createUuid(),id:t}]},Tn=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]=an(an({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[i]=an(an({},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()&&ee.simulcast&&(u.ext=u.ext.filter((function(e){return!e.uri.includes("rtp-stream-id")}))),!u.ssrcs&&"downlink"===a){var d=hn(),l=c.msidSemantic.token;u.ssrcs=En(d,l)}return n.remoteSDP=c,c},On=function(e){var t=e.localSDP,r=e.remoteSDP,n=e.sessionManager,i=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),d=z(n.sessions.values());if("downlink"===c){var l=r.media.slice(2),p=d.filter((function(e){return e instanceof Xr})),f=p.find((function(e){var t;return"admin"===(null===(t=e.stream)||void 0===t||null===(t=t.info)||void 0===t?void 0:t.owner)}));f&&!ee.audioSFU&&(a.set(f.id,i),f.addTransceiver(i));var v=[];u.forEach((function(e){var t={direction:e.direction},r=l.find((function(t){return t.type===e.type&&e.mid==t.mid})),n=p.find((function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)})),i=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&n?(a.set(n.stream.id,i),n.addTransceiver(i)):"audio"===e.type&&v.push(i))})),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var h=d.filter((function(e){return e instanceof Ln}));u.forEach((function(e){var t={direction:e.direction},r=h.find((function(t){return t.mid==e.mid}));if("sendonly"===e.direction&&r){var n=r.tracks[0],i=(null==n?void 0:n.getMediaStreamTrack())||(null==n?void 0:n.trackMediaType);if(n instanceof Ct){var s=kt(n).encodings;t.sendEncodings=s.filter((function(e){return e.activeForBitrateMap})).map((function(e){return{rid:e.rid||void 0,maxBitrate:1e3*e.maxBitrate,maxFramerate:e.maxFramerate,active:e.activeForRealuse,scaleResolutionDownBy:e.scaleResolutionDownBy}}))}var c=o.addTransceiver(i,t);a.set(n.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)}))}},In=function(e,t){if(e){var r,n=e.fmtp,i=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=sn(n);try{for(u.s();!(r=u.n()).done;){var d=r.value,l=d.config,p=d.payload,f=l.split(";");c[p]={};var v,h=sn(f);try{for(h.s();!(v=h.n()).done;){var m=nt(v.value.split("="),2),y=m[0],g=m[1];c[p][y]=g}}catch(e){h.e(e)}finally{h.f()}}}catch(e){u.e(e)}finally{u.f()}for(var b in c){var S=c[b];(t(S)||s.includes(+S.apt))&&s.push(parseInt(b))}if(s.length){for(var k=n.length-1;k>=0;k--){var P=n[k].payload;s.includes(P)&&n.splice(k,1)}for(var w=o.length-1;w>=0;w--)s.includes(o[w].payload)&&o.splice(w,1);for(var E=a.length-1;E>=0;E--)s.includes(a[E].payload)&&a.splice(E,1);e.payloads=i.split(" ").map(Number).filter((function(e){return!s.includes(e)})).join(" ")}}},Rn=function(e,t){var r=e.media.find((function(e){return"video"===e.type}));return In(r,(function(e){var r;return null===(r=e["profile-level-id"])||void 0===r?void 0:r.includes(t)})),e},An=function(e){var t=e.media.find((function(e){return"video"===e.type}));return In(t,(function(e){return e["profile-level-id"]&&!e["packetization-mode"]})),e};function Cn(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 _n(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Cn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Cn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Dn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return 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 n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Mn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function xn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(xn=function(){return!!e})()}var jn=e.getReporter().log,Ln=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,xn()?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),r.applyOptions=r.applyOptions.bind(r),r.applyOptions=Ie(r.applyOptions,1e3,!1),p.forEach((function(e){e.on(H,r.handleTracEvent)})),r.encodings=kt(p[0]).encodings,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():Fn([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:"handleRepublish",value:function(e){var t=this.connection,r=this.transceiver,n=e.getMediaStreamTrack().getSettings(),o=n.width,a=n.height,s=St(o,a);this.signaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:s});var c=function(e,t){var r=mt(e,t),n=function(n){var i=nt(yt(e,t,n,r),2);i[0];var o=1/(i[1]/t);return Math.max(o,1)};return{ld:n(ze.LD),sd:n(ze.SD),fhd:n(r)}}(o,a);t.addTask(i(x.mark((function e(){var t;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return jn.info("scales",c),(t=r.sender.getParameters()).encodings.forEach((function(e){e.scaleResolutionDownBy=c[e.rid]})),jn.info("handleRepublish setParameters",t),e.abrupt("return",r.sender.setParameters(t).then((function(){console.log(r.sender.getParameters().encodings)})));case 5:case"end":return e.stop()}}),e)}))))}},{key:"handleTracEvent",value:function(e,t){var r,n=this,i={replace:function(){return n.replaceTrack(t.getMediaStreamTrack())},mute:function(){return n.mute()},unmute:function(){return n.unmute()},republish:function(){ee.republish?n.handleRepublish(t):n.stop().then((function(){n.connection.sessionManager.channel.client.publish([t])}))},stop:function(){return n.stop()},optimizationMode:function(){return n.updateOptionzationMode()},mirror:function(){return n.handleMirror(t)}};return null===(r=i[e])||void 0===r?void 0:r.call(i)}},{key:"clear",value:function(){var e=this;this.state!==A.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach((function(t){t.off(H,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(this.reporter.log.debug(e),!(n<this.feedbackIndex||this.state!==A.Processing)){this.feedbackIndex=n;var o=this.transceiver;this.connection.addTask((function(){return new Promise((function(r){var n,a=0===i,s=!1,c=o.sender.getParameters(),u=e.map((function(e){return e.rid})),d=Dn(c.encodings);try{for(d.s();!(n=d.n()).done;){var l,p=n.value,f=Dn(e);try{for(f.s();!(l=f.n()).done;){l.value.rid!==p.rid&&p.rid||p.active||a||(p.active=!0,s=!0)}}catch(e){f.e(e)}finally{f.f()}!p.active||u.includes(p.rid)&&!a||(p.active=!1,s=!0)}}catch(e){d.e(e)}finally{d.f()}if(jn.info("encodings",c.encodings),s)return jn.info("applyOptions setParameters",c),o.sender.setParameters(c).then((function(){return yn(t).then(r)}));r()}))}))}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,n=this.transceiver,i=this.connection;if(r[0]instanceof Ct&&null!=n&&null!==(e=n.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;i.addTask((function(){var e=n.sender.getParameters();return e.degradationPreference=dn[o]||"balanced",jn.info("updateOptionzationMode setParameters",e),n.sender.setParameters(e),yn(t)}))}}},{key:"addTransceiver",value:function(e){this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.transceiver=e,this.mid||(this.mid=null==e?void 0:e.mid),this.state=A.Processing,this.feedbackIndex=-1,this.monitor=new Fr(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=Pe(r,o),s=Ee(r.bytesSent,o.bytesSent),c={codec:this.connection.peerConnectionStats.audioCodec||r.codec,sendBytes:r.bytesSent,audioLevel:Math.max(r.audioLevel,0),sendPackets:r.packetsSent,sendPacketsLost:r.packetsLost,sampleRate:r.sampleRate,channelCount:r.channels,rtt:this.connection.peerConnectionStats.roundTripTime||r.roundTripTime,timestamp:r.timestamp,sendBitrate:8*s/a};this.audioStatsMap.set(t,c)}else if(n){var u,d,l=((null===(u=this.transceiver)||void 0===u||null===(u=u.sender)||void 0===u?void 0:u.getParameters())||{}).encodings,p=void 0===l?[]:l,f=(null===(d=this.metricsMap.get(t))||void 0===d?void 0:d.videoMetrics)||{},v=Pe(n,f),h=Ee(n.totalBytesSent,f.totalBytesSent),m={codec:this.connection.peerConnectionStats.videoCodec||n.codec,sendFrameRate:Math.round(n.sendFramesPerSecond),captureFrameRate:n.captureFramesPerSecond,encodeFrameRate:n.encodeFramesPerSecond,qpSum:n.totalQpSum||0,targetBitrate:n.targetBitrate,encodeLayers:p.length,sendLayers:p.filter((function(e){return e.active})).length,outgingBitrate:n.availableOutgoingBitrate,sendResolution:{width:n.maxSendFrameWidth,height:n.maxSendFrameHeight},captureResolution:{width:n.captureFrameWidth,height:n.captureFrameHeight},sendBytes:n.totalBytesSent,sendPackets:n.totalPacketsSent,sendPacketsLost:n.totalPacketsLost,timestamp:n.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||n.roundTripTime,sendBitrate:8*h/v};this.videoStatsMap.set(t,m)}this.metricsMap.set(t,e)}},{key:"getMetrics",value:function(e){var t,r=this;return null===(t=this.connection)||void 0===t?void 0:t.getStats().then((function(){var t;return null===(t=r.monitor)||void 0===t?void 0:t.getStats().then((function(t){return r.handleMetrics(t,e)}))}))}},{key:"onMonitor",value:function(){var e=this;this.monitor.on("audio-send-stream",(function(t){e.reporter.metric.audioSendStream(_n({sessionId:e.id},t))})),this.monitor.on("video-send-stream",(function(t){e.reporter.metric.videoSendStream(_n({sessionId:e.id},t))})),this.monitor.on("bwe",(function(t){e.reporter.metric.bwe(_n({sessionId:e.id},t))}))}}])}(),Nn=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,gn(r,t);case 4:return o=e.sent,a=o.localSDP,s=o.stream,t.forEach((function(e){var t=e.getTrackId(),o=a.media.find((function(e){return e.mid==r.idToTransceiverMap.get(t).mid}));if("audio"===e.trackMediaType)i.audio=[{source:"mic",autoMix:n,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Ct){var c;i.video=i.video||[];var u=o.ssrcGroups,d=void 0===u?[]:u,l=kt(e),p=l.encodings,f=l.resolutionLevel;p.length>1&&(d=p.map((function(){return{semantics:"FID",ssrcs:"".concat(hn()," ").concat(hn())}})));var v=d.filter((function(e){return"FID"===e.semantics})).map((function(e){return{ssrc:Number(e.ssrcs.split(" ")[0]),rtxSsrc:Number(e.ssrcs.split(" ")[1])}})),h=p[p.length-1],m={trackId:e.getTrackId(),forwardOnly:e.source===exports.VideoSourceInfo.SCREENCAST,msid:s.id,mid:"".concat(o.mid),highestResolutionLevel:f,uplinkSsrcGroup:v,source:e.source||exports.VideoSourceInfo.CAMERA,streamParameters:{ssrc:null==v||null===(c=v[0])||void 0===c?void 0:c.ssrc,bitrate:"".concat(h.maxBitrate),resolution:{width:h.targetWidth,height:h.targetHeight},framerate:h.maxFramerate},ssrcParameters:v.map((function(e,t){var r;return{ssrc:e.ssrc,active:p[t].activeForBitrateMap,tlayer:1,bitrate:p[t].maxBitrate,rid:(null===(r=p[t])||void 0===r?void 0:r.rid)||void 0,maxBitrate:p[t].maxBitrate,minBitrate:p[t].minBitrate,framerate:p[t].maxFramerate,resolution:{width:p[t].targetWidth,height:p[t].targetHeight}}}))};i.video.push(m)}})),e.abrupt("return",i);case 9:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),Vn=function(e){var t,r=e.tracks,n=e.connection,o=e.labels,a=r.map((function(t){return{publication:new Ln(_n(_n({},e),{},{tracks:[t]})),track:t}})),s=new Promise((function(e,s){t=function(){var t=i(x.mark((function t(){var c,u;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,Nn(r,n,o);case 2:return c=t.sent,u={connectionId:n.id,media:c,simulcast:ee.simulcast,simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},t.abrupt("return",n.signaling.batchPublish(u).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=ie(e.track,i)})),t.abrupt("return",e(a));case 4:o=Dn(n),t.prev=5,c=x.mark((function e(){var t,r,n,i,o,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=s.value,r=t.id,n=t.origin,i=t.msg,o=a.findIndex((function(e){return e.track.getTrackId()===n.id})),c=a[o]||{},u=c.publication,"ok"===i&&u?u.initInner(r):"ok"!==i&&(a[o].error=ie(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){jn.info("batchPublishStart error",e),s(e)})));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()}));return n.addTask(t),s},Fn=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,bn(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(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 Un(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Un=function(){return!!e})()}var Gn={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},Bn=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Un()?Reflect.construct(i,[],l(n).constructor):i.apply(n,a)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},Gn)}),Object.defineProperty(r,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.pc=e.pc,r}return f(t,_r),u(t,[{key:"extractMetrics",value:function(t){var r=Object.assign({},this.connectionMetrics),n="";return t.forEach((function(t){var i;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===n)e.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/",""),r.sdpFmtpLine=t.sdpFmtpLine)}})),this.connectionMetrics=Object.assign({},r),this.connectionMetrics}},{key:"makeReport",value:function(){var e=this;this.getStats().then((function(t){e.emit("metrics",t)}))}},{key:"getStats",value:function(){var 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 qn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Hn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Hn(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Hn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Jn=function(){return!!e})()}var Yn={uplink:"",downlink:""},Qn=function(){function r(t){var n,a,s,c,u;o(this,r),a=this,s=l(s=r),n=d(a,Jn()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),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,"subSdpFmtpLines",{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,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(u=i(x.mark((function e(){var t,r=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]&&r[0],"uplink"===n.direction?(n.pc.addTransceiver("audio",{direction:"sendonly"}),n.pc.addTransceiver("video",{direction:"sendonly"})):(n.mcuAudioStream=null,n.mcuAudioTranceiver=n.pc.addTransceiver("audio",{direction:"recvonly"}),n.pc.addTransceiver("video",{direction:"recvonly"})),t&&On(n),e.next=5,n.exchangeSDP(t);case 5:n.state=C.Idle,n.enquenTask.start();case 7:case"end":return e.stop()}}),e)}))),function(){return u.apply(this,arguments)})}),Object.defineProperty(n,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;n.reporter.log.info("connectionId:".concat(n.id," ice gathering state: ").concat(t))}}),n.pc=null;var p=t.direction,f=t.sessionManager;return n.signaling=f.channel.signaling,n.sessionManager=f,n.reporter=f.reporter,n.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,n=!1,i=function(){for(;r<e&&t.length;){r++;var n=t.shift();n&&n().finally((function(){r--,i()}))}};return{add:function(e){t.push(e),n&&i()},start:function(){n=!0,i()}}}(),n.subSdpFmtpLines=[],n.direction=p,n.idToTransceiverMap=new Map,n.idToTransceiversMap=new Map,n.createPeerConnection(),n.id="".concat(n.direction,"_").concat(e.createUuid()),n}return f(r,e.EventEmitter),u(r,[{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.info("connectionId:".concat(this.id," clear RTC PeerConnection.")),this.detachEvents(),"closed"!==this.pc.signalingState&&this.pc.close(),this.pc=null)}},{key:"onTrack",value:function(e){var t=e.track,r=e.streams;"audio"===t.kind?ee.audioSFU?this.emit("track",t,r[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.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"clearPcForReoffer",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.info("connectionId:".concat(this.id,": start client reoffer")),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.info("connectionId:".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),this.reporter.log.info("connectionId:".concat(this.id," connection state changed to ").concat(r)),"failed"===r||"closed"===r?(this.clientFailoverTimer&&e.removeTimer(this.clientFailoverTimer),this.clientFailoverTimer=e.addTimer((function(){t.state!==C.New&&(t.reporter.log.info("connectionId:".concat(t.id,": emit reoffer")),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=qn(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"===Yn[this.direction]&&(Yn[this.direction]="all",a.iceTransportPolicy="all"),a.iceServers=[{urls:c,username:r,credential:n}]}return Yn[this.direction]=a.iceTransportPolicy,this.reporter.log.info("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var t=this;this.pc?this.reporter.log.warn("connectionId:".concat(this.id," A PeerConnection was created. Cannot create again for the same PeerConnectionChannel.")):(this.pc=new RTCPeerConnection(this.getPeerConnectionConfig()),this.attachEvents(),this.createPeerConnectionTimer=e.addTimer((function(){var e;"connected"===(null===(e=t.pc)||void 0===e?void 0:e.connectionState)||t.exchangeSdpTask||(t.reporter.log.info("connectionId:".concat(t.id,": emit reoffer")),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 Bn(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]=an(an({},s[c]),{},{ssrcGroups:n,ssrcs:o}))})),a))),n.pc.setLocalDescription(r).catch((function(e){throw n.reporter.log.error("connectionId:".concat(n.id," Failed to create offer or set SDP. Message: ").concat(e.message,")}")),e}))})).then((function(){n.reporter.log.info("connectionId:".concat(n.id," set local sdp success"));var c=function(r,n){var i=n.direction,o=["uplink"===i,ee.downlinkForbidHighProfile],a=t.parse(r);if(o.some((function(e){return e}))&&(a=Rn(a,"64")),ee.disableTransportCC&&"uplink"===i&&function(e){e.media.forEach((function(e){e.ext=e.ext.filter((function(e){return!e.uri.includes("transport-wide-cc")})),e.rtcpFb=e.rtcpFb.filter((function(e){return"transport-cc"!==e.type}))}))}(a),"downlink"===i&&!ee.downlinkForbidHighProfile){var s=[];a.media.find((function(e){return"video"===e.type})).fmtp.forEach((function(e){var t=e.config;t.includes("profile-level-id")&&s.push(t)})),n.subSdpFmtpLines=s}if(e.Environment.isFirefox()&&(a=An(a)),"uplink"===i&&e.Environment.isFirefox()&&ee.simulcast){var c=a.media.find((function(e){return"video"===e.type}));kn(c)}return n.localSDP=a,a}(r.sdp,n);r.sdp=t.write(c),n.offerSDP=c,r.sdp=t.write(c);var u,d={direction:"downlink"!==n.direction?"in":"out",sdpOffer:r.sdp,connectionId:n.id,isFailover:o,optionsJsonStr:JSON.stringify({supportCVO:1})};if(o){var l=t.parse(r.sdp);l.media=l.media.slice(0,2),l.groups=[{mids:"0 1",type:"BUNDLE"}],d.sdpOffer=t.write(l)}!function(e){var t=e.fn,r=e.times,n=e.interval,o=void 0===n?0:n,a=e.resolve,s=e.reject;if(!(r>0))throw new Error("invalid params times");var c=function(){var e=i(x.mark((function e(){var n,i;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=0;case 1:if(!(i<r)){e.next=22;break}return e.prev=2,e.next=5,t();case 5:return n=e.sent,null==a||a(n),e.abrupt("break",22);case 10:if(e.prev=10,e.t0=e.catch(2),i!==r-1){e.next=17;break}return null==s||s(e.t0),e.abrupt("return",e.t0);case 17:return e.next=19,Te(o);case 19:i++,e.next=1;break;case 22:return e.abrupt("return",n);case 23:case"end":return e.stop()}}),e,null,[[2,10]])})));return function(){return e.apply(this,arguments)}}();c()}({key:"createPeerConnection_".concat(n.direction),fn:(u=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(d.isFailover||!n.prevId){r.next=7;break}return r.next=5,n.stopSinglePC(!0);case 5:n.id="".concat(n.direction,"_").concat(e.createUuid()),d.connectionId=n.id;case 7:return n.prevId=n.id,r.abrupt("return",n.signaling.createPeerConnection(d).then((function(r){var i=r.sdpAnswer,a=Tn(i,n,o,Yn[n.direction]);n.pc.setRemoteDescription({sdp:t.write(a),type:"answer"}).then((function(){var e;n.reporter.log.info("connectionId:".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("connectionId:".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 u.apply(this,arguments)}),times:3,interval:2e3,reject:s,resolve:a})})).catch((function(t){var r,i;n.reporter.log.error("connectionId:".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(){return this.state===C.New?Promise.reject():(this.reporter.log.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=C.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){ee.downlinkForbidHighProfile=!0,this.reporter.log.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.reporter.log.info("connectionId".concat(this.id,": start reoffer for sub:").concat(e.id," video stucked")),this.idToTransceiverMap.delete(e.stream.id),this.sessionManager.handleStuckResubscribe([e])}}]);var n}();function Wn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Kn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Wn(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Wn(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function zn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return $n(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?$n(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function $n(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Xn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Xn=function(){return!!e})()}var Zn=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,Xn()?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:(k=i(x.mark((function e(t){var r=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=10;break}if(this.uplink){e.next=7;break}return this.uplink=new Qn({direction:t,sessionManager:this}),e.next=5,this.uplink.startSinglePC();case 5:this.uplink.on("reoffer",this.handleRepulish),this.uplink.on("ended",(function(){r.uplink=null}));case 7:return e.abrupt("return",this.uplink);case 10:if(this.downlink){e.next=16;break}return this.downlink=new Qn({direction:t,sessionManager:this}),e.next=14,this.downlink.startSinglePC();case 14:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",(function(){r.downlink=null}));case 16:return e.abrupt("return",this.downlink);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return k.apply(this,arguments)})},{key:"handleRepulish",value:(S=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:if("disconnected"!==this.channel.internalChannel.connectionState){t.next=2;break}return t.abrupt("return");case 2:n=z(this.client.localTracks),i=zn(this.sessions.values());try{for(i.s();!(o=i.n()).done;)(a=o.value)instanceof Ln&&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=7,this.reporter.trace.connectionsEvent(s,"clientReofferStart"),t.next=11,null===(c=this.uplink)||void 0===c?void 0:c.clearPcForReoffer();case 11: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=17;break}return t.next=16,this.batchPublish(n);case 16:this.reporter.log.info("".concat(this.client.userId," batchPublish finished for republish"));case 17:this.reporter.trace.connectionsEvent(s,"clientReofferSuccess"),this.reporter.log.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),t.next=28;break;case 22:t.prev=22,t.t0=t.catch(7),this.reporter.log.error("".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 28:case"end":return t.stop()}}),t,this,[[7,22]])}))),function(){return S.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(b=i(x.mark((function t(r){var n,i,o,a,s,c,u,d,l,p,f;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if("disconnected"!==this.channel.internalChannel.connectionState){t.next=2;break}return t.abrupt("return");case 2:n=[],i=zn(r);try{for(i.s();!(o=i.n()).done;)(a=o.value)instanceof Xr&&a.state===A.Processing&&(n.push({stream:a.stream,uid:a.uid,resolutionInfo:a.userConfigResolution,session:a,profileFallback:!0}),this.removeSession(a.id))}catch(e){i.e(e)}finally{i.f()}return s=n.map((function(e){return e.uid})).join(),this.client.emit("media-reconnect-start",s),this.reporter.log.info("resubscribe ".concat(s," start")),t.prev=8,t.next=11,this.batchUnscribe(n);case 11:return t.next=13,this.batchSubscribe(n);case 13:c=t.sent,u=zn(c);try{for(u.s();!(d=u.n()).done;)l=d.value,p=l.subscription,f=l.error,p&&!f&&this.handleSubscribeReoffer(p)}catch(e){u.e(e)}finally{u.f()}this.client.emit("media-reconnect-end",s),t.next=24;break;case 19:t.prev=19,t.t0=t.catch(8),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t.t0))),this.client.emit("media-reconnect-end",s),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 24:case"end":return t.stop()}}),t,this,[[8,19]])}))),function(e){return b.apply(this,arguments)})},{key:"handleResubscribe",value:(g=i(x.mark((function t(){var r,n,i,o,a,s,c,u,d,l,p,f,v,h,m,y,g=arguments;return x.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n=g.length>0&&void 0!==g[0]&&g[0],"disconnected"!==this.channel.internalChannel.connectionState){t.next=3;break}return t.abrupt("return");case 3:i=n?"server":"client",o=[],a=zn(this.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof Xr&&c.state===A.Processing&&(o.push({stream:c.stream,uid:c.uid}),this.removeSession(c.id))}catch(e){a.e(e)}finally{a.f()}return u=o.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=11,this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferStart")),t.next=15,null===(l=this.downlink)||void 0===l?void 0:l.clearPcForReoffer();case 15:if(this.downlink=null,!o.length){t.next=22;break}return t.next=19,this.batchSubscribe(o);case 19:p=t.sent,f=zn(p);try{for(f.s();!(v=f.n()).done;)h=v.value,m=h.subscription,y=h.error,m&&!y&&this.handleSubscribeReoffer(m)}catch(e){f.e(e)}finally{f.f()}case 22:this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferSuccess")),this.reporter.log.debug("".concat(this.client.userId," resubscribe ").concat(u," success")),this.client.emit("media-reconnect-end",u),t.next=33;break;case 27:t.prev=27,t.t0=t.catch(11),this.reporter.log.debug("".concat(this.client.userId," resubscribe failed for ").concat(e.tryJsonStringify(t.t0))),this.reporter.trace.connectionsEvent(d,"".concat(i,"ReofferFailed")),this.client.emit("media-reconnect-end",u),this.channel.signaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 33:case"end":return t.stop()}}),t,this,[[11,27]])}))),function(){return g.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(ee.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=zn(void 0===i?[]:i);try{var a=function(){var t,i,o=n.value,a=o.actionName,s=o.connectionId;if("reoffer"!==a)return 1;if(s===(null===(t=r.uplink)||void 0===t?void 0:t.id)){var c=r.uplink,u=r.client,d=u.userId,l=u.localTracks;r.client.emit("media-reconnect-start",d),r.reporter.trace.connectionsEvent(s,"serverReofferStart"),c.reoffer().then((function(){r.reporter.log.info("".concat(d," republish ").concat(l.map((function(e){return e.trackMediaType})).join()," success")),r.reporter.trace.connectionsEvent(s,"serverReofferSuccess"),r.client.emit("media-reconnect-end",d)})).catch((function(t){r.reporter.log.debug("".concat(r.client.userId," republish failed for ").concat(e.tryJsonStringify(t))),r.reporter.trace.connectionsEvent(s,"serverReofferFailed"),r.channel.signaling.emit("connection-state-change","disconnected",r.client.connectionState,"network_error")}))}else s===(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:e>=0||t>=0?T.GREAT:T.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(y=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=nt(e,4),n=t[0],i=t[1],o=t[2],a=t[3],s=0,c=0,u=0,d=0,l=0,p=0;if(n){var f=n.camera,v=n.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,l=Math.max(l,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,l=Math.max(l,v.rtt||0))}for(var h in i&&(c+=i.sendPacketsLost||0,s+=i.sendPackets||0,l=Math.max(l,i.rtt||0)),o&&(u+=o.receivePacketsLost||0,d+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var m=a[h],y=m.camera,g=m.auxiliary;y&&(u+=y.receivePacketsLost,d+=y.receivePackets,p=Math.max(p,y.rtt||0)),g&&(u+=g.receivePacketsLost,d+=g.receivePackets,p=Math.max(p,g.rtt||0))}var b=-1,S=-1,k={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:d};if(s){var P,w,E=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(E<0&&(E=c),k.totalUplinkPacketsSentForLost=(null===(w=r.lastChannelNetworkQuality)||void 0===w?void 0:w.totalUplinkPacketsSentForLost)||0,0!==E){var T;k.totalUplinkPacketsSentForLost=s;var O=s-((null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0);O<0&&(O=s),b=E/O}}if(d){var I,R,A,C,_=u-((null===(I=r.lastChannelNetworkQuality)||void 0===I?void 0:I.totalDownlinkPacketsLost)||0);_<0&&(_=u),k.totalDownlinkPacketsRecvForLost=(null===(R=r.lastChannelNetworkQuality)||void 0===R?void 0:R.totalDownlinkPacketsRecvForLost)||0,null===(A=r.lastChannelNetworkQuality)||void 0===A||A.totalDownlinkPacketsRecvForLost,_&&(u!==((null===(C=r.lastChannelNetworkQuality)||void 0===C?void 0:C.totalDownlinkPacketsLost)||0)&&(k.totalDownlinkPacketsRecvForLost=d),S=_/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 y.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:(m=i(x.mark((function e(t,r){var n,i,o=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=Date.now(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return i=e.sent,e.abrupt("return",Vn({uid:this.client.userId,tracks:t,connection:i,labels:r}).then((function(e){var t,r=zn(e);try{var i=function(){var e=t.value,r=e.error,i=e.publication,a=e.track;r?o.reporter.trace.publish(!1,a,"",Date.now()-n):(o.addSession(a.getTrackId(),i),o.reporter.trace.publish(!0,a,i.id,Date.now()-n),o.reporter.trace.publish(!1,a,i.id,Date.now()-n),i.on("ended",(function(){o.removeSession(i.id)})))};for(r.s();!(t=r.n()).done;)i()}catch(e){r.e(e)}finally{r.f()}})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return m.apply(this,arguments)})},{key:"batchUnPublish",value:(h=i(x.mark((function e(t){var r,n=this;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=2;break}return e.abrupt("return",Promise.resolve());case 2:return e.next=4,this.getOrCreatePeerConnection("uplink");case 4:return r=e.sent,e.abrupt("return",Fn(t,{connection:r}).then((function(){var e,r=zn(t);try{for(r.s();!(e=r.n()).done;){var i,o,a,s=e.value;n.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)),n.removeSession(s.id)}}catch(e){r.e(e)}finally{r.f()}})));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t=this,r=Date.now(),n=0,o=function(){var e=i(x.mark((function e(r){var a;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t.getOrCreatePeerConnection("downlink");case 2:return a=e.sent,e.abrupt("return",rn(r,{connection:a}).then(function(){var e=i(x.mark((function e(i){var a,s,c,u;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:for(a=new Map,s=[],c=0;c<i.length;c++)"RoomBusy"===(null===(u=i[c].error)||void 0===u?void 0:u.message)&&(s.push(r[c]),a.set(s.length-1,c));if(!(s.length&&n<=3)){e.next=12;break}return n++,e.next=7,Oe(1);case 7:if("connected"!==t.client.connectionState){e.next=12;break}return e.next=10,o(s);case 10:e.sent.forEach((function(e,t){var r=a.get(t);i[r]=e}));case 12:return e.abrupt("return",i);case 13:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 4:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();return o(e).then((function(e){var n,i=zn(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.log.error("batchSubscribe error",s,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:(v=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:return r=new Array(t.length),n=[],i={},t.forEach((function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.reporter.log.error("batchUnscribe error",o,s)):(i[null==s?void 0:s.id]=t,n.push(c))})),e.next=6,this.getOrCreatePeerConnection("downlink");case 6:return o=e.sent,e.abrupt("return",nn(n,{connection:o}).then((function(){for(var e=0,t=n;e<t.length;e++){var i=t[e];a.removeSession(i.id)}return r})));case 8:case"end":return e.stop()}}),e,this)}))),function(e){return v.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:(p=i(x.mark((function e(){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=3,this.getOrCreatePeerConnection("uplink");case 3:return this.uplink=e.sent,e.next=6,this.getOrCreatePeerConnection("downlink");case 6:this.downlink=e.sent,this.channel.signaling.on("media-message",this.handleMediaMessage),this.channel.signaling.on("serverFailover",this.handleServerFailover);case 9:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{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 Ln&&"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,h=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=h.length>0&&void 0!==h[0]?h[0]:"network",i=z(this.sessions.values()).filter((function(e){var t;return e instanceof Ln&&"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=zn(i),e.prev=9,u.s();case 11:if((d=u.n()).done){e.next=21;break}if(l=d.value,p=l.videoStatsMap.get(n)){e.next=16;break}return e.abrupt("continue",19);case 16:f=l.tracks,v=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 19:e.next=11;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(9),u.e(e.t0);case 26:return e.prev=26,u.f(),e.finish(26);case 29:return e.abrupt("return",c);case 30:case"end":return e.stop()}}),e,this,[[9,23,26,29]])}))),function(){return 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,f=arguments;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=f.length>0&&void 0!==f[0]?f[0]:"network",r=z(this.sessions.values()).filter((function(e){var t;return e instanceof Xr&&"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=zn(r),e.prev=6,i.s();case 8:if((o=i.n()).done){e.next=17;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,d=s.stream,l=c.get(t)){e.next=13;break}return e.abrupt("continue",15);case 13:p=(null===(a=d.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",n[u]=Kn(Kn({},n[u]||{}),{},j({},p,l));case 15:e.next=8;break;case 17:e.next=22;break;case 19:e.prev=19,e.t0=e.catch(6),i.e(e.t0);case 22:return e.prev=22,i.f(),e.finish(22);case 25:return e.abrupt("return",n);case 26:case"end":return e.stop()}}),e,this,[[6,19,22,25]])}))),function(){return 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 Xr&&"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 Ln&&e.state===A.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA})),i=zn(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,h,m,y,g,b,S,k}();function ei(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ti(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ti(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ti(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ri=function(){return!!e})()}var ni={name:"name"},ii=function(){function t(e){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,ri()?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.participants,i=r.id;n.some((function(t){return t.pid===e}))&&t.add(i)})),t}},{key:"parseGroup",value:function(e){var t,r=this,n=e.id,i=e.properties,o=e.participants;return{id:n,name:(null==i||null===(t=i.find((function(e){return"name"===e.key})))||void 0===t?void 0:t.value)||"",joined:o.some((function(e){return e.pid===r.channel.userManager.currentPid})),users:o.map((function(e){return{userId:e.uid,userData:e.userData}}))}}},{key:"groupList",get:function(){var e=this,t=[];return this.groups.forEach((function(r){t.push(e.parseGroup(r))})),t}},{key:"init",value:function(e,t){this.listVer=t,this.groupIds=new Set(e),this.batchSyncGroup(e),this.observerAllGroup(),this.channel.signaling.on("group-list",this.handleGroupListEvents),this.channel.signaling.on("group",this.handleGroupEvents),this.channel.signaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.channel.signaling.off("group",this.handleGroupEvents),this.channel.signaling.off("group-list",this.handleGroupListEvents),this.channel.signaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(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:qt.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!==qt.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=i.updateAction,a=i.id;o===qt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===qt.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!==qt.OptType.OPT_TYPE_ADD||u){if(s===qt.OptType.OPT_TYPE_REMOVE&&u){var d,l=null==u||null===(d=u.audioInfo)||void 0===d||null===(d=d.audio)||void 0===d?void 0:d.id;this.groups.delete(i),this.emit("group","remove",this.parseGroup(u),l)}else if(s===qt.OptType.OPT_TYPE_UPDATE){var p=c.updateAction,f=c.participants;if(u&&(u.ver+1===o||r)){if(p===qt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var v,h=u.participants.map((function(e){return e.pid})),m=ei(f);try{for(m.s();!(v=m.n()).done;){var y=v.value;h.includes(y.pid)||(u.participants.push(y),this.emit("group","user-join",i,{userId:y.uid,userData:y.userData}))}}catch(e){m.e(e)}finally{m.f()}}else if(p===qt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var g=f.map((function(e){return e.pid})),b=z(u.participants);u.participants=u.participants.filter((function(e){return!g.includes(e.pid)})),b.forEach((function(e){g.includes(e.pid)&&t.emit("group","user-leave",i,{userId:e.uid,userData:e.userData})}))}else if(p===qt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.channel.reporter.log.debug("group ".concat(i," audioStream lost"));else if(p===qt.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.channel.reporter.log.debug("group ".concat(i," audioStream recover"));else if(p===qt.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(ni[e.key]),value:e.value})}));else if(p===qt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var S,k=c.properties.map((function(e){return e.key}));u.properties=null===(S=u.properties)||void 0===S?void 0:S.filter((function(e){var t=e.key;return!k.includes(t)})),c.properties.forEach((function(e){t.emit("group","info-updated",i,{key:"remove-".concat(ni[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:qt.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then((function(n){var i=n.fullSync.groupData.groupInfos,o=(void 0===i?[]:i)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],d=new Map(((null==r?void 0:r.properties)||[]).map((function(e){return[e.key,e.value]}))),l=u.map((function(e){return e.pid})),p=a.map((function(e){return e.pid})),f=c.filter((function(e){return e.value!==d[e.key]})),v=c.filter((function(e){return!d.has(e.key)})),h=a.filter((function(e){return!l.includes(e.pid)})),m=u.filter((function(e){return!p.includes(e.pid)}));h.length&&t.handleGroupEvents({id:e,type:qt.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:qt.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:h}},!0),m.length&&t.handleGroupEvents({id:e,ver:o.ver,type:qt.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:qt.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:m}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:qt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:qt.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:qt.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:qt.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:qt.OptType.OPT_TYPE_REMOVE})}))}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.channel.signaling.syncDataByIds({type:qt.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:qt.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:qt.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)})),s.length&&s.forEach((function(t){e.handleGroupListEvents({ver:n,updateOpt:{updateAction:qt.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)}))}))}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,n=e.groupVer,i=void 0===n?[]:n;this.listVer<r&&(this.syncGroupList(),this.listVer=r),i.forEach((function(e){var r=e.id,n=e.ver,i=t.groups.get(r);(null==i?void 0:i.ver)<n&&(t.syncGroup(r),i.ver=n)}))}}])}();function oi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(oi=function(){return!!e})()}var ai=function(){function t(e,r){var n,i,a,s;o(this,t),i=this,a=l(a=t),n=d(i,oi()?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});var c=e.user;return n.userId=c,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]=we(n[D.UPLINK]),n[D.DOWNLINK]=we(n[D.DOWNLINK]),t=n.join("")}t!==(null===(r=this.properties)||void 0===r?void 0:r[q])&&(this.properties[q]=t)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,n=e.ver,i=JSON.parse(r||"{}");this.id=t,this.userName=i.__nick,this.version=n,this.properties=i,this.updateNetworkOfUser(i[q])}},{key:"getRemoteVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,n=JSON.parse(e.stream.info.attributesJsonStr),i=oe(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 si(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return ci(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ci(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function ci(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function ui(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ui=function(){return!!e})()}var di=function(){function t(e,r){var n,i,a,s;return o(this,t),i=this,a=l(a=t),n=d(i,ui()?Reflect.construct(a,[],l(i).constructor):a.apply(i,s)),Object.defineProperty(n,"channel",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(n,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"currentPid",{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,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.users=new Map,n.channel=e,n.reporter=e.reporter,n.handleEvent=n.handleEvent.bind(n),n.streamManager=r,n}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=si(e);try{for(n.s();!(r=n.n()).done;){var i=r.value,o=new ai(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,r){var n=this;if(this.reporter.log.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var i=new ai(t,this.channel);this.users.set(t.user,i),this.emit("user","join",i)}else if("leave"===e){var o=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",o)}else if("update"===e){var a=this.users.get(t.user);null==a||a.update(t)}else if("participant-replace"===e){var s=new Set(null==r?void 0:r.map((function(e){return e.id})));z(this.streamManager.streams.values()).filter((function(e){var t;return s.has(null==e||null===(t=e.info)||void 0===t?void 0:t.owner)})).map((function(e){return e.id})).forEach((function(e){return n.streamManager.remove(e,!0)}));var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new ai(t,this.channel);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.channel.signaling.setParticipantProperties({participantId:this.currentPid,roomId:this.channel.roomId,propertiesJsonStr:JSON.stringify(j({},q,e))})}}])}();function li(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return pi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?pi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function pi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function fi(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 vi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?fi(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):fi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function hi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(hi=function(){return!!e})()}var mi=function(){function t(e){var r,n,i,a;o(this,t),n=this,i=l(i=t),r=d(n,hi()?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.signaling,c=e.reporter;return r.signaling=s,r.reporter=c,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","highestResolutionLevel"]}[o];u.length&&!u.includes(s.field)||this.reporter.log.info("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,h=s.streamVer,m=s.propertiesJsonStr,y=s.highestResolutionLevel,g=this.streams.get(i);if(g){h!==G&&(g.version=h);var b=g.media,S=b.audio,k=b.video,P=g.info.owner;if("audio.status"===l||"video.status"===l){var w;"audio.status"===l?(w="audio",S.status=p):"video.status"===l&&(w="video",k.status=p),this.reporter.trace.streamsEvent(i,"".concat(w," ").concat(p));var E="active"===p?"unmute":"mute";this.emit("stream","update",{owner:P,id:i,updateStatus:"".concat(E,"-").concat(w)})}else if("activeInput"===l){var T=[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(T),l),this.emit("stream","volumeActive",{owners:T})}else if("properties"==l){var O,I=JSON.parse(m);g.info.attributesJsonStr=JSON.stringify(vi(vi({},JSON.parse(g.info.attributesJsonStr)),I));var R=(null===(O=g.media)||void 0===O||null===(O=O.video)||void 0===O?void 0:O.source)===e.VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:P,id:i,properties:I,auxiliary:R})}else"highestResolutionLevel"===l&&(g.media.video.highestResolutionLevel=y,this.emit("stream","update",{owner:P,id:i,highestResolutionLevel:y}))}}r||c<=this.totalVer&&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=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:n=e.sent,i=n.streamVersions,o=n.totalVer,a=z(this.streams.keys()).filter((function(e){return!e.includes("vad")})),s=li(i),e.prev=9,s.s();case 11:if((c=s.n()).done){e.next=19;break}if(u=c.value,d=u.streamId,l=u.streamVer,!d.includes("vad")){e.next=15;break}return e.abrupt("continue",17);case 15:(p=this.streams.get(d))?p&&p.version!==l&&t.push(d):(r.push(d),t.push(d));case 17:e.next=11;break;case 19:e.next=24;break;case 21:e.prev=21,e.t0=e.catch(9),s.e(e.t0);case 24:return e.prev=24,s.f(),e.finish(24);case 27:if(f=i.map((function(e){return e.streamId})),a.filter((function(e){return!f.includes(e)})).forEach((function(e){v.handleEvent({status:"remove",streamId:e,stream:v.streams.get(e),totalVer:o},!0)})),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=34;break}return e.abrupt("return");case 34:this.signaling.getStreams({streamIds:t}).then((function(e){var n,i=e.totalVer,o=e.streams,a=new Map,s=li(v.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=li(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;v.streams.has(l.id)?v.streams.set(l.id,l.stream):a.set(l.id,l.stream)}}catch(e){d.e(e)}finally{d.f()}for(var p=t.map((function(e){return a.get(e)})).filter((function(e){return!!e})).sort((function(e,t){return e.version-t.version})),f=0;f<p.length;f++){var h=p[f];r.includes(h.id)&&v.handleEvent({status:"add",streamId:h.id,stream:h,totalVer:i},!0)}a.clear(),v.totalVer=i}));case 35:case"end":return e.stop()}}),e,this,[[9,21,24,27]])}))),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}();function yi(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 gi(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)?gi(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function gi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function bi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Si(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?bi(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):bi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function ki(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(ki=function(){return!!e})()}var Pi=function(){function t(n,i){var a,s,c,u;return o(this,t),s=this,c=l(c=t),a=d(s,ki()?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?ut(a.defaultVideoStreamType,re(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.streams,o=t.streamsVer,s=t.groupList,c=t.groupListVer;a.streamManager.init(i,o),a.groupManager.init(s,c),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,sdkVersion:U}),a.signaling=new Ar(a.internalChannel),a.client=n,a.micMixedGroups=new Set,a.groupManager=new ii(a),a.streamManager=new mi(a),a.userManager=new di(a,a.streamManager),a.sessionManager=new Zn(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 Ln})).map((function(e){return e.tracks[0]}))}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map((function(t){return Si(Si({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})}))}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,n=t.owner,i=t.mediaType,o=t.auxiliary,a=t.owners,s=t.updateStatus,c=t.properties,u=t.highestResolutionLevel,d=this.internalChannel.userManager.participants,l=d.get(n),p=this.userManager.users.get(null==l?void 0:l.user),f=n===this.userManager.currentPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,i,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===i&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stop(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stop(),p.videoTrack=null)),this.client.emit("user-unpublished",p,i,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.userManager.currentUid,s);else if(null!=(null==c?void 0:c.mirror)){var v=o?p.auxiliaryTrack:p.videoTrack;null==v||v.setSourceMirror(c.mirror)}else if(null!=u){var h=this.sessionManager.getSessionByStreamId(r);if(!h)return;h.stream.media.video.highestResolutionLevel=u;var m=h.userConfigResolution,y=h.resolutionInfo;if(u>=m.resolutionLevel&&m.resolutionLevel>y.resolutionLevel)h.applyOptions(m,!0);else if(u<m.resolutionLevel){var g=ut(dt(u),re(h.stream));h.applyOptions(g,!0)}}}else if("volumeActive"===e){var b=a.map((function(e){return d.get(e)})).map((function(e){return null==e?void 0:e.user})).filter((function(e){return!!e}));this.client.emit("volume-indicator",b)}}},{key:"handleGroupEvent",value:function(e,t,r){if("add"===e)this.client.emit("group-add",t);else if("remove"===e)this.micMixedGroups.delete(t.id),r===this.subscribedAudioStream&&(this.remoteAudioTrack.stop(),this.remoteAudioTrack=null,this.updateSubscribedAudioStream(!1,r)),this.client.emit("group-remove",t);else if("user-join"===e)this.client.emit("group-user-join",t,r);else if("user-leave"===e)this.client.emit("group-user-leave",t,r);else if("info-updated"===e){var n=r.key,i=r.value;this.client.emit("group-info-updated",t,n,i)}}},{key:"handleUserEvent",value:function(e,t){"join"===e?(this.client.emit("user-joined",t),t.hasVideo&&this.client.emit("user-published",t,"video"),t.hasAudio&&this.client.emit("user-published",t,"audio"),t.hasAuxiliary&&this.client.emit("user-published",t,"video",!0)):"leave"===e&&this.client.emit("user-left",t)}},{key:"getStream",value:function(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"mcu"===i?c.find((function(e){var t=e.info.owner,r=e.type;return"admin"===t&&"mixed"===r})):c.find((function(t){var r=t.media.video;return(null==r?void 0:r.source)===(o?e.VideoSourceInfo.SCREENCAST:e.VideoSourceInfo.CAMERA)}))}},{key:"join",value:(p=i(x.mark((function e(t){var r,n,i,o,a,s;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.reporter.log.info("dingrtc channel join",t,ee.gslb[0]),e.next=3,this.signaling.join(t,ee.gslb[0]);case 3:return n=e.sent,i=n.joinResponse,o=n.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(ee.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=i.room.id,c=i.room.ssrcMask,u=i.room.ssrcClientSequence,d=void 0,d=Math.log2(c+1),u>2147483647>>d||(pn=c,ln=(u<<d|2147483648)>>>0),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:i.id}),o&&o.uis&&this.setIceConfig(o.uis),e.next=13,this.sessionManager.start();case 13:return this.handleJoinResponse(i),e.abrupt("return",i);case 15:case"end":return e.stop()}var c,u,d}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"setIceConfig",value:function(e){var t=e.iceServerList,r=void 0===t?[]:t;e.level&&(e.iceServerList=r.filter((function(e){return/([0-9]{1,3}\.){3}[0-9]{1,3}/i.test(e)})),this.iceConfig=e)}},{key:"clear",value:function(){var e;this.userManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stop(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.userManager.off("user",this.handleUserEvent),this.groupManager.off("group",this.handleGroupEvent)}},{key:"leave",value:function(){if("disconnected"!==this.internalChannel.connectionState)return this.reporter.trace.leave(),this.signaling.leave()}},{key:"publish",value:(c=i(x.mark((function e(t){var r,n,i,o;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,n=this.groupManager,i=this.groups,o=[],i.some((function(e){return e.joined}))?o.push.apply(o,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})))):o.push("common"),e.abrupt("return",this.sessionManager.batchPublish(t,o));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return c.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 Ln&&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=oe(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),i||t.once("audio-first-frame",(function(){r.remoteAudioTrack.emit("first-frame-decoded")})),this.remoteAudioTrack}return n.getRemoteVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(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=e.auxiliary,a=e.uid,s=n[t],c=s.error,u=s.subscription;i.push({uid:a,auxiliary:o,error:c,track:r.getRemoteTrack(e,u)})})),e.abrupt("return",i);case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}()));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(e){var t,r=this,n=[],i=yi(e);try{for(i.s();!(t=i.n()).done;){var o=t.value,a=this.handleSubscribeParam(Si(Si({},o),{},{action:"unsubscribe"})),s=a.session,c=a.stream,u=a.user,d=a.uid;this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:d}),c&&n.push(Si({stream:c,user:u,session:s},o))}}catch(e){i.e(e)}finally{i.f()}return n.length?this.sessionManager.batchUnscribe(n).then((function(e){for(var t=0,i=n;t<i.length;t++){var o,a=i[t],s=a.mediaType,c=a.user,u=a.auxiliary;if("audio"===s)r.updateSubscribedAudioStream(!1,""),null===(o=r.remoteAudioTrack)||void 0===o||o.stop(),r.remoteAudioTrack=null;else if(u){var d;null===(d=c.auxiliaryTrack)||void 0===d||d.stop(),c.auxiliaryTrack=null}else{var l;null===(l=c.videoTrack)||void 0===l||l.stop(),c.videoTrack=null}}return e})):Promise.resolve()}},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(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.updateSubscribedAudioStream(!0,n.id),r.remoteAudioTrack=oe(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.updateSubscribedAudioStream(!1,""),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=ut(t,re(n));return i.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,n=e.publishAudioToGroup;return this.groupManager.join(e).then((function(e){var i=e.joinGroupAudioSuccess;n&&i&&t.micMixedGroups.add(r)}))}},{key:"leaveGroup",value:function(e){var t=this,r=e.groupId;return this.groupManager.leave(e).then((function(){t.micMixedGroups.delete(r)}))}},{key:"dismissGroup",value:function(e){var t=this;return this.groupManager.dismiss(e).then((function(){t.micMixedGroups.delete(e)}))}},{key:"mixGroupAudio",value:function(e,t,r){return this.signaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(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=!(a.length>2&&void 0!==a[2])||a[2],i=[],null!=r&&i.push(this.groupManager.groups.get(r).audioInfo.label),!this.localTracks.includes(t)){e.next=18;break}if(o=this.streamManager.getStreamByTrackId(t.getTrackId()),null==r){e.next=14;break}return e.next=8,this.mixGroupAudio(o.id,i[0],"mix");case 8:if(this.micMixedGroups.add(r),!n){e.next=12;break}return e.next=12,this.mixGroupAudio(o.id,"common","unmix");case 12:e.next=16;break;case 14:return e.next=16,this.mixGroupAudio(o.id,"common","mix");case 16:e.next=22;break;case 18:return n||i.push("common"),e.next=21,this.sessionManager.batchPublish([t],i);case 21:this.micMixedGroups.add(r);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t){return 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}();function wi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(wi=function(){return!!e})()}var Ei={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},Ti=function(){function e(t){var r,n,a,s,c;return o(this,e),n=this,a=l(a=e),r=d(n,wi()?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,o,a;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,n=t.audioLevel,e.next=6,r.client.getRemoteAudioStats();case 6:i=e.sent,o=i.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,n||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:Ee(a.timestamp,r.audioDeviceBufferInfo.timestamp),attr_play_level:Math.round(32767*a.maxPlayLevel),attr_rec_level:Math.round(32767*a.maxRecLevel)},r.emit("audio-device-buffer",Object.assign({},r.audioDeviceBufferReport))),r.audioDeviceBufferInfo=a;case 11:case"end":return e.stop()}}),e)}))),function(){return c.apply(this,arguments)})}),r.audioDeviceBufferReport={attr_duration_ms:0,attr_rec_level:0,attr_play_level:0},r.audioDeviceBufferInfo=Object.assign({},Ei),r.client=t,r}return f(e,_r),u(e)}();function Oi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Ii(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Oi(Object(r),!0).forEach((function(t){j(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Oi(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function Ri(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Ai(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Ai(e,t):void 0}}(e))||t){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function Ai(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function Ci(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Ci=function(){return!!e})()}var _i=function(){function t(){var r,n,i,a;return o(this,t),n=this,i=l(i=t),r=d(n,Ci()?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 Pi(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:"emit",value:function(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];var o,a,s,c,u,d;"network-quality"!==e&&"volume-indicator"!==e&&(o=this.reporter.log).info.apply(o,["client emit event",e].concat(n));return(a=t,s="emit",c=this,d=L(l(1&(u=3)?a.prototype:a),s,c),2&u&&"function"==typeof d?function(e){return d.apply(c,e)}:d)([e].concat(n))}},{key:"join",value:function(t){var r=this;return this.reporter.log.info("join",t),this.addEventListeners(),this.channel.join(t).then((function(n){var i;return r.channelName=t.channel,r.monitor=new Ti(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 At&&!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=Ri(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){this.reporter.log.info("unpublish",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,i),"connected"===this.connectionState){t.next=3;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 3:return t.abrupt("return",this.channel.batchSubscribe([{uid:r,mediaType:n,action:"subscribe",auxiliary:i}]).then((function(e){var t=e[0],r=t.error,n=t.track;if(r)throw r;return n})));case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"batchSubscribe",value:function(t){if(this.reporter.log.info("batchSubscribe",t),Array.isArray(t)&&t.length){if("connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);return this.channel.batchSubscribe(t.map((function(e){return Ii(Ii({},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.batchUnsubscribe([{uid:t,auxiliary:n,mediaType:r,action:"unsubscribe"}]).then((function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"batchUnsubscribe",value:function(t){if(this.reporter.log.info("batchUnsubscribe",t),Array.isArray(t)&&t.length)return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel)):this.channel.batchUnsubscribe(t.map((function(e){return Ii(Ii({},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,r);var i=this.remoteUsers.find((function(t){return t.userId===e}));return null!=i&&i.relatedStreams?this.channel.setRemoteStreamType(e,t,r).then((function(){n.emit("stream-type-changed",e,t,r)})):(this.reporter.log.warn("".concat(e," videoTrack not existed")),Promise.reject("viedoTrack doesnt exiested"))}},{key:"getRemoteVideoStats",value:function(){return this.channel.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.channel.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach((function(t){var r,n,i=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==i||null===(r=i[q])||void 0===r?void 0:r[D.DOWNLINK])||0),uplinkNetworkQuality:Number((null==i||null===(n=i[q])||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||"")),"disconnected"===e&&this.init(),this.emit("connection-state-change",e,t,r)}},{key:"sendClientStatToRemote",value:function(){var t=this,r=this.clientStatSync.join("");if(r!==this.currentClientState){var n=we(null,r[D.UPLINK]),i=we(null,this.currentClientState[D.UPLINK]),o=we(null,r[D.DOWNLINK]),a=we(null,this.currentClientState[D.DOWNLINK]);n===i&&o===a||this.channel.userManager.setParticipantProperties(r).catch((function(r){t.reporter.log.debug("setParticipantProperties error ".concat(e.tryJsonStringify(r)))})),this.currentClientState=r}}},{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){this.reporter.log.info("joinGroup",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.reporter.log.info("leaveGroup",e),this.channel.leaveGroup({groupId:e,publishAudioToChannel:!1})}},{key:"setGroupName",value:function(t,r){this.reporter.log.info("setGroupName",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.reporter.log.info("subscribeGroup",e),this.channel.subscribeGroup(e)}},{key:"unsubscribeGroup",value:function(e){return this.reporter.log.info("unsubscribeGroup",e),this.channel.unsubscribeGroup(e)}},{key:"mixAudioToGroup",value:function(t,r,n){if(this.reporter.log.info("mixAudioToGroup",t,r,n),"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.reporter.log.info("dismissGroup",e),this.channel.dismissGroup(e)}},{key:"register",value:function(e){this.reporter.log.info("register",e),e.attach(this.channel.internalChannel,this.channel)}},{key:"ungister",value:function(e){this.reporter.log.info("ungister",e),e.detach(this.channel.internalChannel)}}]);var r,n}(),Di=function(){var e=i(x.mark((function e(t){var r;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:window.addEventListener("offline",(function(){t.info("browser offline event")})),window.addEventListener("online",(function(){t.info("browser online event")})),r=function(){"visible"===document.visibilityState?t.info("page changed to visible"):t.info("page changed to invisible")},document.addEventListener("visibilitychange",r),window.addEventListener("blur",(function(){t.info("page blurred")})),window.addEventListener("focus",(function(){t.info("page focused")}));case 6:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function Mi(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(Mi=function(){return!!e})()}Ve();var xi=e.getReporter().log;xi.info("sdk version",U),xi.info("userAgent",navigator.userAgent),xi.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),Di(xi);var ji=function(){function t(){var r,n,i,a;if(o(this,t),n=this,i=l(i=t),r=d(n,Mi()?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=U,!Y.checkSupported())return d(r);var s=fe.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 xi.info("createClient"),new _i}},{key:"checkSystemRequirements",value:function(){return xi.info("checkSystemRequirements"),Y.checkSupported()}},{key:"getSupportedCodec",value:function(){return xi.info("getSupportedCodec"),Y.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return xi.info("createCameraVideoTrack",e),jt(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return xi.info("createMicrophoneAudioTrack",e),xt(e)}},{key:"createCustomVideoTrack",value:function(e){return xi.info("createCustomVideoTrack",e),Vt(e)}},{key:"createCustomAudioTrack",value:function(e){return xi.info("createCustomAudioTrack",e),Ft(e)}},{key:"createScreenVideoTrack",value:function(e){return xi.info("createScreenVideoTrack",e),Lt(e)}},{key:"createMicrophoneAndCameraTracks",value:(n=i(x.mark((function e(t,r){return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return xi.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",Nt(t,r));case 2:case"end":return e.stop()}}),e)}))),function(e,t){return n.apply(this,arguments)})},{key:"getCameras",value:function(){return xi.info("getCameras"),fe.getCameras()}},{key:"getDevices",value:(r=i(x.mark((function e(){var t;return x.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return xi.info("start getDevices"),e.prev=1,e.next=4,fe.getDevices();case 4:return t=e.sent,xi.info("getDevices suc",t),e.abrupt("return",t);case 9:return e.prev=9,e.t0=e.catch(1),xi.info("error getDevices ",e.t0),e.abrupt("return",e.t0);case 13:case"end":return e.stop()}}),e,null,[[1,9]])}))),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return xi.info("getPlaybackDevices"),fe.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return xi.info("getMicrophones"),fe.getMicrophones()}},{key:"setLogLevel",value:function(t){e.setLogLevel(t),xi.info("setLogLevel",t)}},{key:"setClientConfig",value:function(e){xi.info("setClientConfig",e),ee.setClientConfig(e)}}]);var r,n}(),Li=new ji;Object.defineProperty(exports,"ErrorCodeAndMsgMap",{enumerable:!0,get:function(){return e.ErrorCodeAndMsgMap}}),exports.FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},exports.default=Li;