dingrtc 3.9.21 → 3.9.22-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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 i(e,t,r,i,n,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(i,n)}function n(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var a=e.apply(t,r);function s(e){i(a,n,o,s,c,"next",e)}function c(e){i(a,n,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 i=r.call(e,t);if("object"!=a(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==a(t)?t:t+""}function c(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,s(i.key),i)}}function u(e,t,r){return t&&c(e.prototype,t),r&&c(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function d(e,t){if(t&&("object"==a(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&p(e,t)}function v(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var m,h={exports:{}},g={exports:{}};(m=g).exports=function(e,t){this.v=e,this.k=t},m.exports.__esModule=!0,m.exports.default=m.exports;var b=g.exports,y={exports:{}},k={exports:{}};!function(e){function t(r,i,n,o){var a=Object.defineProperty;try{a({},"",{})}catch(r){a=0}e.exports=t=function(e,r,i,n){function o(r,i){t(e,r,function(e){return this._invoke(r,i,e)})}r?a?a(e,r,{value:i,enumerable:!n,configurable:!n,writable:!n}):e[r]=i:(o("next",0),o("throw",1),o("return",2))},e.exports.__esModule=!0,e.exports.default=e.exports,t(r,i,n,o)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(k);var S=k.exports;!function(e){var t=S;function r(){
|
|
2
2
|
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
|
|
3
|
-
var i,n,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.toStringTag||"@@toStringTag";function c(e,r,o,a){var s=r&&r.prototype instanceof d?r:d,c=Object.create(s.prototype);return t(c,"_invoke",function(e,t,r){var o,a,s,c=0,d=r||[],l=!1,p={p:0,n:0,v:i,a:f,f:f.bind(i,4),d:function(e,t){return o=e,a=0,s=i,p.n=t,u}};function f(e,t){for(a=e,s=t,n=0;!l&&c&&!r&&n<d.length;n++){var r,o=d[n],f=p.p,v=o[2];e>3?(r=v===t)&&(s=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=i):o[0]<=f&&((r=e<2&&f<o[1])?(a=0,p.v=t,p.n=o[1]):f<v&&(r=e<3||o[0]>t||t>v)&&(o[4]=e,o[5]=t,p.n=v,a=0))}if(r||e>1)return u;throw l=!0,t}return function(r,d,v){if(c>1)throw TypeError("Generator is already running");for(l&&1===d&&f(d,v),a=d,s=v;(n=a<2?i:s)||!l;){o||(a?a<3?(a>1&&(p.n=-1),f(a,s)):p.n=s:p.v=s);try{if(c=2,o){if(a||(r="next"),n=o[r]){if(!(n=n.call(o,s)))throw TypeError("iterator result is not an object");if(!n.done)return n;s=n.value,a<2&&(a=0)}else 1===a&&(n=o.return)&&n.call(o),a<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=i}else if((n=(l=p.n<0)?s:e.call(t,p))!==u)break}catch(e){o=i,a=1,s=e}finally{c=1}}return{value:n,done:l}}}(e,o,a),!0),c}var u={};function d(){}function l(){}function p(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),v=p.prototype=d.prototype=Object.create(f);function m(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,t(e,s,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,t(v,"constructor",p),t(p,"constructor",l),l.displayName="GeneratorFunction",t(p,s,"GeneratorFunction"),t(v),t(v,s,"Generator"),t(v,a,function(){return this}),t(v,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:m}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(y);var P=y.exports,T={exports:{}},w={exports:{}},E={exports:{}};!function(e){var t=b,r=S;e.exports=function e(i,n){function o(e,r,a,s){try{var c=i[e](r),u=c.value;return u instanceof t?n.resolve(u.v).then(function(e){o("next",e,a,s)},function(e){o("throw",e,a,s)}):n.resolve(u).then(function(e){c.value=e,a(c)},function(e){return o("throw",e,a,s)})}catch(e){s(e)}}var a;this.next||(r(e.prototype),r(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(e,t,r){function i(){return new n(function(t,i){o(e,r,t,i)})}return a=a?a.then(i,i):i()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports}(E);var I=E.exports;!function(e){var t=P,r=I;e.exports=function(e,i,n,o,a){return new r(t().w(e,i,n,o),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports}(w);var M=w.exports;!function(e){var t=M;e.exports=function(e,r,i,n,o){var a=t(e,r,i,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports}(T);var O=T.exports,R={exports:{}};!function(e){e.exports=function(e){var t=Object(e),r=[];for(var i in t)r.unshift(i);return function e(){for(;r.length;)if((i=r.pop())in t)return e.value=i,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports}(R);var A=R.exports,x={exports:{}},C={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}(C);var _=C.exports;!function(e){var t=_.default;e.exports=function(e){if(null!=e){var r=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],i=0;if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}}}throw new TypeError(t(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports}(x);var D=x.exports;!function(e){var t=b,r=P,i=O,n=M,o=I,a=A,s=D;function c(){var u=r(),d=u.m(c),l=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var f={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(i){t||(t={stop:function(){return r(i.a,2)},catch:function(){return i.v},abrupt:function(e,t){return r(i.a,f[e],t)},delegateYield:function(e,n,o){return t.resultName=n,r(i.d,s(e),o)},finish:function(e){return r(i.f,e)}},r=function(e,r,n){i.p=t.prev,i.n=t.next;try{return e(r,n)}finally{t.next=i.n}}),t.resultName&&(t[t.resultName]=i.v,t.resultName=void 0),t.sent=i.v,t.next=i.n;try{return e.call(this,t)}finally{i.p=t.prev,i.n=t.next}}}return(e.exports=c=function(){return{wrap:function(e,t,r,i){return u.w(v(e),t,r,i&&i.reverse())},isGeneratorFunction:p,mark:u.m,awrap:function(e,r){return new t(e,r)},AsyncIterator:o,async:function(e,t,r,o,a){return(p(t)?n:i)(v(e),t,r,o,a)},keys:a,values:s}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}(h);var j=(0,h.exports)(),L=j;try{regeneratorRuntime=j}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=j:Function("r","regeneratorRuntime = r")(j)}var N,V,F,U,G,B,H,q,W,Y,J,Q,K,z,$=v(L);function X(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 Z(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ee(e,t){if(e){if("string"==typeof e)return Z(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)?Z(e,t):void 0}}function te(e){return function(e){if(Array.isArray(e))return Z(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||ee(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 re(){return re="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=l(e)););return e}(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},re.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"}(N||(N={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(V||(V={})),exports.AudioSourceInfo=void 0,(F=exports.AudioSourceInfo||(exports.AudioSourceInfo={})).MIC="mic",F.SCREENCAST="screen-cast",F.MIXED="mixed",exports.VideoSourceInfo=void 0,(U=exports.VideoSourceInfo||(exports.VideoSourceInfo={})).CAMERA="camera",U.SCREENCAST="screen-cast",U.MIXED="mixed",function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(G||(G={})),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"}(B||(B={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(H||(H={})),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"}(q||(q={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(W||(W={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(Y||(Y={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(J||(J={})),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"}(Q||(Q={})),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"}(K||(K={})),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"}(z||(z={}));var ie,ne="3.9.21",oe={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,(ie=exports.AudioSourceState||(exports.AudioSourceState={})).Playing="playing",ie.Paused="paused",ie.Stopped="stopped";var ae=ne,se=-999,ce="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.Environment.browserType,e.Environment.browserVersion,e.Environment.system,e.Environment.systemVersion;var ue="onertc_state_sync",de="onertc_internal_track_event",le="rtc_sdk_el_data",pe="rtc_sdk_player_container_label",fe=e.getReporter().getLoggerWithPrefix("rtc-support"),ve=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=n($.mark(function t(){var r,i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return r={audio:[],video:[]},t.prev=1,(i=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"}),t.next=2,i.createOffer();case 2:if(n=t.sent.sdp){t.next=3;break}return t.abrupt("return",r);case 3:return i.close(),i=null,n.match(/ VP8/i)&&r.video.push("VP8"),n.match(/ VP9/i)&&r.video.push("VP9"),n.match(/ AV1/i)&&r.video.push("AV1"),n.match(/ H264/i)&&r.video.push("H264"),n.match(/ H265/i)&&r.video.push("H265"),n.match(/ opus/i)&&r.audio.push("OPUS"),n.match(/ PCMU/i)&&r.audio.push("PCMU"),n.match(/ PCMA/i)&&r.audio.push("PCMA"),n.match(/ G722/i)&&r.audio.push("G722"),t.abrupt("return",r);case 4:throw t.prev=4,t.catch(1),fe.error("get supportedCodecs failed"),new e.DingRTCError(e.ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 5:case"end":return t.stop()}},t,null,[[1,4]])})),function(){return t.apply(this,arguments)})},{key:"checkSupported",value:function(){var t=!1;try{var r=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(r&&i&&n)}catch(e){return fe.error("checkSystemRequirements error",e),!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 fe.info("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}()),me=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},i=r.setParameters,n=r.getParameters;return!(!i||!n)&&(!e.Environment.isFirefox()&&(e.Environment.isSafari()?parseInt(e.Environment.browserVersion)>=14:e.Environment.isChrome()?parseInt(e.Environment.browserVersion)>=81:!e.Environment.isAndroid()))};function he(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(he=function(){return!!e})()}var ge=e.getReporter().getLoggerWithPrefix("[rtc-config]"),be=new(function(){function t(){var e,r,i,n;return o(this,t),r=this,i=l(i=t),e=d(r,he()?Reflect.construct(i,[],l(r).constructor):i.apply(r,n)),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:me()}),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,"preferH264CbProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"highStartBitrate",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_holdVideoLastFrame",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_consoleLogLevel",{enumerable:!0,configurable:!0,writable:!0,value:"warn"}),Object.defineProperty(e,"connectPcTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:4e3}),e.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),e}return f(t,e.EventEmitter),u(t,[{key:"setClientConfig",value:function(t){ge.info("setClientConfig",t);var r=t||{},i=r.gslb,n=r.simulcast,o=r.audioSFU,a=r.republish,s=r.disableTransportCC,c=r.highStartBitrate;"string"==typeof i&&(this.gslb=[i],e.setGslb(i)),Array.isArray(i)&&e.isString(i[0])&&(this.gslb=i,e.setGslb(i[0])),null!=n&&me()&&(this.simulcast=Boolean(n)),null!=o&&(this.audioSFU=Boolean(o)),null!=s&&(this.disableTransportCC=Boolean(s)),null!=a&&(this.republish=Boolean(a)),null!=c&&(this.highStartBitrate=!!c),null!=t&&t._consoleLogLevel&&(this._consoleLogLevel=null==t?void 0:t._consoleLogLevel),"boolean"==typeof(null==t?void 0:t.preferH264CbProfile)&&(this.preferH264CbProfile=t.preferH264CbProfile),(null==t?void 0:t.connectPcTimeoutMs)>=0&&t.connectPcTimeoutMs<=Number.MAX_SAFE_INTEGER?this.connectPcTimeoutMs=t.connectPcTimeoutMs:void 0!==(null==t?void 0:t.connectPcTimeoutMs)&&null!==(null==t?void 0:t.connectPcTimeoutMs)&&console.error("connectPcTimeoutMs should be a non-negative number")}}])}()),ye=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},ke=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var i=[],n=r.optional,o=r.parameters;return null!=o&&o.resolution&&i.push(o.resolution),null!=n&&null!==(t=n.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&i.push.apply(i,te(n.parameters.resolution)),i.sort(ye),i},Se=function(t,r){var i,n=t.media,o=n.audio,a=n.video;if(r===Q.QuotaLimit)return i=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if(o)i=new e.DingRTCError(e.ErrorCode.SubscribeAudioStreamFailed,r);else if(a){var s=a.source;s===exports.VideoSourceInfo.CAMERA?i=new e.DingRTCError(e.ErrorCode.SubscribeVideoStreamFailed,r):s===exports.VideoSourceInfo.SCREENCAST&&(i=new e.DingRTCError(e.ErrorCode.SubscribeScreenShareFailed,r))}return i},Pe=function(t,r){var i,n=t.trackMediaType;if(r===Q.QuotaLimit)return i=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if("audio"===n)i=new e.DingRTCError(e.ErrorCode.PublishAudioStreamFailed,r);else{var o=t.source;o===exports.VideoSourceInfo.CAMERA?i=new e.DingRTCError(e.ErrorCode.PublishVideoStreamFailed,r):o===exports.VideoSourceInfo.SCREENCAST&&(i=new e.DingRTCError(e.ErrorCode.PublishScreenShareFailed,r))}return i},Te=function(e,t,r,i){var n=i,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?be.audioSFU?i?i.replaceStream(e):n=new vr(null,r,e):i?i.replaceTrack(a[0]):n=new vr(a[0],r):"video"===t&&o.length&&(i?i.replaceTrack(o[0]):n=new mr(o[0],r)),n},we=function(e){return"object"===a(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function Ee(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ee(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ee(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Me(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 Oe(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)?Oe(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Oe(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Re(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Re=function(){return!!e})()}var Ae=e.getReporter().getLoggerWithPrefix("[rtc-device]"),xe=function(){function t(){var e,r,i,a,s;return o(this,t),r=this,i=l(i=t),e=d(r,Re()?Reflect.construct(i,[],l(r).constructor):i.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=n($.mark(function r(){var i;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=1;break}return r.abrupt("return");case 1:return e.checking=!0,r.next=2,t.getDevices();case 2:i=r.sent,e.compareDevices(i,"audiooutput"),e.compareDevices(i,"videoinput"),e.compareDevices(i,"audioinput"),e.deviceList=i,e.checking=!1;case 3: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 i,n=t.filter(function(e){return e.kind===r}),o=e.deviceList.filter(function(e){return e.kind===r}),a=n.map(function(e){return e.deviceId}),s=o.map(function(e){return e.deviceId}),c=n.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=Me(c);try{for(l.s();!(i=l.n()).done;){var p=i.value;e.emit(d[r],{device:p,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var f,v=Me(u);try{for(v.s();!(f=v.n()).done;){var m=f.value;e.emit(d[r],{device:m,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),t._instance?d(e,t._instance):(e.deviceList=[],ve.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:(r=n($.mark(function r(i,n){var o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(t.accGetMedia++,o=t.accGetMedia,!we(i)){r.next=6;break}if(Ae.info("getDisplayMedia with",o,i,n),!e.Environment.isElectron()){r.next=3;break}if(n.video){r.next=1;break}throw new e.DingRTCError(e.ErrorCode.ScreenShareOpenFail,"only video screen cast is supported, but got no video parameters");case 1:return r.next=2,navigator.mediaDevices.getUserMedia({audio:!1,video:{mandatory:{chromeMediaSource:"screen",minWidth:(null===(s=n.video)||void 0===s?void 0:s.width)||1280,maxWidth:(null===(c=n.video)||void 0===c?void 0:c.width)||1280,minHeight:(null===(u=n.video)||void 0===u?void 0:u.height)||720,maxHeight:(null===(d=n.video)||void 0===d?void 0:d.height)||720,minFrameRate:(null===(l=n.video)||void 0===l?void 0:l.frameRate)||5,maxFrameRate:(null===(p=n.video)||void 0===p?void 0:p.frameRate)||5}}});case 2:a=r.sent,r.next=5;break;case 3:return r.next=4,null===(f=navigator.mediaDevices)||void 0===f?void 0:f.getDisplayMedia(n);case 4:a=r.sent;case 5:return Ae.info("succ getDisplayMedia with",o),r.abrupt("return",a);case 6:return Ae.info("getUserMedia with",o,i,n),r.next=7,null===(v=navigator.mediaDevices)||void 0===v?void 0:v.getUserMedia(n);case 7:return m=r.sent,Ae.info("succ getUserMedia with",o),i.audio&&(this.audioPermitted=!0),i.video&&(this.videoPermitted=!0),r.abrupt("return",m);case 8:case"end":return r.stop()}},r,this)})),function(e,t){return r.apply(this,arguments)})},{key:"getDevices",value:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(function(n,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||i?l.length?(r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),n(l)):n(l):(Ae.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){n(e)},o)},o)),n(a)})}else o(new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))})}}]);var r}();Object.defineProperty(xe,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(xe,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(xe,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new xe}),Object.defineProperty(xe,"accGetMedia",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(xe,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({audio:!0}).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})}).catch(function(t){throw e.parseAudioDeviceError(t)})}}),Object.defineProperty(xe,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({video:!0}).then(function(e){return Ae.info("getCameras",e),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 Ie(Ie({},r),{},{toJSON:function(){return r}})})}).catch(function(t){throw Ae.error("getCameras error",t),e.parseVideoDeviceError(t)})}}),Object.defineProperty(xe,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({audio:!0}).then(function(e){return Ae.info("getMicrophones",e),e.filter(function(e){return"audioinput"===e.kind})}).catch(function(t){throw Ae.error("getMicrophones error",t),e.parseAudioDeviceError(t)})}});var Ce,_e,De=function(e){return{width:oe[e][0],height:oe[e][1]}},je=function(t){var r,i=Object.create({}),n={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.Environment.isSafari()?i.deviceId=t.deviceId:i.deviceId={exact:t.deviceId}),n.autoGainControl&&(i.autoGainControl={ideal:null==a||a}),n.echoCancellation&&(i.echoCancellation={ideal:null==o||o}),n.noiseSuppression&&(i.noiseSuppression={ideal:null==s||s}),i},Le=function(t){if(!e.isObject(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,i=t.video;if(!we(t)&&"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(we(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&&!i)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n={};if("object"===a(r)&&r.source===exports.AudioSourceInfo.MIC||"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST?n.audio=je(r):n.audio=t.audio,"object"===a(i)){var o,s=i.frameRate,c=i.deviceId,u=i.source,d=i.facingMode,l=i.displaySurface,p=i.dimension;n.video={},e.isNumber(s)&&(n.video.frameRate=Math.min(i.frameRate,30)),p&&(o=De(p)),o&&o.width&&o.height&&(u===exports.VideoSourceInfo.SCREENCAST||e.Environment.isFirefox()?(n.video.width=o.width,n.video.height=o.height):(n.video.width={ideal:o.width,max:o.width},n.video.height={ideal:o.height,max:o.height})),e.isString(c)&&c&&(n.video.deviceId={exact:c}),u===exports.VideoSourceInfo.SCREENCAST&&(e.Environment.isFirefox()&&(n.video.mediaSource="screen"),l&&["browser","window","monitor"].includes(l)&&(n.video.displaySurface=l)),d&&["user","environment"].includes(d)&&(n.video.facingMode=d)}else n.video=i;return xe.getMedias(t,n)},Ne=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},Ve=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},Fe=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},Ue=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Ge=function(e){var t=e.fn,r=e.times,i=e.interval,o=void 0===i?0:i,a=e.resolve,s=e.reject,c=function(){var e=n($.mark(function e(){var i,n,c;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=0;case 1:if(!(n<r)){e.next=7;break}return e.prev=2,e.next=3,t();case 3:return i=e.sent,null==a||a(i),e.abrupt("continue",7);case 4:if(e.prev=4,c=e.catch(2),n!==r-1){e.next=5;break}return null==s||s(c),e.abrupt("return",c);case 5:return e.next=6,Be(o);case 6:n++,e.next=1;break;case 7:return e.abrupt("return",i);case 8:case"end":return e.stop()}},e,null,[[2,4]])}));return function(){return e.apply(this,arguments)}}();return c()},Be=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=1;break}return e.next=1,new Promise(function(e){setTimeout(e,t)});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),He=function(t){return new Promise(function(r){e.addTimer(r,1e3*t)})},qe=e.getReporter().getLoggerWithPrefix("[rtc-mediaElPool]"),We="rtc-intersecting",Ye="visible",Je="invisible",Qe=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],Ke=function(e){return"".concat(null==e?void 0:e.getAttribute(ce),"-").concat(null==e?void 0:e.rtcPurpose)},ze=function(){return u(function t(r,i){var n=this;o(this,t),Object.defineProperty(this,"mediaElementCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),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(){n.mediaElementPool.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(e.removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(te(n.mediaElementPool),te(n.mediaElementsInUse)).forEach(function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(t){n.mediaElementsInUse.forEach(function(r){if(r.srcObject){var i=r.srcObject;if(r.error&&(qe.debug("".concat(t,": tag=").concat(r.tagName," ").concat(Ke(r)," has error, error=").concat(r.error,", doc.visibilityState=").concat(document.visibilityState,", mediaStream="),e.getPlainMediaStreamInfo(i)),"visible"===document.visibilityState&&Ne(i)&&r.load()),r.paused){var o=!1;if(n.hasActivated&&"video"===n.mediaKind?function(e){return e&&e.getAttribute(We)===Ye}(r)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(r).visibility&&(o=!0):o=!0,o){var a="".concat(t,": ").concat(Ke(r)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(r.getAttribute(We),", mediaStream="),s=e.getPlainMediaStreamInfo(i);qe.error(a,s),Ne(i)&&r.load(),r.paused&&r.play().catch(function(e){console.error("inPoll",e)})}}}}),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,t),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(t){n.mediaElementsInUse.forEach(function(r){if(r.srcObject){var i=r.srcObject,o="video"===n.mediaKind?i.getVideoTracks()[0]:void 0;if(!r.paused&&n.currentTimeOfLastCheckMap.get(r)===r.currentTime&&"video"===n.mediaKind&&!0!==(null==o?void 0:o.muted))return qe.error("".concat(t,": tag=").concat(r.tagName," label=").concat(Ke(r),", currentTime Stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(r.currentTime,", mediaStream="),e.getPlainMediaStreamInfo(i)),void("visible"===document.visibilityState&&Ne(i)&&r.load());n.currentTimeOfLastCheckMap.set(r,r.currentTime)}})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="error event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject),a=null==r?void 0:r.error;qe.error(i,o,a)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="pause event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject),a=null==r?void 0:r.error;qe.debug(i,o,a)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="play event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject);qe.debug(i,o)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=[].concat(te(n.mediaElementPool),te(n.mediaElementsInUse));if(!n.hasActivated){n.hasActivated=!0;var r="".concat(n.mediaKind," good! media elements activated by click");if(qe.debug(r),t.forEach(function(e){e.load()}),qe.info("load all for activate"),n._activatedListener)try{n._activatedListener()}catch(t){qe.error("error occurred when exec activatedListener",e.tryJsonStringify(t))}else qe.debug("ignore activatedListener for there is no one")}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),qe.debug("build ".concat(r," pool size"),i),this.mediaElementCount=i,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(We,Ye):null===(r=e.target)||void 0===r||r.setAttribute(We,Je)})}));for(var a=1;a<=i;a++){var s=this._createElement("".concat(r,"-").concat(a));this.mediaElementPool.push(s),this.allElements.add(s)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=e.addTimer(function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")},4e3,"interval")},[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(ce,"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())?qe.info("".concat(this.mediaKind," pop label=").concat(Ke(t)," for ").concat(e)):(t=this._createElement("".concat(this.mediaKind,"-").concat(++this.mediaElementCount)),qe.info("".concat(this.mediaKind," create new videoEl for no more video element in pool"))),this.mediaElementsInUse.push(t),this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||"",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&&(qe.debug("".concat(this.mediaKind," pushed"),Ke(e)),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(e){var t,r=document.createElement(this.mediaKind);return null===(t=this.observer)||void 0===t||t.observe(r),this.addAtttribute(r),r.setAttribute(ce,e),r}},{key:"_resetMediaElement",value:function(e){Qe.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}}])}(),$e=function(){return Ce||et(),Ce},Xe=function(){return _e||et(),_e};window.getAudioElementPool=$e,window.getVideoElementPool=Xe;var Ze=e.Environment.isIOS()||e.Environment.isAndroid()?9:25,et=function(){Ce||(Ce=new ze("audio",2)),_e||(_e=new ze("video",Ze))},tt=e.getReporter().getLoggerWithPrefix("[rtc-actx]"),rt=null,it=function(){if(rt||(rt=new AudioContext),"running"!==rt.state){var e=setTimeout(function(){var e="timeout for resume audioContext, probably page still has no user gesture like click or touch";console.error(e),tt.error(e)},2e3);rt.resume().finally(function(){clearTimeout(e)})}return rt},nt=function(e){var t=e.getAudioTracks(),r=it().createMediaStreamDestination();return t.forEach(function(e){it().createMediaStreamSource(new MediaStream([e])).connect(r)}),r.stream.getAudioTracks()[0]},ot=function(e,t){t.connect(e),e.fftSize=2048,e.smoothingTimeConstant=.4;var r=new Float32Array(e.fftSize);if(e.getFloatTimeDomainData)e.getFloatTimeDomainData(r);else{var i=new Uint8Array(e.fftSize);e.getByteTimeDomainData(i);for(var n=0;n<r.length;++n)r[n]=i[n]/128-1}for(var o=0,a=0;a<r.length;a++)o+=r[a]*r[a];return Math.max(10*Math.log10(o/r.length)+100,0)/100},at=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),i=e.videoHeight,n=e.videoWidth;return t.width=n,t.height=i,r.drawImage(e,0,0,n,i),t.toDataURL("image/png")},st=$e(),ct=Xe(),ut=e.getReporter().getLoggerWithPrefix("[rtc-playerMgr]"),dt=u(function t(r,i,n,a){var s=this;o(this,t),Object.defineProperty(this,"mediaEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playerConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaWrapperEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkSwitchSnapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastCheckResult",{enumerable:!0,configurable:!0,writable:!0,value:{msTrackPlayable:!1,elPlaying:!1}}),Object.defineProperty(this,"isPlayerPlaying",{enumerable:!0,configurable:!0,writable:!0,value:function(){return s.mediaEl&&s.mediaEl.currentTime>0&&!s.mediaEl.paused&&!s.mediaEl.ended&&s.mediaEl.readyState>=2}}),Object.defineProperty(this,"snapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r=s.track.getMediaStreamTrack(),i="live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted);if(be._holdVideoLastFrame&&(i&&(null===(e=s.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])===r)){var n=s.canvas.getContext("2d");n.clearRect(0,0,s.canvas.width,s.canvas.height);var o=s.mediaEl.videoHeight,a=s.mediaEl.videoWidth;s.canvas.width===a&&s.canvas.height===o||(s.canvas.width=a,s.canvas.height=o),n.drawImage(s.mediaEl,0,0,a,o)}}}),Object.defineProperty(this,"checkSwitchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,i,n,o,a=s.track.getMediaStreamTrack(),c="live"===(null==a?void 0:a.readyState)&&(null==a?void 0:a.enabled)&&!(null!=a&&a.muted);c===s.lastCheckResult.msTrackPlayable&&s.isPlayerPlaying()===s.lastCheckResult.elPlaying||ut.info("rtcTrackId=".concat(s.track.getTrackId()," play change trackPlayable=").concat(c," isPlaying=").concat(s.isPlayerPlaying()),{msTrackReadyState:null==a?void 0:a.readyState,msTrackEnabled:null==a?void 0:a.enabled,msTrackMuted:null==a?void 0:a.muted,elCurrentTime:null===(e=s.mediaEl)||void 0===e?void 0:e.currentTime,elPaused:null===(t=s.mediaEl)||void 0===t?void 0:t.paused,elEnded:null===(r=s.mediaEl)||void 0===r?void 0:r.ended,elReadyState:null===(i=s.mediaEl)||void 0===i?void 0:i.readyState});(s.lastCheckResult={msTrackPlayable:c,elPlaying:s.isPlayerPlaying()},be._holdVideoLastFrame)&&(c&&(null===(n=s.mediaEl)||void 0===n||null===(n=n.srcObject)||void 0===n||null===(o=n.getVideoTracks)||void 0===o||null===(o=o.call(n))||void 0===o?void 0:o[0])!==a?s.switchOriginVideo():c||s.mediaEl.srcObject===s.snapshotMediaStream||s.switchSnapshot())}}),Object.defineProperty(this,"startCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){"video"===s.track.trackMediaType&&(ut.info("startCheckPlayState trackid=",s.track.getTrackId()),s.snapshotInterval=setInterval(s.snapshot,300),s.checkSwitchSnapshotInterval=setInterval(s.checkSwitchSnapshot,150))}}),Object.defineProperty(this,"stopCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;ut.info("stopCheckPlayState trackid=",null===(e=s.track)||void 0===e||null===(t=e.getTrackId)||void 0===t?void 0:t.call(e)),clearInterval(s.snapshotInterval),clearInterval(s.checkSwitchSnapshotInterval)}}),Object.defineProperty(this,"playVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t;ut.info("playVideo",s.track.getTrackId(),null===(t=s.mediaWrapperEl)||void 0===t?void 0:t.getAttribute(pe)),s.mediaWrapperEl.appendChild(s.mediaEl),s.mediaEl.pause();var r=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=r,s.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play video error trackid=",null===(r=s.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))}),s.stopCheckPlayState(),s.startCheckPlayState()}}),Object.defineProperty(this,"playAudio",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=t,s.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play audio error trackid=",null===(r=s.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))}),s.stopCheckPlayState(),s.startCheckPlayState()}}),Object.defineProperty(this,"stopPlay",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;if(ut.info("stopPlay",s.track.getTrackId(),null===(e=s.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(pe)),s.stopCheckPlayState(),s.mediaEl&&s.track){var r,i;if(s.mediaEl.pause(),null!==(t=s.mediaWrapperEl)&&void 0!==t&&t.contains(s.mediaEl))null===(r=s.mediaWrapperEl)||void 0===r||null===(i=r.removeChild)||void 0===i||i.call(r,s.mediaEl);s.mediaEl.srcObject=null,s.canvas=null,"audio"===s.track.trackMediaType?st.pushElement(s.mediaEl):ct.pushElement(s.mediaEl)}}}),Object.defineProperty(this,"switchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){ut.info("switchSnapshot trackid",s.track.getTrackId()),s.mediaEl.srcObject=s.snapshotMediaStream,s.mediaEl.play().catch(function(t){ut.info("snapshot play error, trackid",s.track.getTrackId(),e.tryJsonStringify(t))})}}),Object.defineProperty(this,"switchOriginVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){setTimeout(function(){var t,r,i=s.track.getMediaStreamTrack();if("live"===(null==i?void 0:i.readyState)&&(null==i?void 0:i.enabled)&&!(null!=i&&i.muted)&&(null===(t=s.mediaEl)||void 0===t||null===(t=t.srcObject)||void 0===t||null===(r=t.getVideoTracks)||void 0===r||null===(r=r.call(t))||void 0===r?void 0:r[0])!==i){ut.info("switchOriginVideo trackid",s.track.getTrackId());var n=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=n,s.mediaEl.play().catch(function(t){ut.info("switchOriginVideo play error, trackid",s.track.getTrackId(),e.tryJsonStringify(t))})}},1e3)}}),this.mediaWrapperEl=a,this.mediaWrapperEl&&!this.mediaWrapperEl.getAttribute(pe)&&this.mediaWrapperEl.setAttribute(pe,"container_".concat(t.containerRtcLabelAcc++)),this.track=r,this.playerConfig=i,this.mediaEl=n,this.mediaEl.setAttribute(le,this.track.getTrackId()),this.canvas=document.createElement("canvas"),this.canvas.setAttribute(le,this.track.getTrackId()),this.snapshotMediaStream=this.canvas.captureStream(4)});Object.defineProperty(dt,"containerRtcLabelAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var lt=new(function(){return u(function e(){o(this,e),Object.defineProperty(this,"playControllerArr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.playControllerArr=[]},[{key:"getElement",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}).map(function(e){return e.mediaEl})}},{key:"getPlayCtrls",value:function(e){return this.playControllerArr.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,i){var n,o=this;ut.info("call play",t.getTrackId(),r instanceof HTMLElement?r.tagName:r,i);var 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=i||{},l=d.mirror,p=d.fit;if((n=this.playControllerArr.find(function(e){return e.mediaWrapperEl===u}))&&(null===(c=n.track)||void 0===c?void 0:c.getTrackId())!==(null==t?void 0:t.getTrackId()))return this.stopPlay(n.track,r),void this.play(t,r,i);if(n)n.mediaEl.pause(),!t.sourceMirror!=!l?n.mediaEl.style.transform="scaleX(-1)":n.mediaEl.style.transform="",p&&(n.mediaEl.style.objectFit=p),n.mediaEl.srcObject=s,n.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play video error trackid=",null===(r=n.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))});else{var f,v=null===(f=this.getPlayCtrls(t))||void 0===f?void 0:f.length;if(v>3){var m,h=["DingRTC WARN: possible memory leak. More than 3 HTMLElement containers are playing the same track.","Please call track.stop to stop playing HTMLElements that will unmount in DOM.","TrackId:",t.getTrackId()];(m=console).warn.apply(m,h),ut.info.apply(ut,h.concat([v]))}(function(e,t){if(e.style.width="100%",e.style.height="100%",t){var r=t.mirror,i=t.fit;!0===r&&(e.style.transform="scaleX(-1)"),i&&(e.style.objectFit=i)}})((n=new dt(t,i,Xe().popElement(),u)).mediaEl,{mirror:!t.sourceMirror!=!l,fit:p}),n.playVideo(),this.playControllerArr.push(n)}}else(n=this.playControllerArr.find(function(e){var r;return(null===(r=e.track)||void 0===r?void 0:r.getTrackId())===t.getTrackId()}))?(n.mediaEl.pause(),n.mediaEl.srcObject=s,ut.info("element loaded",t.getTrackId()),n.mediaEl.load()):((n=new dt(t,null,$e().popElement(),null)).playAudio(),this.playControllerArr.push(n));n.mediaEl.paused&&n.mediaEl.play().catch(function(t){"NotAllowedError"===t.name?(ut.error("autoplay failed",e.tryJsonStringify(t)),e.EventBus.emit("autoplay-failed",o)):"AbortError"!==t.name&&ut.warn("".concat(a," play error"),e.tryJsonStringify(t))})}},{key:"isPlaying",value:function(e){return this.playControllerArr.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.isPlayerPlaying()})}},{key:"stopPlay",value:function(e,t){var r;ut.info("call stop play",e.getTrackId());var i=this.findDom(t),n=this.playControllerArr.filter(function(r){var n;return(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())&&(!t||r.mediaWrapperEl===i)});if(n.length){n.forEach(function(e){e.stopPlay()});var o=this.playControllerArr.filter(function(e){return!n.includes(e)});(r=this.playControllerArr).splice.apply(r,[0,this.playControllerArr.length].concat(te(o)))}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}()),pt=function(){return lt};function ft(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ft=function(){return!!e})()}window.playerMgr=lt;var vt=e.getReporter(),mt=vt.trace,ht=vt.getLoggerWithPrefix("[rtc-track]"),gt=ht,bt=pt(),yt=function(){function t(r,i){var n,a,s,c;return o(this,t),a=this,s=l(s=t),n=d(a,ft()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:mt}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r?(n.trackMediaType=r.kind,n.trackSettings=r.getSettings()):i&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.analyser=it().createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(e.createUuid(6)),n.setMediaStreamTrack(r,i),n}return f(t,e.EventEmitter),u(t,[{key:"isPlaying",get:function(){return bt.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return ht.info("track emit event",e,null==i?void 0:i[0]),(o="emit",a=this,s=3,c=re(l(t.prototype),o,a),2&s&&"function"==typeof c?function(e){return c.apply(a,e)}:c)([e].concat(i));var o,a,s,c}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(t,r){var i=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),t||r){var o;if(n&&t&&(t.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),t)this.sourceNode=null===(o=it())||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([t]));else if(r){var a,s=nt(r);this.sourceNode=null===(a=it())||void 0===a?void 0:a.createMediaStreamSource(new MediaStream([s]))}t?(this.mediaStreamTrack=t,this.mediaStreamTrack.onended=function(){i.source===exports.VideoSourceInfo.SCREENCAST?i.logger.sendEvent("SCREEN_DEVICE_STOP"):i.source===exports.AudioSourceInfo.MIC?new e.DingRTCError(e.ErrorCode.MicInterrupt):i.source===exports.VideoSourceInfo.CAMERA&&new e.DingRTCError(e.ErrorCode.CameraInterrupt)}):r&&(this.sfuStream=r)}}},{key:"replaceTrack",value:function(e,t){gt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(de,"replace",this),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){console.error("The API stop is deprecated. Use stopPlay to stop playing or use close to destroy mediaStream track"),gt.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),bt.stopPlay(this,e)}},{key:"stopPlay",value:function(e){gt.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),bt.stopPlay(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.mediaWrapperElement,i=e.config;e.updated?bt.getPlayCtrls(this).forEach(function(e){e.mediaWrapperEl?bt.findDom(e.mediaWrapperEl)?bt.play(t,e.mediaWrapperEl,e.playerConfig):bt.stopPlay(t,e.mediaWrapperEl):bt.play(t,e.mediaWrapperEl,e.playerConfig)}):bt.play(this,r,i);if("audio"===this.trackMediaType){var n=it();"running"!==n.state&>.error("audioContext not running",n.state)}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function kt(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 i,n,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=(i=o.call(r)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){u=!0,n=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw n}}return s}}(e,t)||ee(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var St,Pt=function(e){return e.width>1920&&e.height>1080},Tt=function(e){var t;if(!e)return be.simulcast;var r=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==r?void 0:r.width)||e.trackSettings.width,n=(null==r?void 0:r.height)||e.trackSettings.height;return be.simulcast&&e.source===exports.VideoSourceInfo.CAMERA&&!Pt({width:i,height:n})};function wt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Et(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?wt(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(St||(St={}));var It=X(X(X(X(X(X({},St.LLD,"lld"),St.LD,"ld"),St.SD,"sd"),St.HD,"hd"),St.FHD,"fhd"),St.QHD,"qhd"),Mt={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},Ot=function(e,t){var r=At(e,t),i=function(e,t){var r={high:z.QHD,low:z.LD,QHD:z.QHD,FHD:z.FHD,HD:z.HD,SD:z.SD,LD:z.LD},i=r[e]||z.None,n=Mt[e],o=t[t.length-1].width*t[t.length-1].height;if(o<n[0]){var a=Object.entries(Mt).find(function(e){var t=kt(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]});i=r[kt(a,1)[0]]}return i}(e,t);return{resolution:r,resolutionLevel:i}},Rt=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},At=function(e,t){var r=Mt[e],i=t.length,n=t[t.length-1];if(("FHD"===e||"high"===e)&&Pt(n))return n;if(t[0].width*t[0].height>Mt.FHD[1])return t[0];for(var o=0;i>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=i-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},xt=[49152,76800,307200,1228800,2764800,4915200],Ct=[200,350,1e3,1800,2828,5600],_t=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],Dt=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],jt=function(e,t){var r=St.FHD,i=e*t;return i<=xt[St.LLD]?r=St.LLD:i<=xt[St.LD]?r=St.LD:i<=xt[St.SD]?r=St.SD:i<=xt[St.HD]?r=St.HD:i<=xt[St.FHD]?r=St.FHD:i<=xt[St.QHD]&&(r=St.QHD),r},Lt=function(e,t,r,i){var n=0,o=0;if(i<=r)return[n=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)n=_t[r][0],o=_t[r][1];else if(4*t==3*e)n=Dt[r][0],o=Dt[r][1];else{var s=Math.sqrt(1*_t[r][0]*_t[r][1]/e/t);s=1*(n=(n=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[n,o]},Nt=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!i){var n=1;30!==r&&(n=Math.sqrt(r/30));var o=Ct[jt(e,t)];i=Math.round(Math.max(n*o,50))}return i},Vt=function(e){var t=e.width,r=e.height,i=e.frameRate,n=e.maxBitrate,o=e.resolutionLevel,a=jt(t,r),s=[],c=a>=St.HD?3:2,u=function(e){var o=kt(Lt(t,r,e,a),2),s=o[0],c=o[1],u=Ct[e]/Ct[a],d=1/(c/r);return{targetWidth:s,rid:It[e],targetHeight:c,minBitrate:50,maxFramerate:i,maxBitrate:Math.round(Math.max(30,n*u)),scaleResolutionDownBy:d}};a>St.LLD&&s.push(Et({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,St.LLD)===o},u(St.LLD))),a>St.LD&&s.push(Et({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,St.LD)===o},u(St.LD))),a>St.SD&&s.push(Et({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,St.SD)===o},u(St.SD))),a===St.FHD?(s.push(Et({activeForBitrateMap:!1,activeForRealuse:!1},u(St.HD))),s.push(Et({activeForBitrateMap:!0,activeForRealuse:be.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(St.FHD)))):s.push(Et({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},Ft=function(e,t){var r=jt(e,t);return Math.pow(2,r)},Ut=function(e){var t,r=e.getMaxBitrate(),i=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),n=(null==i?void 0:i.width)||e.trackSettings.width,o=(null==i?void 0:i.height)||e.trackSettings.height,a=(null==i?void 0:i.frameRate)||e.trackSettings.frameRate,s=!Tt(e),c={resolutionLevel:Ft(n,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:n,targetHeight:o}]:be.republish?c.encodings=Vt({width:1920,height:1080,frameRate:30,maxBitrate:Nt(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=Vt({width:n,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function Gt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Bt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Gt(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Gt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ht(e,t,r){return t=l(t),d(e,qt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function qt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(qt=function(){return!!e})()}function Wt(e,t,r,i){var n=re(l(e.prototype),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}var Yt=pt(),Jt=e.getReporter().getLoggerWithPrefix("[rtc-localtrack]"),Qt=function(){function t(e){var r;if(o(this,t),r=Ht(this,t,[e]),Object.defineProperty(r,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var i=e.muted;r.muted=i}return r.enabled=!0,r}return f(t,yt),u(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;Wt(t,"setMediaStreamTrack",this,3)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stopPlay(),r.close&&setTimeout(function(){return r.close()},200),r.emit("track-ended")})}},{key:"play",value:function(e,t){Jt.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,t),this.innnerPlay({mediaWrapperElement:e,config:t})}},{key:"setEnabled",value:function(t){var r,i=this;return Jt.info("setEnabled",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.enabled=t,t?this.updateNewTrack().then(function(e){return i.emit(de,"unmute"),e}):(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"),this.emit(de,"mute"),Promise.resolve()))}},{key:"close",value:function(){var e;Jt.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stopPlay(),this.emit(de,"stop",this),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.sourceNode=null,this.analyser=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 Jt.info("setMuted",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.muted=t,this.mediaStreamTrack.enabled=!t,this.emit(de,t?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var t=this;return Jt.debug("gengrate new audioTrack"),new Promise(function(r,i){var n;Le({audio:Bt({source:t.source},t.config)}).then(function(e){n=e.getAudioTracks()[0]}).catch(function(t){try{var r=it().createOscillator(),o=it().createMediaStreamDestination();r.connect(o),n=o.stream.getAudioTracks()[0]}catch(r){Jt.error("gengrate new audioTrack error",e.parseAudioDeviceError(t)),i(e.parseAudioDeviceError(t))}}).finally(function(){n&&r(n)})})}},{key:"getVideoTrack",value:function(){var t=this;return Jt.info("gengrate new videoTrack",this.config),new Promise(function(r,i){var n,o=Bt({source:t.source},t.config);t.config.facingMode&&t.config.deviceId&&(Jt.info("ignore deviceId param to create videoTrack because facingMode is",t.config.facingMode),delete o.deviceId),Le({video:o,audio:!1}).then(function(e){n=e.getVideoTracks()[0],r(n)}).catch(function(t){Jt.error("gengrate new videoTrack error",e.parseVideoDeviceError(t)),i(e.parseVideoDeviceError(t))})})}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,Jt.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then(function(t){return e.replaceTrackInner(t,null,!0),e.emit(de,"localMixedAudioReplaceTrack",e)}):"video"===this.trackMediaType?this.getVideoTrack().then(function(t){return e.replaceTrackInner(t,null,!0)}):void 0}},{key:"setDevice",value:(r=n($.mark(function e(t){var r,i,n;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Jt.info("setDevice",t),!this.isClosed){e.next=1;break}return e.abrupt("return");case 1:if(!(this instanceof $t)||"user"!==t&&"environment"!==t){e.next=2;break}this.config.facingMode=t,e.next=4;break;case 2:if((this.config.deviceId||(null===(r=this.mediaStreamTrack)||void 0===r||null===(r=r.getSettings())||void 0===r?void 0:r.deviceId)||(null===(i=this.mediaStreamTrack)||void 0===i||null===(n=i.getConstraints)||void 0===n||null===(n=n.call(i))||void 0===n?void 0:n.deviceId))!==t){e.next=3;break}return e.abrupt("return");case 3:this.config.deviceId=t;case 4:return e.abrupt("return",this.updateNewTrack());case 5:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(Jt.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(),Kt=function(){function t(e,r){var i;if(o(this,t),(i=Ht(this,t,[e])).config=r,e){var n=e.getSettings(),a=n.width,s=n.height;i.maxBitrate=Nt(a,s,r.frameRate,r.maxBitrate)}return i}return f(t,Qt),u(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:(r=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f,v,m,h;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(Jt.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),r),i=r.dimension,n=r.frameRate,o=r.maxBitrate,a=r.optimizationMode,s=r.mirror,!n||!Number.isNaN(n)){t.next=1;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid frameRate")));case 1:if(!i||oe[i]){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid dimension")));case 2:if(!s!=!this.config.mirror&&(this.emit(de,"mirror",s),this.config.mirror=s),a&&a!==this.optimizationMode&&(this.config.optimizationMode=a,this.emit(de,"optimizationMode")),c=!1,i&&this.config.dimension!==i&&(this.config.dimension=i,c=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),c=!0),o&&this.maxBitrate!==o&&(c=!0),c){t.next=3;break}return t.abrupt("return",Promise.resolve());case 3:return u=Bt({frameRate:this.config.frameRate},De(this.config.dimension)),d=this.getMediaStreamTrack(),t.prev=4,t.next=5,null==d?void 0:d.applyConstraints(u);case 5:p=null===(l=this.getMediaStreamTrack())||void 0===l?void 0:l.getSettings(),f=p.width,v=p.height,this.maxBitrate=Nt(f,v,this.config.frameRate,o),Jt.info("after applyConstraints",u,this.maxBitrate,e.getPlainMediaTrackInfo(d)),this.emit(de,"republish",this),t.next=7;break;case 6:throw t.prev=6,h=t.catch(4),m=e.parseVideoDeviceError(h),Jt.error("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration error"),m),m;case 7:case"end":return t.stop()}},t,this,[[4,6]])})),function(e){return r.apply(this,arguments)})},{key:"getCurrentFrameData",value:function(){return Jt.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:at(Yt.getElement(this)[0])}},{key:"play",value:function(e,r){return Jt.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,r),Wt(t,"play",this,3)([e,r])}}]);var r}(),zt=function(){function e(t){return o(this,e),Ht(this,e,[t])}return f(e,Qt),u(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Yt.getElement(this)[0]&&(Yt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Yt.getElement(this)[0]?Yt.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:ot(this.analyser,this.sourceNode)}},{key:"play",value:function(){return Jt.info("local audio play"),Wt(e,"play",this,3)([])}},{key:"replaceTrack",value:function(e,t){Jt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0),this.emit(de,"localMixedAudioReplaceTrack",this)}}])}(),$t=function(){function e(t,r){var i;return o(this,e),(i=Ht(this,e,[t,r])).setSource(exports.VideoSourceInfo.CAMERA),i}return f(e,Kt),u(e)}(),Xt=function(){function e(t,r){var i;return o(this,e),(i=Ht(this,e,[t])).config=r,i.setSource(exports.AudioSourceInfo.MIC),i.analyser=it().createAnalyser(),i}return f(e,zt),u(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Yt.getElement(this)[0]&&(Yt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Yt.getElement(this)[0]?Yt.getElement(this)[0].volume:void 0}}])}(),Zt=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createMicrophoneAudioTrack",r),i={AEC:!0,AGC:!0,ANS:!0},o=(n=r||i).AEC,a=void 0===o||o,s=n.AGC,c=void 0===s||s,u=n.ANS,d=void 0===u||u,t.prev=1,t.next=2,Le({video:!1,audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:a,AGC:c,ANS:d}});case 2:return l=t.sent,p=l.getAudioTracks()[0],Jt.info("MicrophoneAudioTrack created",e.getPlainMediaTrackInfo(p)),t.abrupt("return",new Xt(p,Object.assign({},r,{AEC:a,AGC:c,ANS:d})));case 3:throw t.prev=3,f=t.catch(1),e.parseAudioDeviceError(f);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e){return t.apply(this,arguments)}}(),er=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createCameraVideoTrack",r),i=r.deviceId,n=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=1,t.next=2,Le({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:u,dimension:a,facingMode:n},audio:!1});case 2:return d=t.sent,l=d.getVideoTracks()[0],Jt.info("CameraVideoTrack created",e.getPlainMediaTrackInfo(l)),l.addEventListener("ended",function(){return Jt.info("cam track ended",l.id)}),l.addEventListener("unmute",function(){return Jt.info("cam track unmute",l.id)}),l.addEventListener("mute",function(){return Jt.info("cam track mute",l.id)}),t.abrupt("return",new $t(l,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c})));case 3:throw t.prev=3,p=t.catch(1),e.parseVideoDeviceError(p);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e){return t.apply(this,arguments)}}(),tr=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return Jt.info("createScreenVideoTrack config",t),e.abrupt("return",rr(t,"noAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),rr=function(){var t=n($.mark(function t(r,i){var n,o,a,s,c,u,d,l,p,f,v,m,h,g;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("_createScreenVideoTrack",r,i),n=r.displaySurface,o=void 0===n?"monitor":n,a=r.dimension,s=void 0===a?"VD_1920x1080":a,c=r.optimizationMode,u=void 0===c?"detail":c,d=Math.min(r.frameRate||5,30),t.prev=1,t.next=2,Le({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:o,frameRate:d,dimension:s},audio:"withAudio"===i});case 2:return l=t.sent,f=l.getVideoTracks()[0],Jt.info("ScreenVideoTrack created",e.getPlainMediaTrackInfo(f)),f.addEventListener("ended",function(){return Jt.info("screen video track ended",f.id)}),f.addEventListener("unmute",function(){return Jt.info("screen video track unmute",f.id)}),f.addEventListener("mute",function(){return Jt.info("screen video track mute",f.id)}),(v=new Kt(f,Object.assign({},r,{frameRate:d,dimension:s,optimizationMode:u}))).setSource(exports.VideoSourceInfo.SCREENCAST),(h=null===(p=l.getAudioTracks())||void 0===p?void 0:p[0])&&((m=new zt(h)).setSource(exports.AudioSourceInfo.SCREENCAST),Jt.info("ScreenAudioTrack created",e.getPlainMediaTrackInfo(h)),h.addEventListener("ended",function(){return Jt.info("screen audio track ended",h.id)}),h.addEventListener("unmute",function(){return Jt.info("screen audio track unmute",h.id)}),h.addEventListener("mute",function(){return Jt.info("screen audio track mute",h.id)})),t.abrupt("return",m?[v,m]:[v]);case 3:throw t.prev=3,g=t.catch(1),e.parseScreenShareError(g);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e,r){return t.apply(this,arguments)}}(),ir=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return Jt.info("createScreenVideoAndAudioTrack",t),e.abrupt("return",rr(t,"withAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),nr=function(){var t=n($.mark(function t(r,i){var n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createMicrophoneAndCameraTracks",r,i),n=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=i||l).AEC,v=void 0===f||f,m=p.AGC,h=void 0===m||m,g=p.ANS,b=void 0===g||g,t.prev=1,t.next=2,Le({video:{deviceId:o,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:c,facingMode:a},audio:{deviceId:null==i?void 0:i.deviceId,source:exports.AudioSourceInfo.MIC,AEC:v,AGC:h,ANS:b}});case 2:return y=t.sent,k=y.getVideoTracks()[0],S=y.getAudioTracks()[0],Jt.info("CameraVideoTrack and MicrophoneTrack created",e.getPlainMediaStreamInfo(y)),k.addEventListener("ended",function(){return Jt.info("cam track ended",k.id)}),k.addEventListener("unmute",function(){return Jt.info("cam track unmute",k.id)}),k.addEventListener("mute",function(){return Jt.info("cam track mute",k.id)}),S.addEventListener("ended",function(){return Jt.info("mic track ended",S.id)}),S.addEventListener("unmute",function(){return Jt.info("mic track unmute",S.id)}),S.addEventListener("mute",function(){return Jt.info("mic track mute",S.id)}),P=new $t(k,Object.assign({},r,{frameRate:n,dimension:c,optimizationMode:d})),T=new Xt(S,Object.assign({},Object.assign({},i,{AEC:v,AGC:h,ANS:b}))),t.abrupt("return",[P,T]);case 3:throw t.prev=3,w=t.catch(1),e.parseVideoDeviceError(w);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e,r){return t.apply(this,arguments)}}(),or=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=p.length>1&&void 0!==p[1]?p[1]:exports.VideoSourceInfo.CAMERA,Jt.info("createCustomVideoTrack",r,e.getPlainMediaTrackInfo(r.mediaStreamTrack)),o=(n=r||{}).mediaStreamTrack,a=n.dimension,s=void 0===a?"VD_640x480":a,c=n.optimizationMode,u=void 0===c?"balanced":c,d=Math.min(r.frameRate||15,30),o instanceof MediaStreamTrack&&"video"===o.kind){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 1:return Jt.info("createCustomVideoTrack for",e.getPlainMediaTrackInfo(o)),o.addEventListener("ended",function(){return Jt.info("custom video track ended",o.id)}),o.addEventListener("unmute",function(){return Jt.info("custom video track unmute",o.id)}),o.addEventListener("mute",function(){return Jt.info("custom video track mute",o.id)}),(l=new Kt(o,Object.assign({},r,{frameRate:d,dimension:s,optimizationMode:u}))).setSource(i),t.abrupt("return",l);case 2:case"end":return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}(),ar=function(){var t=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=a.length>1&&void 0!==a[1]?a[1]:"mic",Jt.info("createCustomAudioTrack",r,i,e.getPlainMediaTrackInfo(r.mediaStreamTrack)),(n=(r||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 1:return Jt.info("createCustomAudioTrack succeed"),n.addEventListener("ended",function(){return Jt.info("custom audio track ended",n.id)}),n.addEventListener("unmute",function(){return Jt.info("custom audio track unmute",n.id)}),n.addEventListener("mute",function(){return Jt.info("custom audio track mute",n.id)}),(o=new zt(n)).setSource(i),t.abrupt("return",o);case 2:case"end":return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}();function sr(e,t,r,i){var n=re(l(e.prototype),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function cr(e,t,r){return t=l(t),d(e,ur()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function ur(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ur=function(){return!!e})()}var dr,lr=e.getReporter().getLoggerWithPrefix("[rtc-remotetrack]"),pr=pt(),fr=function(){function e(t,r,i){var n;return o(this,e),n=cr(this,e,[t,i]),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.userId=r,n}return f(e,yt),u(e,[{key:"getUserId",value:function(){return lr.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)}}])}(),vr=function(){function t(e,r,i){var n;return o(this,t),n=cr(this,t,[e,r,i]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.deviceId="",n}return f(t,fr),u(t,[{key:"getMediaStreamTrack",value:function(){return be.audioSFU?nt(this.sfuStream):sr(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){lr.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){lr.info("setVolume",e),pr.getElement(this)[0]&&(pr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(lr.info("getVolume"),pr.getElement(this)[0])return pr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(t){var r=this;return lr.info("setSpeaker",t),new Promise(function(i,n){var o,a=pr.getElement(r)[0];a||n(new e.DingRTCError(e.ErrorCode.InvaildState,"please playout audio first")),a.setSinkId||n(new e.DingRTCError(e.ErrorCode.SpeakerSetNotSupported)),null===(o=a.setSinkId)||void 0===o||o.call(a,t).then(function(){r.deviceId=t,i()}).catch(function(t){n(e.parseAudioDeviceError(t))})})}},{key:"getVolumeLevel",value:function(){return ot(this.analyser,this.sourceNode)}},{key:"play",value:function(){return lr.info("remote audio play"),sr(t,"innnerPlay",this,3)([{}])}}])}(),mr=function(){function e(t,r){return o(this,e),cr(this,e,[t,r])}return f(e,fr),u(e,[{key:"play",value:function(t,r){return lr.info("remote video play",this.getTrackId()),sr(e,"innnerPlay",this,3)([{mediaWrapperElement:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(lr.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&sr(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return lr.info("getCurrentFrameData"),this.isPlaying?at(pr.getElement(this)[0]):null}}])}();!function(e){var t,r,i,n,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",(i=e.SyncResponseCode||(e.SyncResponseCode={}))[i.SYNC_OK=0]="SYNC_OK",i[i.SYNC_PART_SUC=10]="SYNC_PART_SUC",i[i.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",i[i.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",i[i.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",i[i.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",i[i.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(n=e.GroupUpdate||(e.GroupUpdate={}))[n.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",n[n.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",n[n.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",n[n.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",n[n.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",n[n.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"}(dr||(dr={}));var hr={options:{syntax:"proto3"},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:"int32",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}}}}}}},gr=e.getProtobufRoot(hr),br=gr.lookupType("signal_msg.Response"),yr=gr.lookupType("signal_msg.BatchNotification"),kr=gr.lookupType("signal_msg.MediaMessage"),Sr=gr.lookupType("signal_msg.StreamNotification");gr.lookupType("signal_msg.ProgressNotification");var Pr=gr.lookupType("signal_msg.ServerFailoverNotification"),Tr=gr.lookupType("signal_msg.PublishRequest"),wr=gr.lookupType("signal_msg.SoacRequest"),Er=gr.lookupType("signal_msg.UnpublishRequest"),Ir=gr.lookupType("signal_msg.StreamControlRequest"),Mr=gr.lookupType("signal_msg.SubscribeRequest"),Or=gr.lookupType("signal_msg.SetStreamPropertiesRequest"),Rr=gr.lookupType("signal_msg.UnsubscribeRequest"),Ar=gr.lookupType("signal_msg.SubscriptionControlRequest"),xr=gr.lookupType("signal_msg.CreatePeerConnectionRequest"),Cr=gr.lookupType("signal_msg.ClosePeerConnectionRequest"),_r=gr.lookupType("signal_msg.BatchPublishRequest"),Dr=gr.lookupType("signal_msg.BatchUnpublishRequest"),jr=gr.lookupType("signal_msg.BatchSubscribeRequest"),Lr=gr.lookupType("signal_msg.BatchUnsubscribeRequest"),Nr=gr.lookupType("signal_msg.JoinGroupRequest"),Vr=gr.lookupType("signal_msg.SetGroupPropertiesRequest"),Fr=gr.lookupType("signal_msg.DismissGroupRequest"),Ur=gr.lookupType("signal_msg.LeaveGroupRequest"),Gr=gr.lookupType("signal_msg.SyncDataRequest"),Br=gr.lookupType("signal_msg.SyncDataByIdsRequest"),Hr=gr.lookupType("signal_msg.GroupChangeLog"),qr=gr.lookupType("signal_msg.GroupListChangeLog"),Wr=gr.lookupType("signal_msg.SetParticipantPropertiesRequest"),Yr=gr.lookupType("signal_msg.QueryStreamsVerRequest"),Jr=gr.lookupType("signal_msg.QueryStreamsRequest");function Qr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Qr=function(){return!!e})()}var Kr=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,Qr()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),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",Sr.decode(t)):"serverFailover"===e?this.emit("serverFailover",Pr.decode(t)):"media-message"===e?this.emit("media-message",kr.decode(t)):"group"===e?this.emit("group",Hr.decode(t)):"group-list"===e&&this.emit("group-list",qr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;yr.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=xr.encode(e).finish();return this.rpc("create-peer-connection",t,e).then(function(e){return e.createPeerConnectionResponse})}},{key:"closePeerConnection",value:function(e){var t=Cr.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=jr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then(function(e){return e.errorMsg})}},{key:"setGroupProperties",value:function(e){var t=Vr.encode(e).finish();return this.rpc("set-group-properties",t,e).then(function(e){return e.setGroupPropertiesResponse})}},{key:"batchUnSubscribe",value:function(e){var t=Lr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=_r.encode(e).finish();return this.rpc("batch-publish",t,e).then(function(e){return e.errorMsg})}},{key:"batchUnPublish",value:function(e){var t=Dr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=Tr.encode(e).finish();return this.rpc("publish",t,e).then(function(e){return e.publishResponse})}},{key:"setParticipantProperties",value:function(e){var t=Wr.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=wr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=Er.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=Ir.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=Or.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=Mr.encode(e).finish();return this.rpc("subscribe",t,e).then(function(e){return e.subscribeResponse})}},{key:"unsubscribe",value:function(e){var t=Rr.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=Ar.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=Yr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then(function(e){return e.queryStreamsVerResponse})}},{key:"getStreams",value:function(e){var t=Jr.encode(e).finish();return this.rpc("query-streams",t,e).then(function(e){return e.queryStreamsResponse})}},{key:"joinGroup",value:function(e){var t=Nr.encode(e).finish();return this.rpc("join-group",t,e).then(function(e){return e.joinGroupResponse})}},{key:"leaveGroup",value:function(e){var t=Ur.encode(e).finish();return this.rpc("leave-group",t,e).then(function(e){return e.leaveGroupResponse})}},{key:"dismissGroup",value:function(e){var t=Fr.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(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise(function(n,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),i),r.channel.signaling.rpc(e,t,i).then(function(t){var i=br.decode(t);i.code===dr.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),i),n(i)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),i),o(i))}).catch(function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)})})}}])}();function zr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(zr=function(){return!!e})()}var $r=function(){function t(){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,zr()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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 Xr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Zr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xr(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}function ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ri=function(){return!!e})()}var ii={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},ni={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},oi=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,ri()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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({},ni),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({},ii),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,i=Object.assign({source:this.source,trackStats:[]},ni,this.connection.peerConnectionStats);if(i.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),o=n.width,a=n.height,s=n.frameRate;i.captureFramesPerSecond=s===1/0?0:s||0,i.captureFrameWidth=o||0,i.captureFrameHeight=a||0}var c=new Map,u=Ve(i,this.lastVideoSendInfo);return t.forEach(function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var n=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(n.sendFrameWidth=t.frameWidth||0,n.sendFrameHeight=t.frameHeight||0,n.framesSent=t.framesSent||0,n.framesEncoded=t.framesEncoded||0,n.targetBitrate=t.targetBitrate||0,n.qpSum=t.qpSum||0,n.bytesSent=t.bytesSent||0,n.packetsSent=t.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=t.timestamp||0,n.totalEncodeTime=t.totalEncodeTime||0,n.keyFramesEncoded=t.keyFramesEncoded||0,n.firCount=t.firCount||0,n.pliCount=t.pliCount||0,n.retransmittedBytesSent=t.retransmittedBytesSent||0,n.retransmittedPacketsSent=t.retransmittedPacketsSent||0,n.qualityLimitationReason=t.qualityLimitationReason||"",n.web_powerEfficientEncoder=t.powerEfficientEncoder||"",n.web_encoderImplementation=t.encoderImplementation||"",n.web_qualityLimitationResolutionChanges=t.qualityLimitationResolutionChanges>=0?t.qualityLimitationResolutionChanges:-1,n.web_codecId=t.codecId||"",n.sendFramesPerSecond=t.framesPerSecond||0,n.sendFrameWidth>i.maxSendFrameWidth){if(i.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&o){var a=Ue(n.framesSent||n.framesEncoded,o.framesSent||o.framesEncoded);n.sendFramesPerSecond=Math.round(a/u)}if(n.framesEncoded){var s=Ue(n.framesEncoded,null==o?void 0:o.framesEncoded);i.encodeFramesPerSecond=Math.round(s/u)}i.sendFramesPerSecond=n.sendFramesPerSecond}c.set(t.ssrc,n),i.targetBitrate=n.targetBitrate,i.totalBytesSent+=n.bytesSent,i.totalPacketsSent+=n.packetsSent,i.totalEncodedTime+=n.totalEncodeTime,i.totalFramesEncoded+=n.framesEncoded,i.totalFramesSent+=n.framesSent,i.totalQpSum+=n.qpSum,i.maxSendFrameHeight=Math.max(n.sendFrameHeight,i.maxSendFrameHeight),c.set(t.ssrc,n)}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),i.totalFramesEncoded+=d.framesEncoded,i.totalEncodedTime+=d.totalEncodeTime,i.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,i.totalPacketsLost+=l.packetsLost,l.packetsLost===(p.packetsLost||0)&&(l.packetsSentForLost=p.packetsSentForLost||0,l.lostTimestamp=p.lostTimestamp||0),c.set(t.ssrc,l)}}),i.trackStats=c,i}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],i=ei(e.trackStats.entries());try{for(i.s();!(t=i.n()).done;){var n=kt(t.value,2),o=n[0],a=n[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=Ue(a.framesSent,s.framesSent),u=Ue(a.framesEncoded,s.framesEncoded),d=Ue(a.keyFramesEncoded,s.keyFramesEncoded),l=Ue(a.retransmittedBytesSent,s.retransmittedBytesSent),p=Ue(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=Ue(a.firCount,s.firCount),v=Ue(a.pliCount,s.pliCount),m=Ue(a.packetsSent,s.packetsSent),h=Ue(a.packetsSentForLost,s.packetsSentForLost),g=Ue(a.lostTimestamp,s.lostTimestamp),b=Ue(a.sentTimestamp,s.sentTimestamp),y=Ue(a.packetsLost,s.packetsLost),k=Ue(a.totalEncodeTime,s.totalEncodeTime),S=Ue(a.qpSum,s.qpSum),P=a.qualityLimitationReason,T=a.sendFrameWidth,w=Zr(Zr({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:P,web_powerEfficientEncoder:a.web_powerEfficientEncoder,web_encoderImplementation:a.web_encoderImplementation,web_qualityLimitationResolutionChanges:a.web_qualityLimitationResolutionChanges,web_codecId:a.web_codecId},a),{},{deltaQbSum:S,deltaPacketsSent:m,deltaPacketsLost:y,deltaFramesSent:c,deltaTimestampForLost:g,deltaFramesEncoded:u,deltaKeyFramesEncoded:d,deltaFirCount:f,deltaEncodedTime:k,deltaPliCount:v,deltaTimestampForSent:b,deltaPacketsSentForLost:h,deltaRetransmittedBytesSent:l,deltaRetransmittedPacketsSent:p});r.push(w)}}catch(e){i.e(e)}finally{i.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,t){var r={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 i,n=this.getLayersMetricInfo(e),o=n.tracksStatInfo,a=n.totalBytesSent,s=n.totalFramesEncoded,c=n.totalEncodedTime;o.length>1&&(r.attr_stream_options+="sim:".concat(o.length,"/"));for(var u={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],web_powerEfficientEncoder_sim:[],web_encoderImplementation_sim:[],web_qualityLimitationResolutionChanges_sim:[],web_codecId_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},d=[],l=0,p=Ue(e.timestamp,this.lastVideoSendInfo.timestamp),f=!0,v=0;v<o.length;v++){var m=o[v];u.attr_enc_key_frames_sim.push(m.deltaKeyFramesEncoded),u.attr_fir_count_sim.push(m.deltaFirCount),u.attr_pli_count_sim.push(m.deltaPliCount),u.attr_quality_limitation_reason_sim.push(m.qualityLimitationReason),u.web_powerEfficientEncoder_sim.push(m.web_powerEfficientEncoder),u.web_encoderImplementation_sim.push(m.web_encoderImplementation),u.web_qualityLimitationResolutionChanges_sim.push(m.web_qualityLimitationResolutionChanges),u.web_codecId_sim.push(m.web_codecId),u.attr_retx_bytes_sim.push(m.deltaRetransmittedBytesSent),u.attr_retx_packets_sim.push(m.deltaRetransmittedPacketsSent),u.attr_resolution_sim.push({count:m.deltaFramesSent||m.deltaFramesEncoded,index:v,resolution:"".concat(m.sendFrameWidth,"*").concat(m.sendFrameHeight)});var h=m.deltaFramesEncoded||m.deltaFramesSent;f&&(f=0===h),u.attr_encoded_framerate_sim.push(X({},v,Math.round(1e3*h/p))),u.attr_encode_qp_sim.push(X({},v,Math.round((m.deltaQbSum||0)/(h||Number.EPSILON))));var g=m.deltaTimestampForLost,b=m.deltaTimestampForSent,y=m.deltaPacketsLost,k=m.deltaPacketsSentForLost;if(y&&k&&g&&b){var S=y/g/(k/b);d.push(Math.max(Math.min(S,1),0))}}for(var P=0,T=Object.entries(u);P<T.length;P++){var w=kt(T[P],2),E=w[0],I=w[1];r[E]=I.length?JSON.stringify(I):""}var M=0,O=Ue(s,this.lastVideoSendInfo.totalFramesEncoded),R=Ue(c,this.lastVideoSendInfo.totalEncodedTime);O&&R&&(M=Math.round(1e3*R/O));var A=Ue(a,this.lastVideoSendInfo.totalBytesSent);r.attr_duration_ms=p,r.attr_bitrate=p>0?Math.min(Math.round(8*A*1e3/p),2e7):0,r.attr_enc_average_elapsed_ms=M,this.videoSendReport=r,f&&(r.attr_resolution_sim="null",r.attr_encoded_framerate_sim="null");var x={web_dtlsState:(null===(i=te(t.values()).find(function(e){return"transport"===e.type}))||void 0===i?void 0:i.dtlsState)||""};this.emit("video-send-stream",Object.assign(x,this.videoSendReport)),d.length&&(l=Math.min(Math.round(d.reduce(function(e,t){return t+e},0)/d.length*255),255)),this.bweReport={attr_duration_ms:p,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:l},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},ii,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 i=t.track.getMediaStreamTrack().getSettings(),n=i.channelCount,o=i.sampleRate;r.channels=n,r.sampleRate=o}}),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(Ue(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*Ue(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/Ue(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,t.originStats)})}},{key:"getStats",value:function(){var t,r,i=this,n=this.tranceiver,o=this.pc;if(!o||null==n||null===(t=n.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(n.sender.track))||void 0===r?void 0:r.then(function(e){return{videoMetrics:i.source?i.extractVideoMetrics(e):void 0,audioMetrics:i.source?void 0:i.extractAudioMetrics(e),originStats:e}})}}])}();function ai(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 si(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)?si(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 si(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ci(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ci=function(){return!!e})()}var ui={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},di={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},li=function(){function t(r){var i,n,a,s,c;o(this,t),a=this,s=l(s=t),n=d(a,ci()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var u=r.connection,p=r.transceiver,f=r.uid,v=r.stream,m=r.transceivers;return n.connection=u,n.pc=u.pc,n.tranceiver=p,n.tranceivers=m,n.firstReportTimer=e.addTimer(function(){n.getStats().then(function(e){n.makeFirstReport(e)})},400,"interval"),n.source="mcu"!==f&&(null===(i=v.media)||void 0===i||null===(i=i.video)||void 0===i?void 0:i.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},di),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},ui),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return f(t,$r),u(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=Object.assign({},ui,this.connection.peerConnectionStats);return i.timestamp=Date.now(),e.forEach(function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(i.bytesReceived=e.bytesReceived||0,i.packetsReceived=e.packetsReceived||0,r||(i.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?i.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:i.packetsReceivedForLost=i.packetsReceived||0),i.packetsLost=e.packetsLost||0,i.audioLevel=e.audioLevel||0,i.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(i.audioLevel=e.audioLevel))}),i}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map(function(e){return t.extractAudioMetrics(e,!0)}),i=Object.assign({},ui,this.connection.peerConnectionStats);i.timestamp=Date.now();var n,o=ai(r);try{for(o.s();!(n=o.n()).done;){var a=n.value;i.bytesReceived+=a.bytesReceived||0,i.packetsLost+=a.packetsLost||0,i.packetsReceived+=a.packetsReceived||0,i.audioLevel=Math.max(i.audioLevel,a.audioLevel||0),i.decodingNormal=Math.max(i.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return i.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?i.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:i.packetsReceivedForLost=i.packetsReceived||0,i}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},di,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 i;null!==(i=e.mimeType)&&void 0!==i&&i.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}}),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(Ue(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=Ue(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),i=Ue(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),n=Ue(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/i,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*n/(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,i=t.pliCount,n=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(n>0&&e.timestamp){var f=Ue(e.timestamp,n);if(e.bytesReceived-u>=0){var v=Ue(e.packetsLost,a),m=Ue(e.packetsReceivedForLost,d),h=0;try{h=Math.round(v/m*255)}catch(e){h=0}isNaN(h)&&(h=0);var g=Ue(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*g/f),attr_dec_frames:g,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:Ue(e.framesDropped,c),attr_fir_count:Ue(e.firCount,r),attr_freeze_count:Ue(e.freezeCount,o),attr_pli_count:Ue(e.pliCount,i),attr_retx_bytes:Ue(e.retransmittedBytesReceived,l),attr_retx_packets:Ue(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*Ue(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(h,255)),attr_resolution:JSON.stringify([{count:g,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,i=r.audioFirstFrame,n=r.audioFirstPacket,o=r.videoFirstPacket,a=t.audioMetrics,s=t.videoMetrics;if(a&&s){if((i||-1===(null==a?void 0:a.decodingNormal))&&n&&o)return void(this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a){if((i||-1===(null==a?void 0:a.decodingNormal))&&n)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&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==a?void 0:a.decodingNormal)>0&&!i&&(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,i=this.tranceiver,n=this.tranceivers,o=this.pc;if(!(o&&(null!=n&&n.length||null!=i&&i.receiver.track)))return Promise.resolve({});if(null==o||!o.getStats)throw new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var a=n.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!=i&&null!==(t=i.receiver)&&void 0!==t&&t.track?o.getStats(i.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,i,n;(r="stop",i=this,"function"==typeof(n=re(l(t.prototype),r,i))?function(e){return n.apply(i,e)}:n)([]),this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();function pi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return fi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?fi(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function fi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function vi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function mi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?vi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):vi(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 gi=e.getReporter().getLoggerWithPrefix("[rtc-subs]"),bi=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,hi()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"subIdAcc",{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,"rtcSignaling",{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,"logger",{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}),Object.defineProperty(r,"targetMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logTrackEnded",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track ended",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackUnmute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track unmute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackMute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track mute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"updateTransceiverListeners",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;null!==(e=r.transceiver)&&void 0!==e&&null!==(e=e.receiver)&&void 0!==e&&e.transport?(r.transceiver.receiver.transport.onerror=r._onDtlsError,r.transceiver.receiver.transport.onstatechange=r._onDtlsStateChange,null!==(t=r.transceiver)&&void 0!==t&&null!==(t=t.receiver)&&void 0!==t&&t.transport.iceTransport&&(r.transceiver.receiver.transport.iceTransport.onselectedcandidatepairchange=r._onSelectedCandidatePairChange.bind(r,r.transceiver.receiver))):r.logger.info("browser version low, no dtls transport to watch")}}),Object.defineProperty(r,"_onDtlsError",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.logger.error("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_error"),null==e||null===(t=e.error)||void 0===t?void 0:t.errorDetail)}}),Object.defineProperty(r,"_onDtlsStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_state_change"),r.transceiver.receiver.transport.state)}}),Object.defineProperty(r,"_onSelectedCandidatePairChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,i=null==e||null===(t=e.transport)||void 0===t||null===(t=t.iceTransport)||void 0===t?void 0:t.getSelectedCandidatePair();r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," selected_candidate_pair_change"),i)}}),r.subIdAcc="subIdAcc-".concat(t.subIdAcc++);var s=e.connection,c=e.stream,u=e.uid,p=e.resolutionInfo,f=e.userConfigResolution,v=e.targetMediaType;return r.connection=s,r.targetMediaType=v,r.resolutionInfo=p,r.userConfigResolution=f,r.rtcSignaling=s.rtcSignaling,r.stream=c,r.uid=u,r.reporter=s.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-subs]"),r.connection.once("ended",function(){r.clear()}),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=Y.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,i=this;if(be.audioSFU&&"audio"===e.kind){var n,o=null===(n=this.transceivers)||void 0===n?void 0:n.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!=o&&o.includes(e.id)&&(e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute)),this._stream=this._stream||new MediaStream([]),this._stream.addTrack(e)}else if(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)){e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute),this._stream=new MediaStream([e]);var a=document.createElement("video");a.onloadeddata=function(){a.srcObject=null,i.handleVideoFirstFrame()},a.srcObject=this._stream}}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===Y.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch(function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))})}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.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=yi(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.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()}},{key:"clear",value:function(){this.state!==Y.End&&(this.reset(),this.state=Y.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 li(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 li(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:Date.now()-this.startTime,remoteUserId:this.uid}),this.logger.info("video-first-frame sessionId=".concat(this.id))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,i=e.videoMetrics;if(r){var n,o=(null===(n=this.metricsMap.get(t))||void 0===n?void 0:n.audioMetrics)||{},a=Ve(r,o),s=Ue(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(i){var u,d,l=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=Ve(i,l),f=Ue(i.bytesReceived,l.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||i.codec,receiveResolution:{width:i.frameWidth,height:i.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(Ue(null==i?void 0:i.framesDecoded,l.framesDecoded)/p),receiveFrameRate:Math.round(Ue(null==i?void 0:i.framesReceived,l.framesReceived)/p),receiveFramesDropped:Ue(null==i?void 0:i.framesDropped,l.framesDropped),receiveBytes:i.bytesReceived,receivePackets:i.packetsReceived,receivePacketsLost:i.packetsLost,rtt:i.roundTripTime,timestamp:i.timestamp},m=this.connection.subSdpFmtpLines.some(function(e){return e.includes("64")}),h=(null===(d=this.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.source)===exports.VideoSourceInfo.CAMERA&&f>3e4&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&h?m&&v.receiveFramesDropped>0&&!be.downlinkForbidHighProfile&&this.connection.handleHighProfileFallback():this.stucked=h),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(mi({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-recv-stream",function(t){e.reporter.metric.audioRecvStream(mi({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}),e.logger.info("video-first-packet sessionId=".concat(e.id))}),this.monitor.on("video-recv-stream",function(t){e.reporter.metric.videoRecvStream(mi({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}))}}])}();Object.defineProperty(bi,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var yi=function(e,t){if(!t)return null;var r=t.resolutionLevel,i=e.media.video.highestResolutionLevel;if(i&&i<r){var n=Rt(i);return Ot(n,ke(e))}return t},ki=function(e){var t,r={audio:[],video:[]},i=pi(e);try{for(i.s();!(t=i.n()).done;){var n=t.value,o=n.stream,a=n.error,s=n.resolutionInfo,c=n.targetMediaType;if(a)gi.error("skip subscribe",o,a);else{var u=Si(o,s,c),d=u.audio,l=u.video;if("audio"===c&&d){var p=mi(mi({},d),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:ji()}]});be.audioSFU&&(p.ssrcGroup=new Array(6).fill(0).map(function(){return{ssrc:ji()}})),r.audio.push(p)}else if("video"===c&&l){var f,v;r.video.push(mi(mi({},l),{},{trackId:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.trackId,ssrcGroup:null===(v=o.media)||void 0===v||null===(v=v.video)||void 0===v?void 0:v.ssrcGroup,subSsrcGroup:{ssrc:ji(),rtxSsrc:ji()}}))}}}}catch(e){i.e(e)}finally{i.f()}return r},Si=function(e,t,r){var i=e.id,n=e.media,o=n.audio,a=n.video,s={};if(o&&"audio"===r)s.audio={from:i};else if(a&&"video"===r){var c;s.video={from:i,format:null===(c=n.video)||void 0===c?void 0:c.format,parameters:yi(e,t)}}return s},Pi=function(){var e=n($.mark(function e(t,r){var i,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=[],o={},t.forEach(function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo,u=e.targetMediaType;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var d=new bi({connection:r,uid:s,userConfigResolution:c,resolutionInfo:c&&yi(n,c),stream:n,targetMediaType:u});o[n.id]=d}}),s=new Promise(function(e,s){a=function(){var a=n($.mark(function a(){var c;return $.wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if((c=ki(t)).audio.length||c.video.length){a.next=1;break}return gi.info("batchSubscribe no valid media to sub"),a.abrupt("return",e(i));case 1:return a.next=2,Bi(r,c,o);case 2:r.rtcSignaling.batchSubscribe({connectionId:r.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:be.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:c}).then(function(){var r=n($.mark(function r(n){var a,s,c,u,d,l;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=1;break}return i.forEach(function(e){e.error=e.error||Se(e.stream,s)}),r.abrupt("return",e(i));case 1:c=pi(a),r.prev=2,d=$.mark(function e(){var r,n,a,s,c,d;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],d=t.findIndex(function(e){return e.stream.id===s.id}),"ok"===a&&c?(c.id=n,i[d].id=n,i[d].subscription=c):"ok"!==a&&(i[d].error=Se(c.stream,a));case 1:case"end":return e.stop()}},e)}),c.s();case 3:if((u=c.n()).done){r.next=5;break}return r.delegateYield(d(),"t0",4);case 4:r.next=3;break;case 5:r.next=7;break;case 6:r.prev=6,l=r.catch(2),c.e(l);case 7:return r.prev=7,c.f(),r.finish(7);case 8:e(i);case 9:case"end":return r.stop()}},r,null,[[2,6,7,8]])}));return function(e){return r.apply(this,arguments)}}()).catch(s);case 3:case"end":return a.stop()}},a)}));return function(){return a.apply(this,arguments)}}()}),r.addTask(a),e.abrupt("return",s);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ti=function(){var e=n($.mark(function e(t,r){var i,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=new Promise(function(e,o){i=function(){var i=n($.mark(function i(){var n,a;return $.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return n=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}),i.next=1,Yi(r,t);case 1:r.rtcSignaling.batchUnSubscribe({connectionId:r.id,audio:n,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(o);case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()}),r.addTask(i),e.abrupt("return",o);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function wi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ei(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?wi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wi(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ii(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return 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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}var Oi=e.getReporter().getLoggerWithPrefix("[rtc-sdp]"),Ri={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},Ai=0,xi=0,Ci=0,_i=new Set,Di=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(xi=e,Ai=(t<<r|2147483648)>>>0)},ji=function(){if(0==Ai||0==xi)return 0;var e=Math.min(xi+1,1e4);do{var t=Ai+(xi&Ci++);if(0!=t&&!_i.has(t))return t}while(--e>0);return 0},Li=function(t,r){var i,n;if((null===(i=t.rids)||void 0===i?void 0:i.length)>1)return e.Environment.isFirefox()&&(r=Gi(r)),r.rids=null===(n=t.rids)||void 0===n?void 0:n.map(function(e){return{direction:"recv",id:e.id}}),r.simulcast={dir1:"recv",list1:t.simulcast.list1},r},Ni=function(){var e=n($.mark(function e(r){var i,n,o,a,s,c,u;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,n=r.transceiver,o=i.remoteSDP,a=i.pc,e.next=1,a.createOffer();case 1:return s=e.sent,e.next=2,a.setLocalDescription(s);case 2:return i.localSDP=t.parse(s.sdp),c=i.localSDP.media.find(function(e){return e.mid==n.mid}),u=o.media.find(function(e){return e.mid==n.mid}),Li(c,u),e.next=3,a.setRemoteDescription({type:"answer",sdp:t.write(o)});case 3:i.remoteSDP=o;case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),Vi=function(){var r=n($.mark(function r(i,n){var o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return o=i.pc,a=i.idToTransceiverMap,s=i.remoteSDP,c=new MediaStream(n.map(function(e){return e.getMediaStreamTrack()})),u=n.map(function(e){var t={direction:"sendonly"};if(e instanceof Kt){var r=Ut(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 n=i.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Kt&&n.sender.setParameters){var o=e.optimizationMode,s=n.sender.getParameters();s.degradationPreference=Ri[o]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(Oi.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach(function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,Oi.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}})),Oi.info("adjustUplinkSDPWhenPublish setParameters",s),n.sender.setParameters(s)}return a.set(e.getTrackId(),n),n}),r.next=1,o.createOffer();case 1:return d=r.sent,l=t.parse(d.sdp),r.next=2,o.setLocalDescription(d);case 2:i.localSDP=l,s.groups[0].mids=i.localSDP.groups[0].mids,p=Ii(u),r.prev=3,v=$.mark(function t(){var r,i,n,o,a,c,u;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:r=f.value,i=s.media.find(function(e){return e.type===r.sender.track.kind}),e.Environment.isFirefox()&&"video"===i.type&&(delete i.rids,delete i.simulcast),n=Ei(Ei({},i),{},{ext:te(i.ext),mid:r.mid}),o=l.media.find(function(e){return e.mid==r.mid}),a=new URLSearchParams(location.search).get("startkbs")||2e3,c=new URLSearchParams(location.search).get("minkbs"),u=new URLSearchParams(location.search).get("maxkbs"),Oi.info("startkbs, minkbs, maxkbs",a,c,u),n.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&&be.highStartBitrate?t.push("x-google-start-bitrate=".concat(a)):t.push("x-google-start-bitrate=500"),c&&t.push("x-google-min-bitrate=".concat(c)),u&&t.push("x-google-max-bitrate=".concat(u)),e.config=t.join(";")}}),Li(o,n),s.media.push(n);case 1:case"end":return t.stop()}},t)}),p.s();case 4:if((f=p.n()).done){r.next=6;break}return r.delegateYield(v(),"t0",5);case 5:r.next=4;break;case 6:r.next=8;break;case 7:r.prev=7,m=r.catch(3),p.e(m);case 8:return r.prev=8,p.f(),r.finish(8);case 9:return window.remoteSDP=s,r.next=10,o.setRemoteDescription({type:"answer",sdp:t.write(s)});case 10:return i.remoteSDP=s,r.abrupt("return",{localSDP:i.localSDP,stream:c});case 11:case"end":return r.stop()}},r,null,[[3,7,8,9]])}));return function(e,t){return r.apply(this,arguments)}}(),Fi=function(){var e=n($.mark(function e(r,i){var n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.pc,o=r.remoteSDP,i.map(function(e){return e.transceiver}).forEach(function(e){if(e){n.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=1,n.createOffer();case 1:return a=e.sent,s=t.parse(a.sdp),e.next=2,n.setLocalDescription(a);case 2:return r.localSDP=s,o.groups[0].mids=s.groups[0].mids,r.remoteSDP=o,e.next=3,n.setRemoteDescription({type:"answer",sdp:t.write(o)});case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ui=function(t,r,i){var n=t.ssrc,o=t.rtxSsrc;!function(e){e.ssrc&&_i.add(e.ssrc),e.rtxSsrc&&_i.add(e.rtxSsrc)}(t),r.ssrcGroups=[],o&&r.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(o)}),r.ssrcs=[],[n,o].filter(function(e){return void 0!==e}).forEach(function(t){r.ssrcs.push({attribute:"msid",value:"".concat(i," v").concat(n),id:t},{attribute:"cname",value:e.createUuid(),id:t})})},Gi=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},Bi=function(){var e=n($.mark(function e(r,i,n){var o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w,E,I,M,O,R,A,x,C,_,D,j,L,N,V,F,U,G,B,H,q;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(c=r.pc,u=r.idToTransceiverMap,d=r.remoteSDP,l=r.idToTransceiversMap,p=d.media.find(function(e){return"video"===e.type}),f=d.media.find(function(e){return"audio"===e.type}),v=null===(o=p.ssrcs)||void 0===o?void 0:o.find(function(e){return"msid"===e.attribute}).value.split(" ")[0],null!==(a=i.audio)&&void 0!==a&&a[0])if(h=null===(m=i.audio)||void 0===m?void 0:m[0],g=h.from,be.audioSFU){if(l.get(g)){b=Ii(l.get(g));try{for(b.s();!(y=b.n()).done;)y.value.direction="recvonly"}catch(e){b.e(e)}finally{b.f()}k=d.media.filter(function(e){return"audio"===e.type}),S=Ii(k);try{for(S.s();!(P=S.n()).done;)P.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"})}),l.set(g,r.mcuAudioTranceivers);n[g].addTransceivers(l.get(g))}else u.get(g)||u.set(g,r.mcuAudioTranceiver),u.get(g).direction="recvonly",f.direction="sendonly",n[g].addTransceiver(u.get(g));T=Ii(i.video),e.prev=1,E=$.mark(function e(){var r,i,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=w.value,i=r.from,o=u.get(i)){e.next=1;break}u.set(i,c.addTransceiver("video",{direction:"recvonly"})),e.next=5;break;case 1:if("inactive"===o.direction){e.next=4;break}return o.direction="inactive",e.next=2,c.createOffer();case 2:return a=e.sent,e.next=3,c.setLocalDescription(a);case 3:return d.media.find(function(e){return e.mid==o.mid}).direction="inactive",e.next=4,c.setRemoteDescription({type:"answer",sdp:t.write(d)});case 4:u.get(i).direction="recvonly";case 5:n[i].addTransceiver(u.get(i));case 6:case"end":return e.stop()}},e)}),T.s();case 2:if((w=T.n()).done){e.next=4;break}return e.delegateYield(E(),"t0",3);case 3:e.next=2;break;case 4:e.next=6;break;case 5:e.prev=5,H=e.catch(1),T.e(H);case 6:return e.prev=6,T.f(),e.finish(6);case 7:return e.next=8,c.createOffer();case 8:return I=e.sent,M=t.parse(I.sdp),d.groups[0].mids=M.groups[0].mids,e.next=9,c.setLocalDescription(I);case 9:r.localSDP=M,be.audioSFU&&i.audio[0]&&(O=i.audio[0],R=O.ssrcGroup,A=O.from,l.get(A).forEach(function(e,t){var r,i=null===(r=R[t])||void 0===r?void 0:r.ssrc,n=d.media.find(function(t){var r=t.mid,i=t.type;return r==e.mid&&"audio"===i});n||(n=Ei(Ei({},f),{},{mid:e.mid}),d.media.push(n)),n.ssrcs=Qi(i,v),n.direction="sendonly"})),x=Ii(i.video),e.prev=10,_=$.mark(function e(){var t,r,i,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=C.value,r=t.from,i=t.subSsrcGroup,o=u.get(r),(a=d.media.find(function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r}))||((a=Ei({},p)).mid=o.mid,d.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,Ui(i,a,v);case 1:case"end":return e.stop()}},e)}),x.s();case 11:if((C=x.n()).done){e.next=13;break}return e.delegateYield(_(),"t1",12);case 12:e.next=11;break;case 13:e.next=15;break;case 14:e.prev=14,q=e.catch(10),x.e(q);case 15:return e.prev=15,x.f(),e.finish(15);case 16:return Oi.info("sub remoteSDP before remove high profile",t.write(d)),qi(d),r.remoteSDP=d,D=t.write(d),Oi.info("sub remoteSDP after remove high profile",D),e.next=17,c.setRemoteDescription({type:"answer",sdp:D});case 17:null!==(s=i.audio)&&void 0!==s&&s[0]&&(L=null===(j=i.audio)||void 0===j?void 0:j[0],N=L.from,be.audioSFU||n[N].addTransceiver(u.get(N))),V=Ii(i.video);try{for(V.s();!(F=V.n()).done;)G=F.value,B=G.from,null===(U=n[B])||void 0===U||U.updateTransceiverListeners()}catch(e){V.e(e)}finally{V.f()}case 18:case"end":return e.stop()}},e,null,[[1,5,6,7],[10,14,15,16]])}));return function(t,r,i){return e.apply(this,arguments)}}(),Hi=function(e){Wi(e,function(e){return!/profile-level-id=42e01f/i.test(e)&&/profile-level-id/i.test(e)})},qi=function(e){Wi(e,function(e){return/profile-level-id=64/i.test(e)&&/profile-level-id/i.test(e)})},Wi=function(e,t){e.media.forEach(function(e){if("video"===e.type){var r=e.rtp.filter(function(e){return"H264"===e.codec}).filter(function(r){return e.fmtp.find(function(e){return e.payload===r.payload&&t((null==e?void 0:e.config)||"")})}),i=new Map;e.fmtp.forEach(function(e){/apt=\d+/i.test(e.config)&&i.set(e.payload,e.config.split("=")[1])}),Oi.info("rtxPayloadMap",Array.from(i.entries())),e.rtp=e.rtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===i.get(e.payload)})}),e.fmtp=e.fmtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===i.get(e.payload)})}),e.payloads=e.payloads.split(" ").map(function(e){return e.trim()}).filter(function(e){return!r.find(function(t){return"".concat(t.payload)===e||"".concat(t.payload)===i.get(parseInt(e))})}).join(" "),e.rtcpFb=e.rtcpFb.filter(function(e){return!r.find(function(t){return parseInt("".concat(t.payload))===parseInt("".concat(e.payload))||"".concat(t.payload)===i.get(parseInt("".concat(e.payload)))})})}})},Yi=function(){var e=n($.mark(function e(r,i){var n,o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=r.pc,o=r.remoteSDP,a=[],s=Ii(i);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,te(l))}catch(e){s.e(e)}finally{s.f()}return a.forEach(function(e){e.direction="inactive"}),e.next=1,n.createOffer();case 1:return p=e.sent,e.next=2,n.setLocalDescription(p);case 2:r.localSDP=t.parse(p.sdp),f=$.mark(function e(){var t;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=m[v],o.media.find(function(e){return e.mid==t.mid}).direction="inactive";case 1:case"end":return e.stop()}},e)}),v=0,m=a;case 3:if(!(v<m.length)){e.next=5;break}return e.delegateYield(f(),"t0",4);case 4:v++,e.next=3;break;case 5:return r.remoteSDP=o,e.next=6,n.setRemoteDescription({type:"answer",sdp:t.write(o)});case 6:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ji=function(e,t){var r=t.media;return e.media.forEach(function(e){var t=e.mid,i=e.ssrcGroups,n=void 0===i?[]:i,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex(function(e){return e.mid==t&&e.type===s});c>-1&&(r[c]=Ei(Ei({},r[c]),{},{ssrcGroups:n,ssrcs:a}))}),t},Qi=function(t,r){return[{attribute:"msid",value:"".concat(r," v").concat(t),id:t},{attribute:"cname",value:e.createUuid(),id:t}]},Ki=function(r,i,n){var o=i.direction,a=i.remoteSDP;Oi.info("origin answer for createpc",i.id,r);var s=t.parse(r);s.media.forEach(function(t){t.candidates.forEach(function(t){t.generation=0,t["network-cost"]=e.isPrivateIP(t.ip)?10:1e3})}),n&&(s=function(e,t){var r=t.media.find(function(e){return"audio"===e.type}),i=t.media.find(function(e){return"video"===e.type});return e.media.forEach(function(t,n){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[n]=Ei(Ei({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[n]=Ei(Ei({},i),{},{mid:o,ssrcGroups:s,ssrcs:u}),l.length&&(e.media[n].rids=l,e.media[n].simulcast={dir1:"recv",list1:l.map(function(e){return"~".concat(e.id)}).join(";")}))}),e}(a,s));var c=s.media.find(function(e){return"video"===e.type});if("uplink"===o&&e.Environment.isFirefox()&&be.simulcast&&(c.ext=c.ext.filter(function(e){return!e.uri.includes("rtp-stream-id")})),!c.ssrcs&&"downlink"===o){var u=ji(),d=s.msidSemantic.token;c.ssrcs=Qi(u,d)}be.preferH264CbProfile&&Hi(s),i.remoteSDP=s;var l=t.write(s);return Oi.info("final answer for createpc",i.id,l),l},zi=function(r,i){var n=i.direction,o=t.parse(r);if(qi(o),be.preferH264CbProfile&&Hi(o),be.disableTransportCC&&"uplink"===n&&function(e){e.media.forEach(function(e){e.ext=e.ext.filter(function(e){return!e.uri.includes("transport-wide-cc")}),e.rtcpFb=e.rtcpFb.filter(function(e){return"transport-cc"!==e.type})})}(o),"downlink"===n&&!be.downlinkForbidHighProfile){var a=[];o.media.find(function(e){return"video"===e.type}).fmtp.forEach(function(e){var t=e.config;t.includes("profile-level-id")&&a.push(t)}),i.subSdpFmtpLines=a}if(e.Environment.isFirefox()&&(o=Xi(o)),"uplink"===n&&e.Environment.isFirefox()&&be.simulcast){var s=o.media.find(function(e){return"video"===e.type});Gi(s)}return i.localSDP=o,o},$i=function(e){var t=e.localSDP,r=e.remoteSDP,i=e.sessionManager,n=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),d=te(i.sessions.values());if("downlink"===c){var l=r.media.slice(2),p=d.filter(function(e){return e instanceof bi}),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&&!be.audioSFU&&(a.set(f.id,n),f.addTransceiver(n));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}),i=p.find(function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)}),n=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&i?(a.set(i.stream.id,n),i.addTransceiver(n)):"audio"===e.type&&v.push(n))}),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var m=d.filter(function(e){return e instanceof an});u.forEach(function(e){var t={direction:e.direction},r=m.find(function(t){return t.mid==e.mid});if("sendonly"===e.direction&&r){var i=r.tracks[0],n=(null==i?void 0:i.getMediaStreamTrack())||(null==i?void 0:i.trackMediaType);if(i instanceof Kt){var s=Ut(i).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(n,t);a.set(i.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)})}},Xi=function(e){return function(e,t){if(e){var r,i=e.fmtp,n=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=Ii(i);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,m=Ii(f);try{for(m.s();!(v=m.n()).done;){var h=kt(v.value.split("="),2),g=h[0],b=h[1];c[p][g]=b}}catch(e){m.e(e)}finally{m.f()}}}catch(e){u.e(e)}finally{u.f()}for(var y in c){var k=c[y];(t(k)||s.includes(+k.apt))&&s.push(parseInt(y))}if(s.length){for(var S=i.length-1;S>=0;S--){var P=i[S].payload;s.includes(P)&&i.splice(S,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var w=a.length-1;w>=0;w--)s.includes(parseInt("".concat(a[w].payload)))&&a.splice(w,1);e.payloads=n.split(" ").map(Number).filter(function(e){return!s.includes(e)}).join(" ")}}}(e.media.find(function(e){return"video"===e.type}),function(e){return e["profile-level-id"]&&!e["packetization-mode"]}),e};function Zi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function en(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Zi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Zi(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function tn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return rn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?rn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function rn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function nn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(nn=function(){return!!e})()}var on=e.getReporter().getLoggerWithPrefix("[publication]"),an=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,nn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"rtcSignaling",{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,"logger",{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,"rtcStreamMuted",{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.rtcSignaling=s.rtcSignaling,r.uid=c,r.reporter=s.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtp-publication]"),r.state=Y.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),p.forEach(function(e){e.on(de,r.handleTracEvent)}),p[0]instanceof Kt&&(r.encodings=Ut(p[0]).encodings),r.state=Y.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!==Y.Processing?Promise.resolve():un([this],{connection:this.connection}).catch(function(r){t.clear(),t.logger.warn("negative ack for unpublish, ".concat(e.tryJsonStringify(r)))})}},{key:"mute",value:(i=n($.mark(function e(){var t,r,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===Y.Processing&&"muted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore mute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!0,this.id),this.rtcStreamMuted="muted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,i=e.catch(2),this.logger.error("mute error",this.id,i),this.rtcStreamMuted="unmuted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return i.apply(this,arguments)})},{key:"unmute",value:(r=n($.mark(function e(){var t,r,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===Y.Processing&&"unmuted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore unmute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!1,this.id),this.rtcStreamMuted="unmuted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,i=e.catch(2),this.logger.error("unmute error",this.id,i),this.rtcStreamMuted="muted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0],r=this.connection.idToTransceiverMap.get(t.getTrackId());this.addTransceiver(r),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this,r=this.connection,i=this.transceiver,o=e.getMediaStreamTrack().getSettings(),a=o.width,s=o.height,c=Ft(a,s);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:c});var u=function(e,t){var r=jt(e,t),i=function(i){var n=kt(Lt(e,t,i,r),2);n[0];var o=1/(n[1]/t);return Math.max(o,1)};return{ld:i(St.LD),sd:i(St.SD),fhd:i(r)}}(a,s);r.addTask(n($.mark(function e(){var r;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t.logger.info("scales",u),(r=i.sender.getParameters()).encodings.forEach(function(e){e.scaleResolutionDownBy=u[e.rid]}),t.logger.info("handleRepublish setParameters",r),e.abrupt("return",i.sender.setParameters(r).then(function(){console.log(i.sender.getParameters().encodings)}));case 1:case"end":return e.stop()}},e)})))}},{key:"handleTracEvent",value:function(e,t){var r,i=this,n={replace:function(){return i.replaceTrack(t.getMediaStreamTrack())},mute:function(){return i.mute()},unmute:function(){return i.unmute()},republish:function(){be.republish?i.handleRepublish(t):i.stop().then(function(){i.connection.sessionManager.serviceManager.client.publish([t])})},stop:function(){return i.stop()},optimizationMode:function(){return i.updateOptionzationMode()},mirror:function(){return i.handleMirror(t)}};return null===(r=n[e])||void 0===r?void 0:r.call(n)}},{key:"clear",value:function(){var e=this;this.state!==Y.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach(function(t){t.off(de,e.handleTracEvent)}),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.state=Y.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],i=r.index,n=r.bitrate;if(this.logger.debug("applyOptions",e),!(i<this.feedbackIndex||this.state!==Y.Processing)){this.feedbackIndex=i;var o=this.transceiver;this.connection.addTask(function(){return new Promise(function(r){var i,a=0===n,s=!1,c=o.sender.getParameters(),u=e.map(function(e){return e.rid}),d=tn(c.encodings);try{for(d.s();!(i=d.n()).done;){var l,p=i.value,f=tn(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()}return t.logger.info("encodings",c.encodings),s&&t.logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then(function(){return Ni(t).then(r)})})})}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,i=this.transceiver,n=this.connection;if(r[0]instanceof Kt&&null!=i&&null!==(e=i.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;n.addTask(function(){var e=i.sender.getParameters();return e.degradationPreference=Ri[o]||"balanced",t.logger.info("updateOptionzationMode setParameters",e),i.sender.setParameters(e),Ni(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=Y.Processing,this.feedbackIndex=-1,this.monitor=new oi(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;if(this.transceiver){null===(t=this.transceiver.sender.track)||void 0===t||t.stop();try{this.transceiver.sender.replaceTrack(e)}catch(e){this.logger.error("_DEV_TODO_","sender replaceTrack error",e)}}}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,i=e.videoMetrics;if(r){var n,o=(null===(n=this.metricsMap.get(t))||void 0===n?void 0:n.audioMetrics)||{},a=Ve(r,o),s=Ue(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(i){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=Ve(i,f),m=Ue(i.totalBytesSent,f.totalBytesSent),h={codec:this.connection.peerConnectionStats.videoCodec||i.codec,sendFrameRate:Math.round(i.sendFramesPerSecond),captureFrameRate:i.captureFramesPerSecond,encodeFrameRate:i.encodeFramesPerSecond,qpSum:i.totalQpSum||0,targetBitrate:i.targetBitrate,encodeLayers:p.length,sendLayers:p.filter(function(e){return e.active}).length,outgingBitrate:i.availableOutgoingBitrate,sendResolution:{width:i.maxSendFrameWidth,height:i.maxSendFrameHeight},captureResolution:{width:i.captureFrameWidth,height:i.captureFrameHeight},sendBytes:i.totalBytesSent,sendPackets:i.totalPacketsSent,sendPacketsLost:i.totalPacketsLost,timestamp:i.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||i.roundTripTime,sendBitrate:8*m/v};this.videoStatsMap.set(t,h)}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(en({sessionId:e.id},t))}),this.monitor.on("video-send-stream",function(t){e.reporter.metric.videoSendStream(en({sessionId:e.id},t))}),this.monitor.on("bwe",function(t){e.reporter.metric.bwe(en({sessionId:e.id},t))})}}]);var r,i}(),sn=function(){var e=n($.mark(function e(t,r){var i,n,o,a,s,c=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=c.length>2&&void 0!==c[2]?c[2]:["common"],n={},e.next=1,Vi(r,t);case 1: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)n.audio=[{source:"mic",autoMix:i,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Kt){var c;n.video=n.video||[];var u=o.ssrcGroups,d=void 0===u?[]:u,l=Ut(e),p=l.encodings,f=l.resolutionLevel;p.length>1&&(d=p.map(function(){return{semantics:"FID",ssrcs:"".concat(ji()," ").concat(ji())}}));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])}}),m=p[p.length-1],h={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(m.maxBitrate),resolution:{width:m.targetWidth,height:m.targetHeight},framerate:m.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}}})};n.video.push(h)}}),e.abrupt("return",n);case 2:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),cn=function(e){var t=e.tracks,r=e.connection,i=e.labels,o=e.existedPublications,a=void 0===o?[]:o,s=e.mixedLocalAudioTrack,c={videoPubResultArr:[]},u=[];t.forEach(function(t){var r;if("audio"!==t.trackMediaType||t.source!==exports.AudioSourceInfo.MIC&&t.source!==exports.AudioSourceInfo.SCREENCAST)c.videoPubResultArr.push({publication:new an(en(en({},e),{},{tracks:[t]})),track:t});else{var i=a.find(function(e){var t,r,i;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(i=e.tracks)||void 0===i?void 0:i[0].source)===exports.AudioSourceInfo.SCREENCAST)}),n=u.find(function(e){var t,r,i;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(i=e.tracks)||void 0===i?void 0:i[0].source)===exports.AudioSourceInfo.SCREENCAST)});i?(i.tracks.push(t),r=i):n?(n.tracks.push(t),r=n):r=new an(en(en({},e),{},{tracks:[s]})),c.audioPubResult={publication:r,track:t}}});var d=t.filter(function(e){return"audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST)});d.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC?s.setMicAudioTrack(e):s.setScreenAudioTrack(e)});var l=[],p=t.filter(function(e){return!("audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST))});if(l.push.apply(l,te(p)),d.length&&(null==s||s.updateMixedAudioTrackToPub(),s.isPublished()||l.push(s)),l.length){var f,v=new Promise(function(e,t){f=function(){var o=n($.mark(function o(){var a,u;return $.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.next=1,sn(l,r,i);case 1:return a=o.sent,u={connectionId:r.id,media:a,simulcast:Tt(l.find(function(e){return e.source===exports.VideoSourceInfo.CAMERA})),simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},o.abrupt("return",r.rtcSignaling.batchPublish(u).then(function(){var t=n($.mark(function t(r){var i,n,o,a,u,l;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=r.detailStatus,"ok"===(n=r.globalStatus)){t.next=1;break}return c.videoPubResultArr.forEach(function(e){e.error=Pe(e.track,n)}),c.audioPubResult&&(c.audioPubResult.error=Pe(c.audioPubResult.track,n)),t.abrupt("return",e(c));case 1:o=tn(i),t.prev=2,u=$.mark(function e(){var t,r,i,n,o,u,l;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=a.value,r=t.id,i=t.origin,n=t.msg,s.getTrackId()===i.id?c.audioPubResult&&(o=c.audioPubResult.publication,"ok"===n&&o?(o.initInner(r),s.setPublication(o),d.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC&&e.muted&&e.emit(de,"mute")})):"ok"!==n&&(c.audioPubResult.error=Pe(c.audioPubResult.track,n))):(u=c.videoPubResultArr.find(function(e){return e.track.getTrackId()===i.id}),l=(u||{}).publication,"ok"===n&&l?l.initInner(r):"ok"!==n&&(u.error=Pe(u.track,n)));case 1:case"end":return e.stop()}},e)}),o.s();case 3:if((a=o.n()).done){t.next=5;break}return t.delegateYield(u(),"t0",4);case 4:t.next=3;break;case 5:t.next=7;break;case 6:t.prev=6,l=t.catch(2),o.e(l);case 7:return t.prev=7,o.f(),t.finish(7);case 8:e(c);case 9:case"end":return t.stop()}},t,null,[[2,6,7,8]])}));return function(e){return t.apply(this,arguments)}}()).catch(function(e){on.info("batchPublishStart error",e),t(e)}));case 2:case"end":return o.stop()}},o)}));return function(){return o.apply(this,arguments)}}()});return r.addTask(f),v}return Promise.resolve({videoPubResultArr:[],audioPubResult:void 0})},un=function(){var e=n($.mark(function e(t,r){var i,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=new Promise(function(e,o){i=function(){var i=n($.mark(function i(){var n,a;return $.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return n=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}),i.next=1,Fi(r.connection,t);case 1:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:n,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(o);case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()}),r.connection.addTask(i),e.abrupt("return",o);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function dn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(dn=function(){return!!e})()}var ln={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},pn=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,dn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},ln)}),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),i="";return t.forEach(function(t){var n;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===i)e.Environment.networkType=(null!==(n=t.networkType)&&void 0!==n?n:e.Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(t.type)&&"succeeded"===t.state)i=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 fn(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 vn(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)?vn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 vn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function mn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(mn=function(){return!!e})()}var hn=function(){function r(i){var a,s,c,u,p,f;o(this,r),s=this,c=l(c=r),a=d(s,mn()?Reflect.construct(c,[],l(s).constructor):c.apply(s,u)),Object.defineProperty(a,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"state",{enumerable:!0,configurable:!0,writable:!0,value:J.New}),Object.defineProperty(a,"processingExchangeSdp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"peerConnectionStats",{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,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"subSdpFmtpLines",{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,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(a,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(p=n($.mark(function e(){var t,r=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]&&r[0],"uplink"===a.direction?(a.pc.addTransceiver("audio",{direction:"sendonly"}),a.pc.addTransceiver("video",{direction:"sendonly"})):(a.mcuAudioStream=null,a.mcuAudioTranceiver=a.pc.addTransceiver("audio",{direction:"recvonly"}),a.pc.addTransceiver("video",{direction:"recvonly"})),t&&$i(a),e.next=1,a.exchangeSdpForCreatePc(t);case 1:a.state=J.Idle,a.enquenTask.start();case 2:case"end":return e.stop()}},e)})),function(){return p.apply(this,arguments)})}),Object.defineProperty(a,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;a.logger.info("connectionId:".concat(a.id," ice gathering state: ").concat(t))}}),Object.defineProperty(a,"exchangeSdpForCreatePc",{enumerable:!0,configurable:!0,writable:!0,value:(f=n($.mark(function r(){var i,o,s,c,u,d,l,p,f,v=arguments;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return i=v.length>0&&void 0!==v[0]&&v[0],a.processingExchangeSdp=!0,r.prev=1,r.next=2,a.pc.createOffer();case 2:return o=r.sent,a.logger.info("connectionId:".concat(a.id," origin offer"),o),i&&(o.sdp=t.write(Ji(a.localSDP,t.parse(o.sdp)))),s=zi(o.sdp,a),a.offerSDP=s,o={type:"offer",sdp:t.write(s)},r.next=3,a.pc.setLocalDescription(o);case 3:return a.logger.info("connectionId:".concat(a.id," set local sdp success")),c={direction:"downlink"!==a.direction?"in":"out",sdpOffer:o.sdp,connectionId:a.id,isFailover:i,optionsJsonStr:JSON.stringify({supportCVO:1})},i&&((u=t.parse(o.sdp)).media=u.media.slice(0,2),u.groups=[{mids:"0 1",type:"BUNDLE"}],c.sdpOffer=t.write(u)),d=function(){var t=n($.mark(function t(){var r,i,n,o;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,"connected"===(null===(r=a.sessionManager)||void 0===r||null===(r=r.serviceManager)||void 0===r||null===(r=r.client)||void 0===r?void 0:r.connectionState)){t.next=1;break}throw new Error("signaling disconnected");case 1:if(c.isFailover||!a.prevId){t.next=3;break}return t.next=2,a.stopSinglePC(!0);case 2:a.id="".concat(a.direction,"_").concat(e.createUuid()),c.connectionId=a.id;case 3:return a.prevId=a.id,t.next=4,a.rtcSignaling.createPeerConnection(c);case 4:return i=t.sent,n=i.sdpAnswer,a.logger.info("connectionId:".concat(a.id," receive answer success")),t.abrupt("return",n);case 5:throw t.prev=5,o=t.catch(0),a.logger.error("connectionId:".concat(a.id," signal createpc failed: ").concat(o)),o;case 6:case"end":return t.stop()}},t,null,[[0,5]])}));return function(){return t.apply(this,arguments)}}(),r.next=4,Ge({fn:d,times:3,interval:2e3});case 4:return l=r.sent,p=Ki(l,a,i),r.next=5,a.pc.setRemoteDescription({sdp:p,type:"answer"});case 5:r.next=7;break;case 6:return r.prev=6,f=r.catch(1),a.logger.error("connectionId:".concat(a.id," Failed to exchangeSDP. Message: ").concat(f.message)),a.fireEndedEvent(),r.abrupt("return",Promise.reject(f));case 7:return r.prev=7,a.processingExchangeSdp=!1,r.finish(7);case 8:case"end":return r.stop()}},r,null,[[1,6,7,8]])})),function(){return f.apply(this,arguments)})}),a.pc=null;var v=i.direction,m=i.sessionManager;return a.rtcSignaling=m.serviceManager.rtcSignaling,a.sessionManager=m,a.reporter=m.reporter,a.logger=a.reporter.getLoggerWithPrefix("[rtc-peerconn]"),a.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,i=!1,n=function(){for(;r<e&&t.length;){r++;var i=t.shift();i&&i().finally(function(){r--,n()})}};return{add:function(e){t.push(e),i&&n()},start:function(){i=!0,n()}}}(),a.subSdpFmtpLines=[],a.direction=v,a.idToTransceiverMap=new Map,a.idToTransceiversMap=new Map,a.createPeerConnection(),a.id="".concat(a.direction,"_").concat(e.createUuid()),a}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.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.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?be.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==J.Ended&&(this.state=J.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"onIceCandidate",value:function(e){var t,r=(t=null==e?void 0:e.candidate)?{address:t.address,candidate:t.candidate,component:t.component,foundation:t.foundation,port:t.port,priority:t.priority,protocol:t.protocol,relatedAddress:t.relatedAddress,relatedPort:t.relatedPort,relayProtocol:t.relayProtocol,sdpMLineIndex:t.sdpMLineIndex,sdpMid:t.sdpMid,tcpType:t.tcpType,type:t.type,usernameFragment:t.usernameFragment}:t;this.logger.info("connectionId:".concat(this.id," onIceCandidate"),r)}},{key:"clearPcForReoffer",value:(i=n($.mark(function t(){var r;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.state!==J.New){t.next=1;break}return t.abrupt("return",Promise.reject());case 1:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),t.prev=2,t.next=3,this.stopSinglePC(!0);case 3:this.removeAllListeners(),t.next=5;break;case 4:t.prev=4,r=t.catch(2),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(e.tryJsonStringify(r)));case 5:this.closePeerConnection();case 6:case"end":return t.stop()}},t,this,[[2,4]])})),function(){return i.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.logger.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!==J.New&&(t.logger.info("connectionId:".concat(t.id,": emit reoffer")),t.emit("reoffer"))},1e3)):"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.serviceManager.iceConfig,r=t.username,i=t.password,n=t.port,o=t.iceServerList,a={bundlePolicy:"max-bundle",iceTransportPolicy:"all",sdpSemantics:"unified-plan"};if(o.length){var s,c=[],u=fn(o);try{for(u.s();!(s=u.n()).done;){var d=s.value;c.push("turn:".concat(d,":").concat(n,"?transport=udp"),"turn:".concat(d,":").concat(n,"?transport=tcp"))}}catch(e){u.e(e)}finally{u.f()}e.Environment.isFirefox()&&c.splice(4,2),a.iceServers=[{urls:c,username:r,credential:i}]}return this.logger.info("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var t=this;this.pc?this.logger.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.processingExchangeSdp||(t.logger.info("connectionId:".concat(t.id,": emit reoffer")),t.emit("reoffer"))},be.connectPcTimeoutMs))}},{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.onicecandidate=function(t){e.onIceCandidate(t)},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new pn(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:"reoffer",value:function(){return this.state===J.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=J.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){be.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.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 i}();function gn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(gn=function(){return!!e})()}var bn=function(){function t(r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,gn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"_micAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_screenAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"mixedAudioTrackResult",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(i,"publication",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"serviceManager",{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,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:"audio"}),Object.defineProperty(i,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"selfMicMutedProperty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"isPublished",{enumerable:!0,configurable:!0,writable:!0,value:function(){return!!i.publication}}),Object.defineProperty(i,"setPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(e){i.logger.info("setPublication",null==e?void 0:e.id),i.publication=e}}),Object.defineProperty(i,"getPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(){return i.publication}}),Object.defineProperty(i,"micTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:i._audioTrackInnerEventHandler.bind(i,exports.AudioSourceInfo.MIC)}),Object.defineProperty(i,"screenAudioTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:i._audioTrackInnerEventHandler.bind(i,exports.AudioSourceInfo.SCREENCAST)}),Object.defineProperty(i,"updateMixedAudioTrackToPub",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,n,o,a,s;i.logger.info("updateMixTrack",null===(e=i._micAudioTrack)||void 0===e?void 0:e.getTrackId(),null===(t=i._screenAudioTrack)||void 0===t?void 0:t.getTrackId()),null===(r=i.mixedAudioTrackResult)||void 0===r||null===(r=r.mixedTrack)||void 0===r||r.stop(),i.mixedAudioTrackResult=i.mixAudioTracks(null===(n=i._micAudioTrack)||void 0===n?void 0:n.getMediaStreamTrack(),null===(o=i._screenAudioTrack)||void 0===o?void 0:o.getMediaStreamTrack()),null===(a=i.publication)||void 0===a||a.replaceTrack(null===(s=i.mixedAudioTrackResult)||void 0===s?void 0:s.mixedTrack)}}),Object.defineProperty(i,"clear",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;i.logger.info("clear"),null===(e=i.mixedAudioTrackResult)||void 0===e||null===(e=e.mixedTrack)||void 0===e||e.stop(),i._micAudioTrack=null,i._screenAudioTrack=null,i.publication=void 0}}),Object.defineProperty(i,"getMediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;return(null===(e=i.mixedAudioTrackResult)||void 0===e?void 0:e.mixedTrack)||null}}),i.logger=r.reporter.getLoggerWithPrefix("[rtc-mixedAudioTrack]"),i.serviceManager=r,i._trackId="audio_".concat(e.createUuid(6)),i}return f(t,e.EventEmitter),u(t,[{key:"getTrackId",value:function(){return this._trackId}},{key:"getScreenAudioTrack",value:function(){return this._screenAudioTrack}},{key:"setScreenAudioTrack",value:function(e){var t,r,i;(this.logger.info("setScreenAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._screenAudioTrack)||void 0===t||t.off(de,this.screenAudioTrackEventHandler),this._screenAudioTrack=e,null===(r=this._screenAudioTrack)||void 0===r||r.on(de,this.screenAudioTrackEventHandler),e)?e.muted||(this.notifyScreenAudioEnabled(!0),null===(i=this.publication)||void 0===i||i.unmute()):this.notifyScreenAudioEnabled(!1)}},{key:"getMicAudioTrack",value:function(){return this._micAudioTrack}},{key:"setMicAudioTrack",value:function(e){var t,r;this.logger.info("setMicAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._micAudioTrack)||void 0===t||t.off(de,this.micTrackEventHandler),this._micAudioTrack=e,null===(r=this._micAudioTrack)||void 0===r||r.on(de,this.micTrackEventHandler),this._micAudioTrack&&(this._micAudioTrack.muted&&!this.selfMicMutedProperty?(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0)):!this._micAudioTrack.muted&&this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)))}},{key:"_audioTrackInnerEventHandler",value:function(e,t){if("localMixedAudioReplaceTrack"===t)this.updateMixedAudioTrackToPub();else if("stop"===t){var r,i,n;if(e===exports.AudioSourceInfo.MIC?this.setMicAudioTrack(null):this.setScreenAudioTrack(null),this.updateMixedAudioTrackToPub(),null===(r=this.mixedAudioTrackResult)||void 0===r||!r.mixedTrack)if(this.logger.warn("mixedAudioTrackResult is null, stop pub audio, pubid=",null===(i=this.publication)||void 0===i?void 0:i.id),this.publication)null===(n=this.publication)||void 0===n||n.stop(),this.publication=null}else if("mute"===t){e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!1):this.selfMicMutedProperty||(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0));var o=e===exports.AudioSourceInfo.MIC?this._screenAudioTrack:this._micAudioTrack;o&&!o.muted&&o.enabled||this.publication.mute()}else"unmute"===t?(e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!0):this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)),this.publication.unmute()):this.logger.info("unhandled action",t)}},{key:"setSelfMicMutedProperty",value:function(e){this.selfMicMutedProperty=e}},{key:"notifyMicDeviceMuted",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({mute_audio_record:e?1:0}))}},{key:"notifyScreenAudioEnabled",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({enable_sys_audio:e?1:0}))}},{key:"mixAudioTracks",value:function(e,t){var r;if(!e&&!t)return null;var i=it();this.audioContext=i;var n=i.createMediaStreamDestination();return e&&i.createMediaStreamSource(new MediaStream([e])).connect(n),t&&i.createMediaStreamSource(new MediaStream([t])).connect(n),{mixedTrack:null===(r=n.stream.getAudioTracks())||void 0===r?void 0:r[0],isOriginTrack:!1}}}])}();function yn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function kn(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){X(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 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 Pn(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)?Pn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Pn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Tn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Tn=function(){return!!e})()}var wn=2e3,En=function(){function t(e,r){var i,a,s,c,u,p,f;return o(this,t),a=this,s=l(s=t),i=d(a,Tn()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(i,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(i,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"mixedLocalAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"republishPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"resubscribePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"handleRepublish",{enumerable:!0,configurable:!0,writable:!0,value:(u=n($.mark(function e(){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:i.republishPromise=i._handleRepub(),i.republishPromise.finally(function(){i.republishPromise=null});case 1:case"end":return e.stop()}},e)})),function(){return u.apply(this,arguments)})}),Object.defineProperty(i,"handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(p=n($.mark(function e(){var t,r=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=r.length>0&&void 0!==r[0]&&r[0],i.resubscribePromise=i._handleResubscribe(t),i.resubscribePromise.finally(function(){i.resubscribePromise=null});case 1:case"end":return e.stop()}},e)})),function(){return p.apply(this,arguments)})}),Object.defineProperty(i,"_handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(f=n($.mark(function e(){var t,r,n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w,E,I,M,O,R,A,x,C,_,D,j,L,N,V,F,U,G,B=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=B.length>0&&void 0!==B[0]&&B[0],i.logger.info("handle resub fromServer=",r),n=r?"server":"client",o=[],a=Sn(i.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof bi&&c.state===Y.Processing&&(u=null,c.stream.media.video?(d=i.serviceManager.rtcUserManager.users.get(c.uid),u="camera"===c.stream.media.video.source?null==d?void 0:d.videoTrack:null==d?void 0:d.auxiliaryTrack):c.stream.media.audio?u=i.serviceManager.remoteAudioTrack:i.logger.error("unknown media type for resub",c.stream),o.push({stream:c.stream,uid:c.uid,targetMediaType:c.targetMediaType,resolutionInfo:c.userConfigResolution,session:c,track:u}))}catch(e){a.e(e)}finally{a.f()}if(l=o.map(function(e){return e.uid}).join(),o.length){i.logger.info("resubscribe start ".concat(l)),i.client.emit("media-reconnect-start",i.client.userId),p=Sn(o);try{for(p.s();!(f=p.n()).done;)h=f.value,i.logger.info("emitted sub-media-reconnect-started",null===(v=h.track)||void 0===v?void 0:v.getTrackId()),i.client.emit("sub-media-reconnect-started",null===(m=h.track)||void 0===m?void 0:m.getTrackId())}catch(e){p.e(e)}finally{p.f()}}g=null===(t=i.downlink)||void 0===t?void 0:t.id,b=Date.now(),y=b+45e3,k=!1,S=i.serviceManager.rtcUserManager.currentSelfPid,P=0;case 1:if(!(P<23&&Date.now()<=y)){e.next=10;break}if(!((T=Date.now())<b+P*wn)){e.next=2;break}return e.next=2,Be(b+P*wn-T);case 2:if(i.logger.debug("resub round=".concat(P,", channelconnect=").concat(i.serviceManager.internalChannel.connectionState)),"connected"===i.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",9);case 3:return e.prev=3,i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferStart")),e.next=4,null===(w=i.downlink)||void 0===w?void 0:w.clearPcForReoffer();case 4:if(i.downlink=null,!o.length){e.next=7;break}return e.next=5,i.batchSubscribe(o);case 5:if(E=e.sent,i.serviceManager.rtcUserManager.currentSelfPid===S){e.next=6;break}return i.logger.error("abort resubscribe for selfCurrentPid changed from to",S,i.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 6:I=Sn(E);try{for(I.s();!(M=I.n()).done;)O=M.value,R=O.subscription,A=O.error,R&&!A&&i.handleResubSuccess(R)}catch(e){I.e(e)}finally{I.f()}i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferSuccess")),i.logger.debug("resub round=".concat(P," resubscribe ").concat(l," success")),i.client.emit("media-reconnect-end",l),x=Sn(o);try{for(x.s();!(C=x.n()).done;)j=C.value,i.logger.info("emitted sub-media-reconnect-succeeded",null===(_=j.track)||void 0===_?void 0:_.getTrackId()),i.client.emit("sub-media-reconnect-succeeded",null===(D=j.track)||void 0===D?void 0:D.getTrackId())}catch(e){x.e(e)}finally{x.f()}case 7:return k=!0,e.abrupt("continue",10);case 8:if(e.prev=8,G=e.catch(3),i.logger.debug("resub round=".concat(P," resubscribe failed for"),G),i.serviceManager.rtcUserManager.currentSelfPid===S){e.next=9;break}return i.logger.error("abort resubscribe for selfCurrentPid changed from to",S,i.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 9:P++,e.next=1;break;case 10:if(!k){if(i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferFailed")),i.downlink.clearPcForReoffer(),i.downlink=null,o.length){i.client.emit("media-reconnect-end",l),L=Sn(o);try{for(L.s();!(N=L.n()).done;)U=N.value,i.logger.info("emitted sub-media-reconnect-failed",null===(V=U.track)||void 0===V?void 0:V.getTrackId()),i.client.emit("sub-media-reconnect-failed",null===(F=U.track)||void 0===F?void 0:F.getTrackId())}catch(e){L.e(e)}finally{L.f()}}o.forEach(function(e){if(i.removeSession(e.session.id),"audio"===e.session.targetMediaType){var t,r;null===(t=i.serviceManager.remoteAudioTrack)||void 0===t||t.stopPlay(),null===(r=i.serviceManager.remoteAudioTrack)||void 0===r||null===(r=r.getMediaStreamTrack())||void 0===r||r.stop(),i.serviceManager.remoteAudioTrack=null}else{var n,o,a,s,c=i.serviceManager.rtcUserManager.users.get(e.session.uid);"camera"===e.session.stream.media.video.source?(null===(n=c.videoTrack)||void 0===n||n.stopPlay(),null===(o=c.videoTrack)||void 0===o||null===(o=o.getMediaStreamTrack())||void 0===o||o.stop(),c.videoTrack=null):(null===(a=c.auxiliaryTrack)||void 0===a||a.stopPlay(),null===(s=c.auxiliaryTrack)||void 0===s||null===(s=s.getMediaStreamTrack())||void 0===s||s.stop(),c.auxiliaryTrack=null)}})}case 11:case"end":return e.stop()}},e,null,[[3,8]])})),function(){return f.apply(this,arguments)})}),i.serviceManager=r,i.client=e,i.reporter=r.reporter,i.logger=i.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),i.streamIdToSessionId=new Map,i.sessions=new Map,i.mixedLocalAudioTrack=new bn(r),i.handleMediaMessage=i.handleMediaMessage.bind(i),i.handleServerFailover=i.handleServerFailover.bind(i),i}return f(t,e.EventEmitter),u(t,[{key:"getOrCreatePeerConnection",value:(k=n($.mark(function e(t){var r=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=3;break}if(this.uplink){e.next=2;break}return this.uplink=new hn({direction:t,sessionManager:this}),e.next=1,this.uplink.startSinglePC();case 1:this.uplink.on("reoffer",this.handleRepublish),this.uplink.on("ended",function(){r.uplink=null});case 2:return e.abrupt("return",this.uplink);case 3:if(this.downlink){e.next=5;break}return this.downlink=new hn({direction:t,sessionManager:this}),e.next=4,this.downlink.startSinglePC();case 4:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",function(){r.downlink=null});case 5:return e.abrupt("return",this.downlink);case 6:case"end":return e.stop()}},e,this)})),function(e){return k.apply(this,arguments)})},{key:"_handleRepub",value:(y=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("handle repub"),r=te(this.client.localTracks),this.mixedLocalAudioTrack.clear(),r.length){this.client.emit("media-reconnect-start",this.client.userId),i=Sn(r);try{for(i.s();!(n=i.n()).done;)o=n.value,this.logger.info("emitted pub-media-reconnect-started",o.getTrackId()),this.client.emit("pub-media-reconnect-started",o.getTrackId())}catch(e){i.e(e)}finally{i.f()}}a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+45e3,u=!1,d=0,d=0;case 1:if(!(d<23&&Date.now()<=c||"disconnected"!==this.serviceManager.internalChannel.connectionState)){e.next=9;break}if(!((l=Date.now())<s+d*wn)){e.next=2;break}return e.next=2,Be(s+d*wn-l);case 2:if(this.logger.debug("repub round=".concat(d,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",8);case 3:return e.prev=3,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(d,", clearPcForReoffer start ").concat(r.map(function(e){return e.trackMediaType}).join())),e.next=4,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 4:if(this.uplink=null,this.logger.info("repub round=".concat(d,", batchPublish start ").concat(r.map(function(e){return e.trackMediaType}).join())),!r.length){e.next=6;break}return e.next=5,this.batchPublish(r);case 5:this.logger.info("".concat(this.client.userId," batchPublish finished for repub")),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),f=Sn(r);try{for(f.s();!(v=f.n()).done;)m=v.value,this.logger.info("emitted pub-media-reconnect-succeeded",m.getTrackId()),this.client.emit("pub-media-reconnect-succeeded",m.getTrackId())}catch(e){f.e(e)}finally{f.f()}case 6:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),u=!0,e.abrupt("continue",9);case 7:e.prev=7,P=e.catch(3),this.logger.error("".concat(this.client.userId," republish failed for"),P);case 8:d++,e.next=1;break;case 9:if(this.logger.info("break from repub loop roundNum, connectionstate",d,this.serviceManager.internalChannel.connectionState),u){e.next=14;break}if(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),"connected"!==this.serviceManager.internalChannel.connectionState){e.next=13;break}return e.prev=10,this.logger.info("unpub all tracks after repub failed"),e.next=11,this.serviceManager.unpublish(r);case 11:e.next=13;break;case 12:e.prev=12,T=e.catch(10),this.logger.info("err for unpub after repub failed",T);case 13:if(null===(h=this.uplink)||void 0===h||h.clearPcForReoffer(),this.uplink=null,r.length){this.client.emit("media-reconnect-end",this.client.userId),g=Sn(r);try{for(g.s();!(b=g.n()).done;)y=b.value,(k=this.streamIdToSessionId.get(y.getTrackId()))&&(this.logger.info("clear old publication for repub failed",k),null===(S=this.sessions.get(k))||void 0===S||S.clear(),this.sessions.delete(k)),this.logger.info("emitted pub-media-reconnect-failed",y.getTrackId()),this.client.emit("pub-media-reconnect-failed",y.getTrackId())}catch(e){g.e(e)}finally{g.f()}}case 14:case"end":return e.stop()}},e,this,[[3,7],[10,12]])})),function(){return y.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(b=n($.mark(function e(t){var r,i,n,o,a,s,c,u,d,l,p,f;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=1;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 1:r=[],i=Sn(t);try{for(i.s();!(n=i.n()).done;)(o=n.value)instanceof bi&&o.state===Y.Processing&&(r.push({stream:o.stream,uid:o.uid,targetMediaType:o.targetMediaType,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){i.e(e)}finally{i.f()}return a=r.map(function(e){return e.uid}).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=2,e.next=3,this.batchUnscribe(r);case 3:return e.next=4,this.batchSubscribe(r);case 4:s=e.sent,c=Sn(s);try{for(c.s();!(u=c.n()).done;)d=u.value,l=d.subscription,p=d.error,l&&!p&&this.handleResubSuccess(l)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=6;break;case 5:e.prev=5,f=e.catch(2),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),f),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 6:case"end":return e.stop()}},e,this,[[2,5]])})),function(e){return b.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return e?this.sessions.get(this.streamIdToSessionId.get(e)):null}},{key:"handleResubSuccess",value:function(e){var t,r=e.uid,i=e.mediaStream,n=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=i.getAudioTracks()[0],a=i.getVideoTracks()[0],s=o?"audio":n?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(be.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,i);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var d=this.serviceManager.rtcUserManager.remoteUsers.find(function(e){return e.userId===r});a&&null!=d&&d.auxiliaryTrack&&n?d.auxiliaryTrack.replaceTrack(a):a&&null!=d&&d.videoTrack&&!n&&d.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,i=e.actions,n=Sn(void 0===i?[]:i);try{var o=function(){var e,i,n=r.value,o=n.actionName,a=n.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,d=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then(function(){t.logger.info("".concat(u," republish ").concat(d.map(function(e){return e.trackMediaType}).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)}).catch(function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")})}else a===(null===(i=t.downlink)||void 0===i?void 0:i.id)&&t.handleResubscribe(!0)};for(n.s();!(r=n.n()).done;)o()}catch(e){n.e(e)}finally{n.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?B.BAD:e>30||t>450?B.POOR:e>20||t>300?B.NORMAL:e>10||t>200?B.GOOD:e>=0||t>=0?B.GREAT:B.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(g=n($.mark(function e(){var t,r=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=te(this.sessions.values())).length){e.next=1;break}return this.emit("network-quality",B.UNKNOWN,B.UNKNOWN),e.abrupt("return");case 1: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=2;break}return this.emit("network-quality",B.DISCONNECTED,B.DISCONNECTED),e.abrupt("return");case 2:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then(function(e){var t=kt(e,4),i=t[0],n=t[1],o=t[2],a=t[3],s=0,c=0,u=0,d=0,l=0,p=0;if(i){var f=i.camera,v=i.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,l=Math.max(l,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,l=Math.max(l,v.rtt||0))}for(var m in n&&(c+=n.sendPacketsLost||0,s+=n.sendPackets||0,l=Math.max(l,n.rtt||0)),o&&(u+=o.receivePacketsLost||0,d+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var h=a[m],g=h.camera,b=h.auxiliary;g&&(u+=g.receivePacketsLost,d+=g.receivePackets,p=Math.max(p,g.rtt||0)),b&&(u+=b.receivePacketsLost,d+=b.receivePackets,p=Math.max(p,b.rtt||0))}var y=-1,k=-1,S={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:d};if(s){var P,T,w=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(w<0&&(w=c),S.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==w){var E;S.totalUplinkPacketsSentForLost=s;var I=s-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsSentForLost)||0);I<0&&(I=s),y=w/I}}if(d){var M,O,R,A,x=u-((null===(M=r.lastChannelNetworkQuality)||void 0===M?void 0:M.totalDownlinkPacketsLost)||0);x<0&&(x=u),S.totalDownlinkPacketsRecvForLost=(null===(O=r.lastChannelNetworkQuality)||void 0===O?void 0:O.totalDownlinkPacketsRecvForLost)||0,null===(R=r.lastChannelNetworkQuality)||void 0===R||R.totalDownlinkPacketsRecvForLost,x&&(u!==((null===(A=r.lastChannelNetworkQuality)||void 0===A?void 0:A.totalDownlinkPacketsLost)||0)&&(S.totalDownlinkPacketsRecvForLost=d),k=x/d)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*y,100),l),r.getNetworkQuality(Math.min(100*k,100),p)),r.lastChannelNetworkQuality=S});case 3:case"end":return e.stop()}},e,this)})),function(){return g.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),this.mixedLocalAudioTrack.getPublication()===r&&this.mixedLocalAudioTrack.clear())}},{key:"batchPublish",value:(h=n($.mark(function e(t,r){var i,n,o,a,s,c,u,d,l,p=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=Date.now(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return n=e.sent,o=te(this.sessions.values()).filter(function(e){return e instanceof an}),e.next=2,cn({uid:this.client.userId,tracks:t,connection:n,labels:r,existedPublications:o,mixedLocalAudioTrack:this.mixedLocalAudioTrack});case 2:a=e.sent,s=te(a.videoPubResultArr),a.audioPubResult&&s.push(a.audioPubResult),c=Sn(s),e.prev=3,d=$.mark(function e(){var t,r,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=u.value,r=t.error,n=t.publication,o=t.track,r?p.reporter.trace.publish(!1,o,"",Date.now()-i):((a=p.streamIdToSessionId.get(o.getTrackId()))&&(p.logger.info("clear old publication before set new one",a),null===(s=p.sessions.get(a))||void 0===s||s.clear(),p.sessions.delete(a)),p.addSession(o.getTrackId(),n),p.reporter.trace.publish(!0,o,n.id,Date.now()-i),p.reporter.trace.publish(!1,o,n.id,Date.now()-i),n.on("ended",function(){p.removeSession(n.id)}));case 1:case"end":return e.stop()}},e)}),c.s();case 4:if((u=c.n()).done){e.next=6;break}return e.delegateYield(d(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,l=e.catch(3),c.e(l);case 8:return e.prev=8,c.f(),e.finish(8);case 9:case"end":return e.stop()}},e,this,[[3,7,8,9]])})),function(e,t){return h.apply(this,arguments)})},{key:"batchUnPublish",value:(m=n($.mark(function e(t){var r,i=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return this.logger.info("batchUnPublish sessions is empty"),e.abrupt("return",Promise.resolve());case 1:return e.next=2,this.getOrCreatePeerConnection("uplink");case 2:return r=e.sent,e.abrupt("return",un(t,{connection:r}).then(function(){var e,r=Sn(t);try{for(r.s();!(e=r.n()).done;){var n,o,a=e.value;i.streamIdToSessionId.delete(null===(n=a.tracks)||void 0===n||null===(n=n[0])||void 0===n||null===(o=n.getTrackId)||void 0===o?void 0:o.call(n)),i.removeSession(a.id)}}catch(e){r.e(e)}finally{r.f()}}));case 3:case"end":return e.stop()}},e,this)})),function(e){return m.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t,r=this,i=Date.now(),o=0,a=function(){var e=n($.mark(function e(t){var i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.getOrCreatePeerConnection("downlink");case 1:return i=e.sent,e.abrupt("return",Pi(t,i).then(function(){var e=n($.mark(function e(i){var n,s,c,u;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(n=new Map,s=[],c=0;c<i.length;c++)"RoomBusy"===(null===(u=i[c].error)||void 0===u?void 0:u.message)&&(s.push(t[c]),n.set(s.length-1,c));if(!(s.length&&o<=3)){e.next=3;break}return o++,e.next=1,He(1);case 1:if("connected"!==r.client.connectionState){e.next=3;break}return e.next=2,a(s);case 2:e.sent.forEach(function(e,t){var r=n.get(t);i[r]=e});case 3:return e.abrupt("return",i);case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}()));case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),s=Sn(e);try{for(s.s();!(t=s.n()).done;){var c=t.value,u=c.stream,d=c.uid,l=c.resolutionInfo;(null==u?void 0:u.id)&&this.reporter.trace.subscribe({subPhase:"init",capabilities:null==u?void 0:u.media,remoteStreamId:null==u?void 0:u.id,remoteUserId:d,elapse:0,sessionId:"",resolutionInfo:l})}}catch(e){s.e(e)}finally{s.f()}return a(e).then(function(e){var t,n=Sn(e);try{var o=function(){var e=t.value,n=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;if(o){r.reporter.trace.subscribe({subPhase:"success",capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-i,sessionId:a,resolutionInfo:u});var d,l=r.streamIdToSessionId.get(s.id);if(l)r.logger.info("clear old subscription before set new one",l),null===(d=r.sessions.get(l))||void 0===d||d.clear(),r.sessions.delete(l);r.addSession(s.id,o),o.on("ended",function(){r.logger.info("remove subscription for ended",a),r.removeSession(a)})}n&&(r.logger.error("batchSubscribe error",s,n),(null==s?void 0:s.id)&&r.reporter.trace.subscribe({subPhase:"failed",capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-i,sessionId:"",resolutionInfo:u}))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}return r.logger.info("batchSubscribe result",null==e?void 0:e.map(function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}})),e})}},{key:"batchUnscribe",value:(v=n($.mark(function e(t){var r,i,n,o,a=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),i=[],n={},t.forEach(function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(n[null==s?void 0:s.id]=t,i.push(c))}),e.next=1,this.getOrCreatePeerConnection("downlink");case 1:return o=e.sent,e.abrupt("return",Ti(i,o).then(function(){for(var e=0,t=i;e<t.length;e++){var n=t[e];a.removeSession(n.id)}return r}));case 2:case"end":return e.stop()}},e,this)})),function(e){return v.apply(this,arguments)})},{key:"clear",value:function(){var t,r,i=this;this.sessions.forEach(function(e){i.removeSession(e.id)}),this.mixedLocalAudioTrack.clear(),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.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(p=n($.mark(function e(){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return this.uplink=e.sent,e.next=2,this.getOrCreatePeerConnection("downlink");case 2:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 3: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",B.DISCONNECTED,B.DISCONNECTED):"connected"!==t.client.connectionState?t.emit("network-quality",B.BAD,B.BAD):"connected"===t.client.connectionState?t.checkChannelNetworkQuality():t.emit("network-quality",B.UNKNOWN,B.UNKNOWN)},2e3,"interval")}},{key:"getLocalAudioStats",value:(c=n($.mark(function e(){var t,r,i,n=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=n.length>0&&void 0!==n[0]?n[0]:"network",i=te(this.sessions.values()).filter(function(e){var t,r;return e instanceof an&&"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=1,Promise.all(i.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=i[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return c.apply(this,arguments)})},{key:"getLocalVideoStats",value:(s=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m,h=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=h.length>0&&void 0!==h[0]?h[0]:"network",n=te(this.sessions.values()).filter(function(e){var t;return e instanceof an&&"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=1,Promise.all(n.map(function(e){return e.getMetrics(i)}));case 1: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(";"))||[],i=r.findIndex(function(e){return e.includes("profile-level-id")});return r[i].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:te(new Set(o(a))),downlinkProfile:te(new Set(o(s)))},u=Sn(n),e.prev=2,u.s();case 3:if((d=u.n()).done){e.next=6;break}if(l=d.value,p=l.videoStatsMap.get(i)){e.next=4;break}return e.abrupt("continue",5);case 4:f=l.tracks,v=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,m=e.catch(2),u.e(m);case 8:return e.prev=8,u.f(),e.finish(8);case 9:return e.abrupt("return",c);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return s.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(a=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=v.length>0&&void 0!==v[0]?v[0]:"network",r=te(this.sessions.values()).filter(function(e){var t;return e instanceof bi&&"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=1,Promise.all(r.map(function(e){return e.getMetrics(t)}));case 1:i={},n=Sn(r),e.prev=2,n.s();case 3:if((o=n.n()).done){e.next=6;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,d=s.stream,l=c.get(t)){e.next=4;break}return e.abrupt("continue",5);case 4:p=(null===(a=d.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",i[u]=kn(kn({},i[u]||{}),{},X({},p,l));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(2),n.e(f);case 8:return e.prev=8,n.f(),e.finish(8);case 9:return e.abrupt("return",i);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return a.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(i=n($.mark(function e(){var t,r,i,n=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=n.length>0&&void 0!==n[0]?n[0]:"network",i=te(this.sessions.values()).filter(function(e){var t;return e instanceof bi&&"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=1,Promise.all(i.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=i[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return i.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=n($.mark(function e(t){var r,i,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=1;break}return e.abrupt("return");case 1:i=te(this.sessions.values()).filter(function(e){return e instanceof an&&e.state===Y.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA}),n=Sn(i),e.prev=2,a=$.mark(function e(){var t,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(i=r.filter(function(e){return e.mid==t.transceiver.mid})).length&&t.applyOptions(i);case 1:case"end":return e.stop()}},e)}),n.s();case 3:if((o=n.n()).done){e.next=5;break}return e.delegateYield(a(),"t0",4);case 4:e.next=3;break;case 5:e.next=7;break;case 6:e.prev=6,s=e.catch(2),n.e(s);case 7:return e.prev=7,n.f(),e.finish(7);case 8:case"end":return e.stop()}},e,this,[[2,6,7,8]])})),function(e){return r.apply(this,arguments)})}]);var r,i,a,s,c,p,v,m,h,g,b,y,k}();function In(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return 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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}function On(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(On=function(){return!!e})()}var Rn={name:"name"},An=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,On()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"serviceManager",{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}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),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.serviceManager.rtcUserManager.currentSelfPid,t=new Set;return this.groups.forEach(function(r){var i=r.participants,n=r.id;i.some(function(t){return t.pid===e})&&t.add(n)}),t}},{key:"parseGroup",value:function(e){var t,r=this,i=e.id,n=e.properties,o=e.participants;return{id:i,name:(null==n||null===(t=n.find(function(e){return"name"===e.key}))||void 0===t?void 0:t.value)||"",joined:o.some(function(e){return e.pid===r.serviceManager.rtcUserManager.currentSelfPid}),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.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(t){var r=t.publishAudioToGroup,i=void 0===r||r,n=t.groupId,o=t.userData;if(this.joinedIds.has(n))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:o,autoJoinGroupAudio:!!i,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(t){var r=t.groupId,i=t.publishAudioToChannel,n=void 0===i||i;if(!this.joinedIds.has(r))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:r,reasonCode:dr.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(t){if(!this.groupIds.has(t))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:t})}},{key:"addUser",value:function(e,t){var r,i=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;i&&!i.find(function(t){return t.pid===e.pid})&&i.push(e)}},{key:"removeUser",value:function(e,t){var r,i=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(i){var n=i.findIndex(function(t){return t.pid===e.pid});n>-1&&i.splice(n,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,i=e.type,n=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||i!==dr.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=n.updateAction,a=n.id;o===dr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===dr.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.logger.info("on group event:",e);var i,n=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(n);if(s!==dr.OptType.OPT_TYPE_ADD||u){if(s===dr.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(n),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===dr.OptType.OPT_TYPE_UPDATE){var d=c.updateAction,l=c.participants;if(u&&(u.ver+1===o||r)){if(d===dr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map(function(e){return e.pid}),v=In(l);try{for(v.s();!(p=v.n()).done;){var m=p.value;f.includes(m.pid)||(u.participants.push(m),this.emit("group","user-join",n,{userId:m.uid,userData:m.userData}))}}catch(e){v.e(e)}finally{v.f()}}else if(d===dr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var h=l.map(function(e){return e.pid}),g=te(u.participants);u.participants=u.participants.filter(function(e){return!h.includes(e.pid)}),g.forEach(function(e){h.includes(e.pid)&&t.emit("group","user-leave",n,{userId:e.uid,userData:e.userData})})}else if(d===dr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(n," audioStream lost"));else if(d===dr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(n," audioStream recover"));else if(d===dr.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",n,{key:"set-".concat(Rn[e.key]),value:e.value})});else if(d===dr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var b,y=c.properties.map(function(e){return e.key});u.properties=null===(b=u.properties)||void 0===b?void 0:b.filter(function(e){var t=e.key;return!y.includes(t)}),c.properties.forEach(function(e){t.emit("group","info-updated",n,{key:"remove-".concat(Rn[e.key])})})}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(i=a.audioInfo)||void 0===i||null===(i=i.audio)||void 0===i||null===(i=i.media)||void 0===i||delete i.video,null==a.ver&&(a.ver=o),this.groups.set(n,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:dr.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then(function(i){var n=i.fullSync.groupData.groupInfos,o=(void 0===n?[]:n)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],d=new Map(((null==r?void 0:r.properties)||[]).map(function(e){return[e.key,e.value]})),l=u.map(function(e){return e.pid}),p=a.map(function(e){return e.pid}),f=c.filter(function(e){return e.value!==d[e.key]}),v=c.filter(function(e){return!d.has(e.key)}),m=a.filter(function(e){return!l.includes(e.pid)}),h=u.filter(function(e){return!p.includes(e.pid)});m.length&&t.handleGroupEvents({id:e,type:dr.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:m}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:h}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:dr.OptType.OPT_TYPE_REMOVE})})}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:dr.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.serviceManager.rtcSignaling.syncData({type:dr.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then(function(t){var r=t.fullSync,i=r.ver,n=r.groupListData.groupIds,o=void 0===n?[]:n,a=o.filter(function(t){return!e.groupIds.has(t)}),s=te(e.groupIds).filter(function(e){return!o.includes(e)});a.length&&a.forEach(function(t){e.handleGroupListEvents({ver:i,updateOpt:{updateAction:dr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)}),s.length&&s.forEach(function(t){e.handleGroupListEvents({ver:i,updateOpt:{updateAction:dr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)})})}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,i=e.groupVer,n=void 0===i?[]:i;this.listVer<r&&(this.syncGroupList(),this.listVer=r),n.forEach(function(e){var r=e.id,i=e.ver,n=t.groups.get(r);(null==n?void 0:n.ver)<i&&(t.syncGroup(r),n.ver=i)})}}])}();function xn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(xn=function(){return!!e})()}var Cn=function(){function t(e,r){var i,n,a,s;o(this,t),n=this,a=l(a=t),i=d(n,xn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"toJSON",{enumerable:!0,configurable:!0,writable:!0,value:function(){return{userId:i.userId,userName:i.userName,hasAuxiliary:i.hasAuxiliary,hasVideo:i.hasVideo,hasAudio:i.hasAudio,joinedTime:i.joinedTime,properties:i.properties,audioMuted:i.audioMuted,auxiliaryMuted:i.auxiliaryMuted,videoMuted:i.videoMuted}}});var c=e.user;return i.userId=c,i.videoTrack=null,i.audioTrack=null,i.auxiliaryTrack=null,i.serviceManager=r,i.joinedTime=Date.now(),i.update(e),i}return f(t,e.EventEmitter),u(t,[{key:"relatedStreams",get:function(){var e=this;return te(this.serviceManager.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,i=e.media;return"active"!==(null==i||null===(t=i.audio)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC})}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,i=e.media;return"active"!==(null==i||null===(t=i.video)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"videoMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,i=e.media;return"active"!==(null==i||null===(t=i.video)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.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 i=t.split("");i[K.UPLINK]=Fe(i[K.UPLINK]),i[K.DOWNLINK]=Fe(i[K.DOWNLINK]),t=i.join("")}t!==(null===(r=this.properties)||void 0===r?void 0:r[ue])&&(this.properties[ue]=t)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,i=e.ver,n=JSON.parse(r||"{}");this.id=t,this.userName=n.__nick,this.version=i;var o=this.properties||{};this.properties=n,this.updateNetworkOfUser(n[ue]),!n.hasOwnProperty("mute_audio_record")||void 0!==o.mute_audio_record&&n.mute_audio_record===o.mute_audio_record||this.serviceManager.client.emit("user-mic-audio-muted",this.userId,!!n.mute_audio_record),!n.hasOwnProperty("enable_sys_audio")||void 0!==o.enable_sys_audio&&n.enable_sys_audio===o.enable_sys_audio||this.serviceManager.client.emit("user-screencast-audio-mixed",this.userId,!!n.enable_sys_audio)}},{key:"updateSubbedVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,i=JSON.parse(e.stream.info.attributesJsonStr),n=Te(e.mediaStream,"video",this.userId,r);return t?this.auxiliaryTrack=n:this.videoTrack=n,i.mirror&&n.setSourceMirror(i.mirror),n}}])}();function _n(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 Dn(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)?Dn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Dn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(jn=function(){return!!e})()}var Ln=function(){function t(e,r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,jn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(i,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"currentSelfPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.users=new Map,i.serviceManager=e,i.reporter=e.reporter,i.logger=i.reporter.getLoggerWithPrefix("[rtc-userMgr]"),i.handleEvent=i.handleEvent.bind(i),i.streamManager=r,i}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){var t=this;return e.uniqBy(te(this.users.values()).sort(function(e,t){return e.joinedTime-t.joinedTime}),"userId").filter(function(e){return e.userId&&e.id!==t.currentSelfPid})}},{key:"init",value:function(e,t){var r,i=_n(e);try{for(i.s();!(r=i.n()).done;){var n=r.value,o=new Cn(n,this.serviceManager);this.users.set(n.user,o),t===n.user&&(this.currentUid=n.user)}}catch(e){i.e(e)}finally{i.f()}this.currentSelfPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentSelfPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var i=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var n=new Cn(t,this.serviceManager);this.users.set(t.user,n),this.emit("user","join",n)}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}));te(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 i.streamManager.remove(e,!0)});var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new Cn(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(X({},ue,e))})}},{key:"notifyParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:e})}}])}();function Nn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Vn(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)?Vn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Vn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Fn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Un(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Fn(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Fn(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Gn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Gn=function(){return!!e})()}var Bn=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,Gn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var s=e.rtcSignaling,c=e.reporter;return r.rtcSignaling=s,r.reporter=c,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),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.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,i=e.find(function(e){return"admin"===e.info.owner&&"mixed"===e.type});null==i||null===(r=i.media)||void 0===r||delete r.video,this.streams=new Map(e.map(function(e){return[e.id,e]})),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(t){var r,i=t.id,n=t.info.owner,o=t.media,a=o.video,s=o.audio;if(!this.streams.get(i)){var c=null===(r=t.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source,u=te(this.streams.values()).find(function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===c});u&&c&&this.remove(u.id),this.reporter.trace.streamsEvent(i,"add"),this.streams.set(t.id,t);var d=(null==a?void 0:a.source)===e.VideoSourceInfo.SCREENCAST;if((null==a?void 0:a.source)===e.VideoSourceInfo.CAMERA||d){this.emit("stream","add",{id:i,owner:n,mediaType:"video",auxiliary:d});var l="active"===a.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:i,auxiliary:d,updateStatus:"".concat(l,"-video")})}if((null==s?void 0:s.source)===exports.AudioSourceInfo.MIC||(null==s?void 0:s.source)===exports.AudioSourceInfo.MIXED){this.emit("stream","add",{id:i,owner:n,mediaType:"audio"});var p="active"===s.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:i,auxiliary:!1,updateStatus:"".concat(p,"-audio")})}}}},{key:"remove",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.streams.get(t);if(i&&(this.streams.delete(t),r)){this.reporter.trace.streamsEvent(t,"remove");var n=i.media,o=n.video,a=n.audio,s=i.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 te(this.streams.values()).find(function(t){var r,i;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(i=t.media.video)||void 0===i?void 0:i.trackId)===e})}},{key:"handleEvent",value:function(t,r){var i=this,n=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.logger.info("streamEvent",t);var d=this.totalVer;if(c===d+1||c==se||r)if("add"===o){if(!a||!a.media||!a.info)return;this.add(a)}else if("remove"===o)this.remove(n,!0);else if("update"===o){var l=s.field,p=s.streamStatus,f=s.activeStream,v=s.extraValue,m=s.streamVer,h=s.propertiesJsonStr,g=s.highestResolutionLevel,b=this.streams.get(n);if(b){m!==se&&(b.version=m);var y=b.media,k=y.audio,S=y.video,P=b.info.owner;if("audio.status"===l||"video.status"===l){var T,w;"audio.status"===l?(w="audio",k.status=p):"video.status"===l&&(w="video",S.status=p),this.reporter.trace.streamsEvent(n,"".concat(w," ").concat(p));var E="active"===p?"unmute":"mute",I=(null===(T=b.media)||void 0===T||null===(T=T.video)||void 0===T?void 0:T.source)===e.VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:P,id:n,updateStatus:"".concat(E,"-").concat(w),auxiliary:I})}else if("activeInput"===l){var M=[f].concat(v||[]).map(function(e){var t;return null===(t=i.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(M),l),this.emit("stream","volumeActive",{owners:M})}else if("properties"==l){var O,R=JSON.parse(h);b.info.attributesJsonStr=JSON.stringify(Un(Un({},JSON.parse(b.info.attributesJsonStr)),R));var A=(null===(O=b.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:n,properties:R,auxiliary:A})}else"highestResolutionLevel"===l&&(b.media.video.highestResolutionLevel=g,this.emit("stream","update",{owner:P,id:n,highestResolutionLevel:g}))}}r||c<=this.totalVer&&c!==se||(c===d+1&&(this.totalVer=c),c>d+1&&!r&&this.sync())}},{key:"sync",value:(r=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=1,this.rtcSignaling.getStreamsVer({});case 1:i=e.sent,n=i.streamVersions,o=i.totalVer,a=te(this.streams.keys()).filter(function(e){return!e.includes("vad")}),s=Nn(n),e.prev=2,s.s();case 3:if((c=s.n()).done){e.next=6;break}if(u=c.value,d=u.streamId,l=u.streamVer,!d.includes("vad")){e.next=4;break}return e.abrupt("continue",5);case 4:(p=this.streams.get(d))?p&&p.version!==l&&t.push(d):(r.push(d),t.push(d));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,v=e.catch(2),s.e(v);case 8:return e.prev=8,s.f(),e.finish(8);case 9:if(f=n.map(function(e){return e.streamId}),a.filter(function(e){return!f.includes(e)}).forEach(function(e){m.handleEvent({status:"remove",streamId:e,stream:m.streams.get(e),totalVer:o},!0)}),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=10;break}return e.abrupt("return");case 10:this.rtcSignaling.getStreams({streamIds:t}).then(function(e){var i,n=e.totalVer,o=e.streams,a=new Map,s=Nn(m.streams.values());try{for(s.s();!(i=s.n()).done;){var c=i.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,d=Nn(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;m.streams.has(l.id)?m.streams.set(l.id,l.stream):a.set(l.id,l.stream)}}catch(e){d.e(e)}finally{d.f()}for(var p=t.map(function(e){return a.get(e)}).filter(function(e){return!!e}).sort(function(e,t){return e.version-t.version}),f=0;f<p.length;f++){var v=p[f];r.includes(v.id)&&m.handleEvent({status:"add",streamId:v.id,stream:v,totalVer:n},!0)}a.clear(),m.totalVer=n});case 11:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}();function Hn(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 qn(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)?qn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 qn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Wn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Yn(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){X(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 Jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Jn=function(){return!!e})()}var Qn=function(){function t(i,n){var a,s,c,u;return o(this,t),s=this,c=l(c=t),a=d(s,Jn()?Reflect.construct(c,[],l(s).constructor):c.apply(s,u)),Object.defineProperty(a,"rtcSignaling",{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,"rtcUserManager",{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,"logger",{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,"processingSubParamsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(a,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"getSubTraceId",{enumerable:!0,configurable:!0,writable:!0,value:function(){return++t.subAcc}}),Object.defineProperty(a,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r,i=t.mediaType,n=t.uid,o=t.auxiliary,s=a.getStream(t),c=a.rtcUserManager.users.get(n),u=a.groups.some(function(e){return e.joined}),d="mcu"===n?a.remoteAudioTrack:o?null==c?void 0:c.auxiliaryTrack:null==c?void 0:c.videoTrack,l=[],p=te(a.processingSubParamsMap.values());a.logger.info("queueingSubParams",p,t),p.forEach(function(e){return l.push.apply(l,te(e))});var f=l.find(function(e){return e.uid===n&&e.mediaType===i&&!!e.auxiliary==!!o});return"mcu"===n&&"video"===i||n&&"mcu"!==n&&"audio"===i?r=new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support subscribe mcu audio"):"mcu"===n&&u?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"cannot subscribe mcu while in group"):d||f?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"duplicated subscription"):s||(a.logger.warn("".concat(n," videoTrack not existed")),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted)),{uid:n,user:c,error:r,stream:s,targetMediaType:i,resolutionInfo:"video"!==i||r?null:Ot(a.defaultVideoStreamType,ke(s))}}}),Object.defineProperty(a,"checkUnsubParam",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r,i=t.mediaType,n=t.uid,o=t.auxiliary,s=a.getStream(t),c=a.rtcUserManager.users.get(n),u="mcu"===n?a.remoteAudioTrack:o?null==c?void 0:c.auxiliaryTrack:null==c?void 0:c.videoTrack;"mcu"===n&&"video"===i||n&&"mcu"!==n&&"audio"===i?(a.logger.warn("only support unsubscribe mcu audio"),r=new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support unsubscribe mcu audio")):s&&u||(a.logger.warn("".concat(n," videoTrack not existing")),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted));var d=a.sessionManager.getSessionByStreamId(null==s?void 0:s.id);return d||(a.logger.warn("no sub session"),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted)),{uid:n,user:c,error:r,stream:s,session:d,subMediaType:i,resolutionInfo:"video"!==i||r?null:Ot(a.defaultVideoStreamType,ke(s))}}}),Object.defineProperty(a,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,n=t.streams,o=t.streamsVer,s=t.groupList,c=t.groupListVer;a.streamManager.init(n,o),a.groupManager.init(s,c),a.rtcUserManager.init(i,r),a.streamManager.on("stream",a.handleStreamEvent),a.rtcUserManager.on("user",a.handleUserEvent),a.groupManager.on("group",a.handleGroupEvent)}}),a.reporter=n,a.logger=a.reporter.getLoggerWithPrefix("[rtc-svcMgr]"),a.internalChannel=new r.DingRTCChannel({reporter:n,sdkVersion:ae}),a.rtcSignaling=new Kr(a.internalChannel),a.client=i,a.micMixedGroups=new Set,a.groupManager=new An(a),a.streamManager=new Bn(a),a.rtcUserManager=new Ln(a,a.streamManager),a.sessionManager=new En(i,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:"publishedLocalTracks",get:function(){var e=te(this.sessionManager.sessions.values()).filter(function(e){return e.state===Y.Processing&&e instanceof an}),t=new Set;return e.map(function(e){if(e.tracks){var r,i;if((null===(r=e.tracks)||void 0===r?void 0:r[0])instanceof bn){var n=e.tracks[0].getMicAudioTrack();n&&t.add(n);var o=e.tracks[0].getScreenAudioTrack();return void(o&&t.add(o))}(null===(i=e.tracks)||void 0===i?void 0:i[0])&&t.add(e.tracks[0])}}),te(t.values())}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map(function(t){return Yn(Yn({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})})}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,i=t.owner,n=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(i),p=this.rtcUserManager.users.get(null==l?void 0:l.user),f=i===this.rtcUserManager.currentSelfPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,n,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===n&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stopPlay(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stopPlay(),p.videoTrack=null)),this.client.emit("user-unpublished",p,n,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.rtcUserManager.currentUid,s,o);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 m=this.sessionManager.getSessionByStreamId(r);if(!m)return;m.stream.media.video.highestResolutionLevel=u;var h=m.userConfigResolution,g=m.resolutionInfo;if(u>=h.resolutionLevel&&h.resolutionLevel>g.resolutionLevel)m.applyOptions(h,!0);else if(u<h.resolutionLevel){var b=Ot(Rt(u),ke(m.stream));m.applyOptions(b,!0)}}}else if("volumeActive"===e){var y=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",y)}}},{key:"handleGroupEvent",value:function(e,t,r){var i=this;if("add"===e)this.client.emit("group-add",t);else if("remove"===e){var n;if(this.micMixedGroups.delete(t.id),this.logger.info("unsub group for group removed",t),r&&(null===(n=r.audio)||void 0===n?void 0:n.id)===this.subscribedAudioStream){var o=r.audio;this.sessionManager.batchUnscribe([{stream:o,session:this.sessionManager.getSessionByStreamId(o.id),targetMediaType:"audio"}]).then(function(){o.id===i.subscribedAudioStream&&(i.updateSubscribedAudioStream(!1,""),i.remoteAudioTrack.stopPlay(),i.remoteAudioTrack=null)})}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 a=r.key,s=r.value;this.client.emit("group-info-updated",t,a,s)}}},{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):this.logger.warn("unhandled inner rtc user emitted event",e,t)}},{key:"getStream",value:function(t){var r,i=t.groupId,n=t.uid,o=t.auxiliary;if(i){var a,s=this.groupManager.groups.get(i);return null==s||null===(a=s.audioInfo)||void 0===a?void 0:a.audio}var c="mcu"===n?te(this.streamManager.streams.values()):null===(r=this.rtcUserManager.users.get(n))||void 0===r?void 0:r.relatedStreams;return"mcu"===n?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:(m=n($.mark(function e(t){var r,i,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",be.gslb[0]),this.sessionManager.mixedLocalAudioTrack.setSelfMicMutedProperty(t.initMicMuted),e.next=1,this.rtcSignaling.join(t,be.gslb[0]);case 1:return i=e.sent,n=i.joinResponse,o=i.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(be.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=n.room.id,Di(n.room.ssrcMask,n.room.ssrcClientSequence),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:n.id}),o&&o.uis&&this.setIceConfig(o.uis),this.sessionManager.start(),this.handleJoinResponse(n),e.abrupt("return",n);case 2:case"end":return e.stop()}},e,this)})),function(e){return m.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.rtcUserManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stopPlay(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.rtcUserManager.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.rtcSignaling.leave()}},{key:"publish",value:(v=n($.mark(function e(t){var r,i,n,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,i=this.groupManager,n=this.groups,o=[],n.some(function(e){return e.joined})?o.push.apply(o,te(te(r).map(function(e){var t;return null===(t=i.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 1:case"end":return e.stop()}},e,this)})),function(e){return v.apply(this,arguments)})},{key:"unpublish",value:(p=n($.mark(function e(t){var r,i,n,o,a,s,c,u=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.republishPromise){e.next=5;break}return this.logger.info("wait for repub before unpublish"),e.prev=1,e.next=2,this.sessionManager.republishPromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unpublish after repub");case 5:return r=t.filter(function(e){return"audio"===e.trackMediaType}),i=t.filter(function(e){return"audio"!==e.trackMediaType}),n=!1,r.length>0&&(o=(this.sessionManager.mixedLocalAudioTrack.getMicAudioTrack()?1:0)+(this.sessionManager.mixedLocalAudioTrack.getScreenAudioTrack()?1:0),r.length>=o?(this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),i.push(this.sessionManager.mixedLocalAudioTrack),n=!0):(r[0].source===exports.AudioSourceInfo.MIC?this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null):this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.updateMixedAudioTrackToPub())),a=new Set(i.map(function(e){return e.getTrackId()})),(s=te(this.sessionManager.sessions.values()).filter(function(e){var t,r;return e instanceof an&&a.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())&&"video"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})).forEach(function(e){u.reporter.trace.unpublish(e.id)}),c=te(s),n&&(c.push(this.sessionManager.mixedLocalAudioTrack.getPublication()),this.sessionManager.mixedLocalAudioTrack.setPublication(null)),e.abrupt("return",this.sessionManager.batchUnPublish(c));case 6:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return p.apply(this,arguments)})},{key:"updateSubbedRemoteTrack",value:function(e,t){var r=this;if(null==t||!t.mediaStream)return null;var i=this.rtcUserManager.users.get(e.uid);if("audio"===e.mediaType){var n=this.remoteAudioTrack;return this.remoteAudioTrack=Te(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),n||t.once("audio-first-frame",function(){r.remoteAudioTrack.emit("first-frame-decoded")}),this.remoteAudioTrack}return i.updateSubbedVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(c=n($.mark(function e(t){var r,i,n,o,a,s=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map(this.handleSubscribeParam),i=this.getSubTraceId(),this.processingSubParamsMap.set(i,t),e.prev=1,e.next=2,this.sessionManager.batchSubscribe(r);case 2:return n=e.sent,o=[],t.forEach(function(e,t){var r=e.auxiliary,i=e.uid,a=n[t],c=a.error,u=a.subscription;o.push({uid:i,auxiliary:r,error:c,track:s.updateSubbedRemoteTrack(e,u)})}),e.abrupt("return",o);case 3:throw e.prev=3,a=e.catch(1),this.logger.error("batch sub error",a),a;case 4:return e.prev=4,this.processingSubParamsMap.delete(i),e.finish(4);case 5:case"end":return e.stop()}},e,this,[[1,3,4,5]])})),function(e){return c.apply(this,arguments)})},{key:"batchUnsubscribe",value:(s=n($.mark(function e(t){var r,i,n,o,a,s,c,u,d,l,p=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.resubscribePromise){e.next=5;break}return this.logger.info("wait for resuball before unsubscribe"),e.prev=1,e.next=2,this.sessionManager.resubscribePromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unsubscribe after resuball");case 5:r=[],i=Hn(t);try{for(i.s();!(n=i.n()).done;)o=n.value,a=this.checkUnsubParam(o),s=a.session,c=a.stream,u=a.user,d=a.uid,l=a.error,s&&c&&!l&&(this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:d}),r.push(Yn({stream:c,user:u,session:s},o)))}catch(e){i.e(e)}finally{i.f()}if(r.length){e.next=6;break}return e.abrupt("return",Promise.resolve());case 6:return e.abrupt("return",this.sessionManager.batchUnscribe(r).then(function(e){for(var t=0,i=r;t<i.length;t++){var n,o=i[t],a=o.mediaType,s=o.user,c=o.auxiliary;if("audio"===a)p.updateSubscribedAudioStream(!1,""),null===(n=p.remoteAudioTrack)||void 0===n||n.stopPlay(),p.remoteAudioTrack=null;else if(c){var u;null===(u=s.auxiliaryTrack)||void 0===u||u.stop(),s.auxiliaryTrack=null}else{var d;null===(d=s.videoTrack)||void 0===d||d.stop(),s.videoTrack=null}}return e}));case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return s.apply(this,arguments)})},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(t){var r=this,i=this.getStream({groupId:t});if(!i)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:i,uid:t,targetMediaType:"audio"}]).then(function(e){return r.updateSubscribedAudioStream(!0,i.id),r.remoteAudioTrack=Te(e[0].subscription.mediaStream,"audio",t,r.remoteAudioTrack),r.remoteAudioTrack})}},{key:"unsubscribeGroup",value:function(t){var r=this,i=this.getStream({groupId:t});return i?this.subscribedAudioStream!==i.id?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState,"you were not subscribed the group")):this.sessionManager.batchUnscribe([{stream:i,session:this.sessionManager.getSessionByStreamId(i.id),targetMediaType:"audio"}]).then(function(){i.id===r.subscribedAudioStream&&(r.updateSubscribedAudioStream(!1,""),r.remoteAudioTrack.stopPlay(),r.remoteAudioTrack=null)}):Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"cannot find audio info of the group"))}},{key:"setRemoteStreamType",value:function(e,t,r){this.logger.info("setRemoteStreamType",e,t,r);var i=this.getStream({uid:e,mediaType:"video",auxiliary:r}),n=this.sessionManager.getSessionByStreamId(i.id),o=Ot(t,ke(i));return n.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,i=e.publishAudioToGroup;return this.groupManager.join(e).then(function(e){t.logger.info("joinGroup response",e);var n=e.joinGroupAudioSuccess;i&&n&&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.rtcSignaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(a=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=!(a.length>1&&void 0!==a[1])||a[1],n=[],null!=r&&n.push(this.groupManager.groups.get(r).audioInfo.label),this.sessionManager.mixedLocalAudioTrack.isPublished()){t.next=1;break}throw this.logger.error("publishToGroup: no published audio track found"),new e.DingRTCError(e.ErrorCode.InvaildState,"no published audio track found");case 1:if(o=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),null==r){t.next=4;break}return t.next=2,this.mixGroupAudio(o.id,n[0],"mix");case 2:if(this.micMixedGroups.add(r),!i){t.next=3;break}return t.next=3,this.mixGroupAudio(o.id,"common","unmix");case 3:t.next=5;break;case 4:return t.next=5,this.mixGroupAudio(o.id,"common","mix");case 5:case"end":return t.stop()}},t,this)})),function(e){return a.apply(this,arguments)})},{key:"unpublishFromGroup",value:(i=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=a.length>1&&void 0!==a[1]&&a[1],n=this.groupManager.groups.get(r).audioInfo.label,this.sessionManager.mixedLocalAudioTrack.isPublished()){t.next=1;break}throw this.logger.error("unpublishFromGroup: no published audio track found"),new e.DingRTCError(e.ErrorCode.InvaildState,"no published audio track found");case 1:return o=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),t.next=2,this.mixGroupAudio(o.id,n,"unmix");case 2:if(this.micMixedGroups.delete(r),!i){t.next=3;break}return t.next=3,this.mixGroupAudio(o.id,"common","mix");case 3:case"end":return t.stop()}},t,this)})),function(e){return i.apply(this,arguments)})}]);var i,a,s,c,p,v,m}();function Kn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Kn=function(){return!!e})()}Object.defineProperty(Qn,"subAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var zn={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},$n=function(){function e(t){var r,i,a,s,c;return o(this,e),i=this,a=l(a=e),r=d(i,Kn()?Reflect.construct(a,[],l(i).constructor):a.apply(i,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=n($.mark(function e(){var t,i,n,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.client.getLocalAudioStats();case 1:return t=e.sent,i=t.audioLevel,e.next=2,r.client.getRemoteAudioStats();case 2:n=e.sent,o=n.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,i||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:Ue(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 3: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({},zn),r.client=t,r}return f(e,$r),u(e)}();function Xn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Zn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xn(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xn(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function eo(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 to(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)?to(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 to(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ro(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ro=function(){return!!e})()}var io=function(){function t(r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,ro()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"id",{enumerable:!0,configurable:!0,writable:!0,value:e.createUuid(6)}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:e.registerReporter(i.id)}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:i.reporter.getLoggerWithPrefix("[rtc-client]")}),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(i,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(i,"deviceChecker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.serviceManager=new Qn(i,i.reporter),i.handleVisibilitychange=i.handleVisibilitychange.bind(i),i.handleNetworkQuality=i.handleNetworkQuality.bind(i),i.handleConnectionChangeEvent=i.handleConnectionChangeEvent.bind(i),i.handlePageUnload=i.handlePageUnload.bind(i),i.init(),i.deviceChecker=null==r?void 0:r.deviceChecker,i}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){return this.serviceManager.rtcUserManager.remoteUsers}},{key:"groups",get:function(){return this.serviceManager.groups}},{key:"userId",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.serviceManager.publishedLocalTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.serviceManager.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.serviceManager.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,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];var o,a,s,c,u;"network-quality"!==e&&"volume-indicator"!==e&&(o=this.logger).info.apply(o,["client emit event",e].concat(i));return(a="emit",s=this,c=3,u=re(l(t.prototype),a,s),2&c&&"function"==typeof u?function(e){return u.apply(s,e)}:u)([e].concat(i))}},{key:"startPlugin",value:(h=n($.mark(function e(t,r){var i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("startPlugin",t,r),"DeviceChecker"===t){e.next=1;break}return this.logger.error("not supported plugin",t),e.abrupt("return",Promise.reject("not supported plugin"));case 1:if(this.deviceChecker){e.next=2;break}return this.logger.error("deviceChecker should be created in DingRTC.createClient before start"),e.abrupt("return",Promise.reject("plugin not created"));case 2:return e.prev=2,e.abrupt("return",this.deviceChecker.start(r));case 3:return e.prev=3,i=e.catch(2),this.logger.error("startPlugin error",t,r,i),e.abrupt("return",Promise.reject(i));case 4:case"end":return e.stop()}},e,this,[[2,3]])})),function(e,t){return h.apply(this,arguments)})},{key:"join",value:(m=n($.mark(function t(r){var i,n,o=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.logger.info("join",r),t.prev=1,this.addEventListeners(),void 0===r.initMicMuted&&(r.initMicMuted=!0),t.next=2,this.serviceManager.join(r).then(function(t){var i;return o.channelName=r.channel,o.monitor=new $n(o),o.monitor.on("audio-device-buffer",function(e){o.reporter.metric.audioDeviceBuffer(e)}),o.syncStatTimer=e.addTimer(function(){o.sendClientStatToRemote()},2e3,"interval"),{remoteUsers:o.remoteUsers,timeLeft:null===(i=t.room)||void 0===i?void 0:i.timeLeft}}).catch(function(e){throw o.init(),e});case 2:return i=t.sent,t.abrupt("return",i);case 3:return t.prev=3,n=t.catch(1),this.logger.error("join error",r,n),t.abrupt("return",Promise.reject(n));case 4:case"end":return t.stop()}},t,this,[[1,3]])})),function(e){return m.apply(this,arguments)})},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.logger.info("setRemoteDefaultVideoStreamType",e),this.serviceManager.defaultVideoStreamType=e}},{key:"leave",value:function(){this.logger.info("leave"),this.serviceManager.leave(),this.init()}},{key:"publish",value:(v=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f,v=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if((i=this.logger).info.apply(i,["publish"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),t.prev=1,"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.PublishNotJoinChannel)));case 2:n=(Array.isArray(r)?r:[r]).filter(function(e){return e instanceof Qt&&!v.localTracks.includes(e)}),o=n.concat(this.localTracks),a=X(X(X(X({},"video"+exports.VideoSourceInfo.CAMERA,0),"video"+exports.VideoSourceInfo.SCREENCAST,0),"audio"+exports.AudioSourceInfo.MIC,0),"audio"+exports.AudioSourceInfo.SCREENCAST,0),s=eo(o),t.prev=3,s.s();case 4:if((c=s.n()).done){t.next=6;break}if(u=c.value,a[u.trackMediaType+u.source]++,!(a[u.trackMediaType+u.source]>=2)){t.next=5;break}throw new e.DingRTCError(e.ErrorCode.QuotaLimitExceed,"".concat(u.trackMediaType,"-").concat(u.source," published already"));case 5:t.next=4;break;case 6:t.next=8;break;case 7:t.prev=7,p=t.catch(3),s.e(p);case 8:return t.prev=8,s.f(),t.finish(8);case 9:if(n.length){t.next=10;break}throw new e.DingRTCError(e.ErrorCode.PublishNoStream);case 10:return t.next=11,this.serviceManager.publish(n);case 11:return d=t.sent,t.abrupt("return",d);case 12:return t.prev=12,f=t.catch(1),(l=this.logger).error.apply(l,["publish error"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[f])),t.abrupt("return",Promise.reject(f));case 13:case"end":return t.stop()}},t,this,[[1,12],[3,7,8,9]])})),function(e){return v.apply(this,arguments)})},{key:"unpublish",value:(p=n($.mark(function t(r){var i,n,o,a,s;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if((i=this.logger).info.apply(i,["unpublish param"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),t.prev=1,n=Array.isArray(r)?r:[r],r||(n=this.localTracks),this.logger.info("unpublish tracks",n.map(function(e){return e.trackMediaType})),"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 2:return t.next=3,this.serviceManager.unpublish(n);case 3:return o=t.sent,t.abrupt("return",o);case 4:return t.prev=4,s=t.catch(1),(a=this.logger).error.apply(a,["unpub error"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[s])),t.abrupt("return",Promise.reject(s));case 5:case"end":return t.stop()}},t,this,[[1,4]])})),function(e){return p.apply(this,arguments)})},{key:"subscribe",value:(c=n($.mark(function t(r,i,n){var o,a;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("subscribe",r,i,n),"connected"===this.connectionState){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 1:return t.next=2,this.serviceManager.batchSubscribe([{uid:r,mediaType:i,auxiliary:n}]).then(function(e){var t=e[0],r=t.error,i=t.track;if(r)throw r;return i});case 2:return o=t.sent,t.abrupt("return",o);case 3:return t.prev=3,a=t.catch(0),this.logger.error("subscribe error",r,i,n,a),t.abrupt("return",Promise.reject(a));case 4:case"end":return t.stop()}},t,this,[[0,3]])})),function(e,t,r){return c.apply(this,arguments)})},{key:"batchSubscribe",value:(s=n($.mark(function t(r){var i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("batchSubscribe",r),Array.isArray(r)&&r.length){t.next=1;break}return t.abrupt("return");case 1:if("connected"===this.connectionState){t.next=2;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 2:return t.next=3,this.serviceManager.batchSubscribe(r.map(function(e){return Zn(Zn({},e),{},{action:"subscribe"})}));case 3:return i=t.sent,t.abrupt("return",i);case 4:return t.prev=4,n=t.catch(0),this.logger.error("batchSubscribe error",n),t.abrupt("return",Promise.reject(n));case 5:case"end":return t.stop()}},t,this,[[0,4]])})),function(e){return s.apply(this,arguments)})},{key:"unsubscribe",value:(a=n($.mark(function t(r,i,n){var o,a;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.logger.info("unsubscribe",r,i,n),t.prev=1,"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 2:return t.next=3,this.serviceManager.batchUnsubscribe([{uid:r,auxiliary:n,mediaType:i}]).then(function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r});case 3:return o=t.sent,t.abrupt("return",o);case 4:return t.prev=4,a=t.catch(1),this.logger.error("unsubscribe error",r,i,a),t.abrupt("return",Promise.reject(a));case 5:case"end":return t.stop()}},t,this,[[1,4]])})),function(e,t,r){return a.apply(this,arguments)})},{key:"batchUnsubscribe",value:(i=n($.mark(function t(r){var i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.logger.info("batchUnsubscribe",r),t.prev=1,Array.isArray(r)&&r.length){t.next=2;break}return t.abrupt("return");case 2:if("connected"===this.connectionState){t.next=3;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel)));case 3:return t.next=4,this.serviceManager.batchUnsubscribe(r.map(function(e){return Zn(Zn({},e),{},{action:"unsubscribe"})}));case 4:return i=t.sent,t.abrupt("return",i);case 5:return t.prev=5,n=t.catch(1),this.logger.error("batchUnsubscribe error",r,n),t.abrupt("return",Promise.reject(n));case 6:case"end":return t.stop()}},t,this,[[1,5]])})),function(e){return i.apply(this,arguments)})},{key:"getLocalAudioStats",value:function(){return this.serviceManager.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.serviceManager.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:(r=n($.mark(function t(r,i,n){var o,a,s,c=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("setRemoteVideoStreamType",r,i,n),"connected"===this.connectionState){t.next=1;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 1:if(null!=(o=this.remoteUsers.find(function(e){return e.userId===r}))&&o.relatedStreams){t.next=2;break}return this.logger.info("".concat(r," videoTrack not existed")),t.abrupt("return",Promise.reject("viedoTrack doesnt exiested"));case 2:return t.next=3,this.serviceManager.setRemoteStreamType(r,i,n).then(function(){c.emit("stream-type-changed",r,i,n)});case 3:return a=t.sent,t.abrupt("return",a);case 4:return t.prev=4,s=t.catch(0),this.logger.error("setRemoteVideoStreamType error",r,i,n,s),t.abrupt("return",Promise.reject(s));case 5:case"end":return t.stop()}},t,this,[[0,4]])})),function(e,t,i){return r.apply(this,arguments)})},{key:"getRemoteVideoStats",value:function(){return this.serviceManager.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.serviceManager.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach(function(t){var r,i,n=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==n||null===(r=n[ue])||void 0===r?void 0:r[K.DOWNLINK])||0),uplinkNetworkQuality:Number((null==n||null===(i=n[ue])||void 0===i?void 0:i[K.UPLINK])||0)}}),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.logger.info("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 i=Fe(null,r[K.UPLINK]),n=Fe(null,this.currentClientState[K.UPLINK]),o=Fe(null,r[K.DOWNLINK]),a=Fe(null,this.currentClientState[K.DOWNLINK]);i===n&&o===a||this.serviceManager.rtcUserManager.setParticipantProperties(r).catch(function(r){t.logger.info("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[K.BACKGROUND_MODE]=Number(t))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[K.UPLINK]=e,this.clientStatSync[K.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.logger.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.serviceManager.sessionManager.on("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.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.serviceManager.sessionManager.off("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(t){this.logger.info("joinGroup",t);try{if("connected"!==this.connectionState)return Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail));var r=t.userData,i=t.groupId,n=new TextEncoder;if(!i||n.encode(i).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.serviceManager.joinGroup(t)}catch(e){return this.logger.error("joinGroup error",t,e),Promise.reject(e)}}},{key:"leaveGroup",value:function(t){this.logger.info("leaveGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.leaveGroup({groupId:t,publishAudioToChannel:!1})}catch(e){return this.logger.error("leaveGroup error",t,e),Promise.reject(e)}}},{key:"setGroupName",value:function(t,r){this.logger.info("setGroupName",t,r);try{if("connected"!==this.connectionState)return Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail));var i=new TextEncoder;if(!r||i.encode(r).length>64)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"update group with invalid name");return this.serviceManager.setGroupProperties(t,{key:"name",value:r})}catch(e){return this.logger.error("setGroupName error",t,r,e),Promise.reject(e)}}},{key:"subscribeGroup",value:function(t){this.logger.info("subscribeGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.subscribeGroup(t)}catch(e){return this.logger.error("subscribeGroup error",t,e),Promise.reject(e)}}},{key:"unsubscribeGroup",value:function(t){this.logger.info("unsubscribeGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.unsubscribeGroup(t)}catch(e){return this.logger.error("unsubscribeGroup error",t,e),Promise.reject(e)}}},{key:"mixAudioToGroup",value:function(t,r,i){this.logger.info("mixAudioToGroup",{mediaType:null==t?void 0:t.trackMediaType,trackId:null==t?void 0:t.getTrackId(),source:null==t?void 0:t.source},r,i);try{if("connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.ConnectionConnectFail);if(r){if(this.logger.info("mix audio to group ".concat(i)),null==i&&this.serviceManager.micMixedGroups.size)throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot mix audio to channel while mixing to others group");return this.serviceManager.publishToGroup(i,!0)}if(this.logger.info("unmix audio from group ".concat(i)),!this.serviceManager.micMixedGroups.has(i))throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot unmix audio from the unmixed group");return this.serviceManager.unpublishFromGroup(i)}catch(e){return this.logger.error("mixAudioToGroup error",{mediaType:null==t?void 0:t.trackMediaType,trackId:null==t?void 0:t.getTrackId(),source:null==t?void 0:t.source},r,i,e),Promise.reject(e)}}},{key:"dismissGroup",value:function(t){this.logger.info("dismissGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.dismissGroup(t)}catch(e){return this.logger.error("dismissGroup error",t,e),Promise.reject(e)}}},{key:"register",value:function(e){this.logger.info("register",e),e.attach(this.serviceManager.internalChannel,this.serviceManager)}},{key:"ungister",value:function(e){this.logger.info("ungister",e),e.detach(this.serviceManager.internalChannel)}}]);var r,i,a,s,c,p,v,m,h}(),no=function(){var e=n($.mark(function e(t){var r;return $.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 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function oo(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(oo=function(){return!!e})()}et();var ao=e.getReporter().getLoggerWithPrefix("[rtc-index]");ao.info("sdk version",ae),ao.info("userAgent",navigator.userAgent),ao.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),no(ao);var so=new(function(){function t(){var r,i,n,a;if(o(this,t),i=this,n=l(n=t),r=d(i,oo()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.VERSION=ae,!ve.checkSupported())return d(r);var s=xe.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(t){ao.info("createClient",null==t?void 0:t.map(function(e){return null==e?void 0:e.pluginName}));var r=null==t?void 0:t.find(function(e){return"DeviceChecker"===(null==e?void 0:e.pluginName)}),i=null==r?void 0:r.createPlugin();return null==i||i.injectLogger(e.getReporter().getLoggerWithPrefix("[rtc-devcheck]")),new io({deviceChecker:i})}},{key:"checkSystemRequirements",value:function(){return ao.info("checkSystemRequirements"),ve.checkSupported()}},{key:"getSupportedCodec",value:function(){return ao.info("getSupportedCodec"),ve.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return ao.info("createCameraVideoTrack",e),er(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return ao.info("createMicrophoneAudioTrack",e),Zt(e)}},{key:"createCustomVideoTrack",value:function(e){return ao.info("createCustomVideoTrack",e),or(e)}},{key:"createCustomAudioTrack",value:function(e){return ao.info("createCustomAudioTrack",e),ar(e)}},{key:"createScreenVideoTrack",value:function(e){return ao.info("createScreenVideoTrack",e),tr(e)}},{key:"createScreenVideoAndAudioTrack",value:function(e){return ao.info("createScreenVideoAndAudioTrack",e),ir(e)}},{key:"createMicrophoneAndCameraTracks",value:(i=n($.mark(function e(t,r){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ao.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",nr(t,r));case 1:case"end":return e.stop()}},e)})),function(e,t){return i.apply(this,arguments)})},{key:"getCameras",value:function(){return ao.info("getCameras"),xe.getCameras()}},{key:"getDevices",value:(r=n($.mark(function e(){var t,r;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ao.info("start getDevices"),e.prev=1,e.next=2,xe.getDevices();case 2:return t=e.sent,ao.info("getDevices suc",t),e.abrupt("return",t);case 3:return e.prev=3,r=e.catch(1),ao.info("error getDevices ",r),e.abrupt("return",r);case 4:case"end":return e.stop()}},e,null,[[1,3]])})),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return ao.info("getPlaybackDevices"),xe.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return ao.info("getMicrophones"),xe.getMicrophones()}},{key:"setLogLevel",value:function(t){console.warn("[dingrtc]: setLogLevel is deprecated"),e.setLogLevel(be._consoleLogLevel),ao.info(" setLogLevel - ignored and hint deprecated",t)}},{key:"setClientConfig",value:function(e){ao.info("setClientConfig",e),be.setClientConfig(e)}}]);var r,i}());Object.defineProperty(exports,"ErrorCodeAndMsgMap",{enumerable:!0,get:function(){return e.ErrorCodeAndMsgMap}}),exports.FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},exports.default=so;
|
|
3
|
+
var i,n,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",s=o.toStringTag||"@@toStringTag";function c(e,r,o,a){var s=r&&r.prototype instanceof d?r:d,c=Object.create(s.prototype);return t(c,"_invoke",function(e,t,r){var o,a,s,c=0,d=r||[],l=!1,p={p:0,n:0,v:i,a:f,f:f.bind(i,4),d:function(e,t){return o=e,a=0,s=i,p.n=t,u}};function f(e,t){for(a=e,s=t,n=0;!l&&c&&!r&&n<d.length;n++){var r,o=d[n],f=p.p,v=o[2];e>3?(r=v===t)&&(s=o[(a=o[4])?5:(a=3,3)],o[4]=o[5]=i):o[0]<=f&&((r=e<2&&f<o[1])?(a=0,p.v=t,p.n=o[1]):f<v&&(r=e<3||o[0]>t||t>v)&&(o[4]=e,o[5]=t,p.n=v,a=0))}if(r||e>1)return u;throw l=!0,t}return function(r,d,v){if(c>1)throw TypeError("Generator is already running");for(l&&1===d&&f(d,v),a=d,s=v;(n=a<2?i:s)||!l;){o||(a?a<3?(a>1&&(p.n=-1),f(a,s)):p.n=s:p.v=s);try{if(c=2,o){if(a||(r="next"),n=o[r]){if(!(n=n.call(o,s)))throw TypeError("iterator result is not an object");if(!n.done)return n;s=n.value,a<2&&(a=0)}else 1===a&&(n=o.return)&&n.call(o),a<2&&(s=TypeError("The iterator does not provide a '"+r+"' method"),a=1);o=i}else if((n=(l=p.n<0)?s:e.call(t,p))!==u)break}catch(e){o=i,a=1,s=e}finally{c=1}}return{value:n,done:l}}}(e,o,a),!0),c}var u={};function d(){}function l(){}function p(){}n=Object.getPrototypeOf;var f=[][a]?n(n([][a]())):(t(n={},a,function(){return this}),n),v=p.prototype=d.prototype=Object.create(f);function m(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,p):(e.__proto__=p,t(e,s,"GeneratorFunction")),e.prototype=Object.create(v),e}return l.prototype=p,t(v,"constructor",p),t(p,"constructor",l),l.displayName="GeneratorFunction",t(p,s,"GeneratorFunction"),t(v),t(v,s,"Generator"),t(v,a,function(){return this}),t(v,"toString",function(){return"[object Generator]"}),(e.exports=r=function(){return{w:c,m:m}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(y);var P=y.exports,T={exports:{}},w={exports:{}},E={exports:{}};!function(e){var t=b,r=S;e.exports=function e(i,n){function o(e,r,a,s){try{var c=i[e](r),u=c.value;return u instanceof t?n.resolve(u.v).then(function(e){o("next",e,a,s)},function(e){o("throw",e,a,s)}):n.resolve(u).then(function(e){c.value=e,a(c)},function(e){return o("throw",e,a,s)})}catch(e){s(e)}}var a;this.next||(r(e.prototype),r(e.prototype,"function"==typeof Symbol&&Symbol.asyncIterator||"@asyncIterator",function(){return this})),r(this,"_invoke",function(e,t,r){function i(){return new n(function(t,i){o(e,r,t,i)})}return a=a?a.then(i,i):i()},!0)},e.exports.__esModule=!0,e.exports.default=e.exports}(E);var I=E.exports;!function(e){var t=P,r=I;e.exports=function(e,i,n,o,a){return new r(t().w(e,i,n,o),a||Promise)},e.exports.__esModule=!0,e.exports.default=e.exports}(w);var M=w.exports;!function(e){var t=M;e.exports=function(e,r,i,n,o){var a=t(e,r,i,n,o);return a.next().then(function(e){return e.done?e.value:a.next()})},e.exports.__esModule=!0,e.exports.default=e.exports}(T);var O=T.exports,R={exports:{}};!function(e){e.exports=function(e){var t=Object(e),r=[];for(var i in t)r.unshift(i);return function e(){for(;r.length;)if((i=r.pop())in t)return e.value=i,e.done=!1,e;return e.done=!0,e}},e.exports.__esModule=!0,e.exports.default=e.exports}(R);var A=R.exports,x={exports:{}},C={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}(C);var _=C.exports;!function(e){var t=_.default;e.exports=function(e){if(null!=e){var r=e["function"==typeof Symbol&&Symbol.iterator||"@@iterator"],i=0;if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length))return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}}}throw new TypeError(t(e)+" is not iterable")},e.exports.__esModule=!0,e.exports.default=e.exports}(x);var D=x.exports;!function(e){var t=b,r=P,i=O,n=M,o=I,a=A,s=D;function c(){var u=r(),d=u.m(c),l=(Object.getPrototypeOf?Object.getPrototypeOf(d):d.__proto__).constructor;function p(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===l||"GeneratorFunction"===(t.displayName||t.name))}var f={throw:1,return:2,break:3,continue:3};function v(e){var t,r;return function(i){t||(t={stop:function(){return r(i.a,2)},catch:function(){return i.v},abrupt:function(e,t){return r(i.a,f[e],t)},delegateYield:function(e,n,o){return t.resultName=n,r(i.d,s(e),o)},finish:function(e){return r(i.f,e)}},r=function(e,r,n){i.p=t.prev,i.n=t.next;try{return e(r,n)}finally{t.next=i.n}}),t.resultName&&(t[t.resultName]=i.v,t.resultName=void 0),t.sent=i.v,t.next=i.n;try{return e.call(this,t)}finally{i.p=t.prev,i.n=t.next}}}return(e.exports=c=function(){return{wrap:function(e,t,r,i){return u.w(v(e),t,r,i&&i.reverse())},isGeneratorFunction:p,mark:u.m,awrap:function(e,r){return new t(e,r)},AsyncIterator:o,async:function(e,t,r,o,a){return(p(t)?n:i)(v(e),t,r,o,a)},keys:a,values:s}},e.exports.__esModule=!0,e.exports.default=e.exports)()}e.exports=c,e.exports.__esModule=!0,e.exports.default=e.exports}(h);var j=(0,h.exports)(),L=j;try{regeneratorRuntime=j}catch(e){"object"==typeof globalThis?globalThis.regeneratorRuntime=j:Function("r","regeneratorRuntime = r")(j)}var N,V,F,U,G,B,H,q,W,Y,J,Q,K,z,$=v(L);function X(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 Z(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ee(e,t){if(e){if("string"==typeof e)return Z(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)?Z(e,t):void 0}}function te(e){return function(e){if(Array.isArray(e))return Z(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||ee(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 re(){return re="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,r){var i=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=l(e)););return e}(e,t);if(i){var n=Object.getOwnPropertyDescriptor(i,t);return n.get?n.get.call(arguments.length<3?e:r):n.value}},re.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"}(N||(N={})),function(e){e.VP8="vp8",e.VP9="vp9",e.H264="h264",e.H265="h265",e.AV1="av1",e.AV1X="av1x"}(V||(V={})),exports.AudioSourceInfo=void 0,(F=exports.AudioSourceInfo||(exports.AudioSourceInfo={})).MIC="mic",F.SCREENCAST="screen-cast",F.MIXED="mixed",exports.VideoSourceInfo=void 0,(U=exports.VideoSourceInfo||(exports.VideoSourceInfo={})).CAMERA="camera",U.SCREENCAST="screen-cast",U.MIXED="mixed",function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(G||(G={})),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"}(B||(B={})),function(e){e[e.Native=1]="Native",e[e.Web=2]="Web",e[e.MiniProgram=3]="MiniProgram"}(H||(H={})),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"}(q||(q={})),function(e){e[e.UserKickOut=2011]="UserKickOut",e[e.UserReplaced=2012]="UserReplaced"}(W||(W={})),function(e){e[e.Idle=0]="Idle",e[e.Processing=1]="Processing",e[e.End=2]="End"}(Y||(Y={})),function(e){e[e.New=0]="New",e[e.Idle=1]="Idle",e[e.Processing=2]="Processing",e[e.Ended=3]="Ended"}(J||(J={})),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"}(Q||(Q={})),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"}(K||(K={})),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"}(z||(z={}));var ie,ne="3.9.22-beta.1",oe={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,(ie=exports.AudioSourceState||(exports.AudioSourceState={})).Playing="playing",ie.Paused="paused",ie.Stopped="stopped";var ae=ne,se=-999,ce="rtc-label";JSON.stringify({needPersonalityAudioStream:!0,outPeerConnectionNotReuse:!0}),e.Environment.browserType,e.Environment.browserVersion,e.Environment.system,e.Environment.systemVersion;var ue="onertc_state_sync",de="onertc_internal_track_event",le="rtc_sdk_el_data",pe="rtc_sdk_player_container_label",fe=e.getReporter().getLoggerWithPrefix("rtc-support"),ve=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=n($.mark(function t(){var r,i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return r={audio:[],video:[]},t.prev=1,(i=new RTCPeerConnection).addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"}),t.next=2,i.createOffer();case 2:if(n=t.sent.sdp){t.next=3;break}return t.abrupt("return",r);case 3:return i.close(),i=null,n.match(/ VP8/i)&&r.video.push("VP8"),n.match(/ VP9/i)&&r.video.push("VP9"),n.match(/ AV1/i)&&r.video.push("AV1"),n.match(/ H264/i)&&r.video.push("H264"),n.match(/ H265/i)&&r.video.push("H265"),n.match(/ opus/i)&&r.audio.push("OPUS"),n.match(/ PCMU/i)&&r.audio.push("PCMU"),n.match(/ PCMA/i)&&r.audio.push("PCMA"),n.match(/ G722/i)&&r.audio.push("G722"),t.abrupt("return",r);case 4:throw t.prev=4,t.catch(1),fe.error("get supportedCodecs failed"),new e.DingRTCError(e.ErrorCode.IceConnectionSetLocalDescFail,"get supportedCodecs failed");case 5:case"end":return t.stop()}},t,null,[[1,4]])})),function(){return t.apply(this,arguments)})},{key:"checkSupported",value:function(){var t=!1;try{var r=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,n=window.WebSocket;t=!!(r&&i&&n)}catch(e){return fe.error("checkSystemRequirements error",e),!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 fe.info("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}()),me=function(){var t,r=(null===(t=window.RTCRtpSender)||void 0===t?void 0:t.prototype)||{},i=r.setParameters,n=r.getParameters;return!(!i||!n)&&(!e.Environment.isFirefox()&&(e.Environment.isSafari()?parseInt(e.Environment.browserVersion)>=14:e.Environment.isChrome()?parseInt(e.Environment.browserVersion)>=81:!e.Environment.isAndroid()))};function he(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(he=function(){return!!e})()}var ge=e.getReporter().getLoggerWithPrefix("[rtc-config]"),be=new(function(){function t(){var e,r,i,n;return o(this,t),r=this,i=l(i=t),e=d(r,he()?Reflect.construct(i,[],l(r).constructor):i.apply(r,n)),Object.defineProperty(e,"gslb",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(e,"simulcast",{enumerable:!0,configurable:!0,writable:!0,value:me()}),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,"preferH264CbProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"downlinkForbidHighProfile",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"highStartBitrate",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_holdVideoLastFrame",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(e,"_consoleLogLevel",{enumerable:!0,configurable:!0,writable:!0,value:"warn"}),Object.defineProperty(e,"connectPcTimeoutMs",{enumerable:!0,configurable:!0,writable:!0,value:4e3}),e.setClientConfig({gslb:["https://gslb.dingrtc.com"]}),e}return f(t,e.EventEmitter),u(t,[{key:"setClientConfig",value:function(t){ge.info("setClientConfig",t);var r=t||{},i=r.gslb,n=r.simulcast,o=r.audioSFU,a=r.republish,s=r.disableTransportCC,c=r.highStartBitrate;"string"==typeof i&&(this.gslb=[i],e.setGslb(i)),Array.isArray(i)&&e.isString(i[0])&&(this.gslb=i,e.setGslb(i[0])),null!=n&&me()&&(this.simulcast=Boolean(n)),null!=o&&(this.audioSFU=Boolean(o)),null!=s&&(this.disableTransportCC=Boolean(s)),null!=a&&(this.republish=Boolean(a)),null!=c&&(this.highStartBitrate=!!c),null!=t&&t._consoleLogLevel&&(this._consoleLogLevel=null==t?void 0:t._consoleLogLevel),"boolean"==typeof(null==t?void 0:t.preferH264CbProfile)&&(this.preferH264CbProfile=t.preferH264CbProfile),(null==t?void 0:t.connectPcTimeoutMs)>=0&&t.connectPcTimeoutMs<=Number.MAX_SAFE_INTEGER?this.connectPcTimeoutMs=t.connectPcTimeoutMs:void 0!==(null==t?void 0:t.connectPcTimeoutMs)&&null!==(null==t?void 0:t.connectPcTimeoutMs)&&console.error("connectPcTimeoutMs should be a non-negative number")}}])}()),ye=function(e,t){return e.width!==t.width?e.width-t.width:e.height-t.height},ke=function(e){var t;if(!e)return[];var r=e.media.video;if(!r)return[];var i=[],n=r.optional,o=r.parameters;return null!=o&&o.resolution&&i.push(o.resolution),null!=n&&null!==(t=n.parameters)&&void 0!==t&&null!==(t=t.resolution)&&void 0!==t&&t.length&&i.push.apply(i,te(n.parameters.resolution)),i.sort(ye),i},Se=function(t,r){var i,n=t.media,o=n.audio,a=n.video;if(r===Q.QuotaLimit)return i=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if(o)i=new e.DingRTCError(e.ErrorCode.SubscribeAudioStreamFailed,r);else if(a){var s=a.source;s===exports.VideoSourceInfo.CAMERA?i=new e.DingRTCError(e.ErrorCode.SubscribeVideoStreamFailed,r):s===exports.VideoSourceInfo.SCREENCAST&&(i=new e.DingRTCError(e.ErrorCode.SubscribeScreenShareFailed,r))}return i},Pe=function(t,r){var i,n=t.trackMediaType;if(r===Q.QuotaLimit)return i=new e.DingRTCError(e.ErrorCode.QuotaLimitExceed);if("audio"===n)i=new e.DingRTCError(e.ErrorCode.PublishAudioStreamFailed,r);else{var o=t.source;o===exports.VideoSourceInfo.CAMERA?i=new e.DingRTCError(e.ErrorCode.PublishVideoStreamFailed,r):o===exports.VideoSourceInfo.SCREENCAST&&(i=new e.DingRTCError(e.ErrorCode.PublishScreenShareFailed,r))}return i},Te=function(e,t,r,i){var n=i,o=e.getVideoTracks(),a=e.getAudioTracks();return"audio"===t&&a.length?be.audioSFU?i?i.replaceStream(e):n=new vr(null,r,e):i?i.replaceTrack(a[0]):n=new vr(a[0],r):"video"===t&&o.length&&(i?i.replaceTrack(o[0]):n=new mr(o[0],r)),n},we=function(e){return"object"===a(e.video)&&e.video.source===exports.VideoSourceInfo.SCREENCAST};function Ee(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ie(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Ee(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Ee(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Me(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 Oe(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)?Oe(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Oe(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Re(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Re=function(){return!!e})()}var Ae=e.getReporter().getLoggerWithPrefix("[rtc-device]"),xe=function(){function t(){var e,r,i,a,s;return o(this,t),r=this,i=l(i=t),e=d(r,Re()?Reflect.construct(i,[],l(r).constructor):i.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=n($.mark(function r(){var i;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(!e.checking){r.next=1;break}return r.abrupt("return");case 1:return e.checking=!0,r.next=2,t.getDevices();case 2:i=r.sent,e.compareDevices(i,"audiooutput"),e.compareDevices(i,"videoinput"),e.compareDevices(i,"audioinput"),e.deviceList=i,e.checking=!1;case 3: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 i,n=t.filter(function(e){return e.kind===r}),o=e.deviceList.filter(function(e){return e.kind===r}),a=n.map(function(e){return e.deviceId}),s=o.map(function(e){return e.deviceId}),c=n.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=Me(c);try{for(l.s();!(i=l.n()).done;){var p=i.value;e.emit(d[r],{device:p,state:"active"})}}catch(e){l.e(e)}finally{l.f()}var f,v=Me(u);try{for(v.s();!(f=v.n()).done;){var m=f.value;e.emit(d[r],{device:m,state:"inactive"})}}catch(e){v.e(e)}finally{v.f()}}}),t._instance?d(e,t._instance):(e.deviceList=[],ve.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:(r=n($.mark(function r(i,n){var o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(t.accGetMedia++,o=t.accGetMedia,!we(i)){r.next=6;break}if(Ae.info("getDisplayMedia with",o,i,n),!e.Environment.isElectron()){r.next=3;break}if(n.video){r.next=1;break}throw new e.DingRTCError(e.ErrorCode.ScreenShareOpenFail,"only video screen cast is supported, but got no video parameters");case 1:return r.next=2,navigator.mediaDevices.getUserMedia({audio:!1,video:{mandatory:{chromeMediaSource:"screen",minWidth:(null===(s=n.video)||void 0===s?void 0:s.width)||1280,maxWidth:(null===(c=n.video)||void 0===c?void 0:c.width)||1280,minHeight:(null===(u=n.video)||void 0===u?void 0:u.height)||720,maxHeight:(null===(d=n.video)||void 0===d?void 0:d.height)||720,minFrameRate:(null===(l=n.video)||void 0===l?void 0:l.frameRate)||5,maxFrameRate:(null===(p=n.video)||void 0===p?void 0:p.frameRate)||5}}});case 2:a=r.sent,r.next=5;break;case 3:return r.next=4,null===(f=navigator.mediaDevices)||void 0===f?void 0:f.getDisplayMedia(n);case 4:a=r.sent;case 5:return Ae.info("succ getDisplayMedia with",o),r.abrupt("return",a);case 6:return Ae.info("getUserMedia with",o,i,n),r.next=7,null===(v=navigator.mediaDevices)||void 0===v?void 0:v.getUserMedia(n);case 7:return m=r.sent,Ae.info("succ getUserMedia with",o),i.audio&&(this.audioPermitted=!0),i.video&&(this.videoPermitted=!0),r.abrupt("return",m);case 8:case"end":return r.stop()}},r,this)})),function(e,t){return r.apply(this,arguments)})},{key:"getDevices",value:function(){var t=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{audio:!0,video:!0},i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(function(n,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||i?l.length?(r.audio&&(t.audioPermitted=!0),r.video&&(t.videoPermitted=!0),n(l)):n(l):(Ae.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){n(e)},o)},o)),n(a)})}else o(new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"enumerateDevices is not supported"))})}}]);var r}();Object.defineProperty(xe,"videoPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(xe,"audioPermitted",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(xe,"_instance",{enumerable:!0,configurable:!0,writable:!0,value:new xe}),Object.defineProperty(xe,"accGetMedia",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(xe,"getPlaybackDevices",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({audio:!0}).then(function(e){return e.filter(function(e){return"audiooutput"===e.kind})}).catch(function(t){throw e.parseAudioDeviceError(t)})}}),Object.defineProperty(xe,"getCameras",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({video:!0}).then(function(e){return Ae.info("getCameras",e),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 Ie(Ie({},r),{},{toJSON:function(){return r}})})}).catch(function(t){throw Ae.error("getCameras error",t),e.parseVideoDeviceError(t)})}}),Object.defineProperty(xe,"getMicrophones",{enumerable:!0,configurable:!0,writable:!0,value:function(){return xe.getDevices({audio:!0}).then(function(e){return Ae.info("getMicrophones",e),e.filter(function(e){return"audioinput"===e.kind})}).catch(function(t){throw Ae.error("getMicrophones error",t),e.parseAudioDeviceError(t)})}});var Ce,_e,De=function(e){return{width:oe[e][0],height:oe[e][1]}},je=function(t){var r,i=Object.create({}),n={};null!==(r=navigator)&&void 0!==r&&null!==(r=r.mediaDevices)&&void 0!==r&&r.getSupportedConstraints&&(n=navigator.mediaDevices.getSupportedConstraints(),console.log(n));var o=t.AEC,a=t.AGC,s=t.ANS;return t.deviceId&&(e.Environment.isSafari()?i.deviceId=t.deviceId:i.deviceId={exact:t.deviceId}),n.autoGainControl&&(i.autoGainControl={ideal:null==a||a}),n.echoCancellation&&(i.echoCancellation={ideal:null==o||o}),n.noiseSuppression&&(i.noiseSuppression={ideal:null==s||s}),i},Le=function(t){if(!e.isObject(t)||!t.audio&&!t.video)return Promise.reject(new TypeError("Invalid constrains"));var r=t.audio,i=t.video;if(!we(t)&&"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST)return Promise.reject(new TypeError("Cannot share screen without video."));if(we(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&&!i)return Promise.reject(new TypeError("At least one of audio and video must be requested."));var n={};if("object"===a(r)&&r.source===exports.AudioSourceInfo.MIC||"object"===a(r)&&r.source===exports.AudioSourceInfo.SCREENCAST?n.audio=je(r):n.audio=t.audio,"object"===a(i)){var o,s=i.frameRate,c=i.deviceId,u=i.source,d=i.facingMode,l=i.displaySurface,p=i.dimension;n.video={},e.isNumber(s)&&(n.video.frameRate=Math.min(i.frameRate,30)),p&&(o=De(p)),o&&o.width&&o.height&&(u===exports.VideoSourceInfo.SCREENCAST||e.Environment.isFirefox()?(n.video.width=o.width,n.video.height=o.height):(n.video.width={ideal:o.width,max:o.width},n.video.height={ideal:o.height,max:o.height})),e.isString(c)&&c&&(n.video.deviceId={exact:c}),u===exports.VideoSourceInfo.SCREENCAST&&(e.Environment.isFirefox()&&(n.video.mediaSource="screen"),l&&["browser","window","monitor"].includes(l)&&(n.video.displaySurface=l)),d&&["user","environment"].includes(d)&&(n.video.facingMode=d)}else n.video=i;return xe.getMedias(t,n)},Ne=function(e){if(!e)return!1;var t=e.getVideoTracks()[0];return t&&t.enabled&&!t.muted},Ve=function(e,t){var r=(e.timestamp-((null==t?void 0:t.timestamp)||e.timestamp))/1e3;return r<=0&&(r=1),r},Fe=function(e,t){return null!=e?[2,4,6,0][e]:null!==t?[3,0,0,0,1,1,2][t]:void 0},Ue=function(e,t){isNaN(e)&&(e=0),isNaN(t)&&(t=0);var r=e-t;return r<0&&(r=e),r},Ge=function(e){var t=e.fn,r=e.times,i=e.interval,o=void 0===i?0:i,a=e.resolve,s=e.reject,c=function(){var e=n($.mark(function e(){var i,n,c;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=0;case 1:if(!(n<r)){e.next=7;break}return e.prev=2,e.next=3,t();case 3:return i=e.sent,null==a||a(i),e.abrupt("continue",7);case 4:if(e.prev=4,c=e.catch(2),n!==r-1){e.next=5;break}return null==s||s(c),e.abrupt("return",c);case 5:return e.next=6,Be(o);case 6:n++,e.next=1;break;case 7:return e.abrupt("return",i);case 8:case"end":return e.stop()}},e,null,[[2,4]])}));return function(){return e.apply(this,arguments)}}();return c()},Be=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(t>0)){e.next=1;break}return e.next=1,new Promise(function(e){setTimeout(e,t)});case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),He=function(t){return new Promise(function(r){e.addTimer(r,1e3*t)})},qe=e.getReporter().getLoggerWithPrefix("[rtc-mediaElPool]"),We="rtc-intersecting",Ye="visible",Je="invisible",Qe=["abort","canplay","canplaythrough","durationchange","emptied","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","ratechange","seeked","seeking","stalled","suspend","volumechange","waiting"],Ke=function(e){return"".concat(null==e?void 0:e.getAttribute(ce),"-").concat(null==e?void 0:e.rtcPurpose)},ze=function(){return u(function t(r,i){var n=this;o(this,t),Object.defineProperty(this,"mediaElementCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),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(){n.mediaElementPool.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementPool=[],n.allElements.clear(),n.mediaElementsInUse.forEach(function(e){return n._resetMediaElement(e)}),n.mediaElementsInUse=[],document.removeEventListener("click",n._onUserInteraction),document.removeEventListener("touchstart",n._onUserInteraction),document.removeEventListener("visibilitychange",n._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible),n.mediaPlaybackCheckInterval&&(e.removeTimer(n.mediaPlaybackCheckInterval,"interval"),n.mediaPlaybackCheckInterval=null),[].concat(te(n.mediaElementPool),te(n.mediaElementsInUse)).forEach(function(e){var t;return null===(t=n.observer)||void 0===t?void 0:t.unobserve(e)})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(t){n.mediaElementsInUse.forEach(function(r){if(r.srcObject){var i=r.srcObject;if(r.error&&(qe.debug("".concat(t,": tag=").concat(r.tagName," ").concat(Ke(r)," has error, error=").concat(r.error,", doc.visibilityState=").concat(document.visibilityState,", mediaStream="),e.getPlainMediaStreamInfo(i)),"visible"===document.visibilityState&&Ne(i)&&r.load()),r.paused){var o=!1;if(n.hasActivated&&"video"===n.mediaKind?function(e){return e&&e.getAttribute(We)===Ye}(r)&&"visible"===document.visibilityState&&"visible"===getComputedStyle(r).visibility&&(o=!0):o=!0,o){var a="".concat(t,": ").concat(Ke(r)," paused, doc.visibilityState=").concat(document.visibilityState,", intersecting=").concat(r.getAttribute(We),", mediaStream="),s=e.getPlainMediaStreamInfo(i);qe.error(a,s),Ne(i)&&r.load(),r.paused&&r.play().catch(function(e){console.error("inPoll",e)})}}}}),n.debouncer.debounce(n._tryReloadOnCurrentTimeFreeze.bind(n,t),1e3)}}),Object.defineProperty(this,"_tryReloadOnCurrentTimeFreeze",{enumerable:!0,configurable:!0,writable:!0,value:function(t){n.mediaElementsInUse.forEach(function(r){if(r.srcObject){var i=r.srcObject,o="video"===n.mediaKind?i.getVideoTracks()[0]:void 0;if(!r.paused&&n.currentTimeOfLastCheckMap.get(r)===r.currentTime&&"video"===n.mediaKind&&!0!==(null==o?void 0:o.muted))return qe.error("".concat(t,": tag=").concat(r.tagName," label=").concat(Ke(r),", currentTime Stop, doc.visibilityState=").concat(document.visibilityState,", curTime=").concat(r.currentTime,", mediaStream="),e.getPlainMediaStreamInfo(i)),void("visible"===document.visibilityState&&Ne(i)&&r.load());n.currentTimeOfLastCheckMap.set(r,r.currentTime)}})}}),Object.defineProperty(this,"_tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible",{enumerable:!0,configurable:!0,writable:!0,value:function(){n._tryReloadOnPauseAndErrorWhenVisible("visibilityChange")}}),Object.defineProperty(this,"_elementDefaultErrorHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="error event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject),a=null==r?void 0:r.error;qe.error(i,o,a)}}),Object.defineProperty(this,"_elementDefaultPauseHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="pause event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject),a=null==r?void 0:r.error;qe.debug(i,o,a)}}),Object.defineProperty(this,"_elementDefaultPlayHandler",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r=t.target,i="play event on ".concat(n.mediaKind," playback, mediaStream="),o=e.getPlainMediaStreamInfo(null==r?void 0:r.srcObject);qe.debug(i,o)}}),Object.defineProperty(this,"_onUserInteraction",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=[].concat(te(n.mediaElementPool),te(n.mediaElementsInUse));if(!n.hasActivated){n.hasActivated=!0;var r="".concat(n.mediaKind," good! media elements activated by click");if(qe.debug(r),t.forEach(function(e){e.load()}),qe.info("load all for activate"),n._activatedListener)try{n._activatedListener()}catch(t){qe.error("error occurred when exec activatedListener",e.tryJsonStringify(t))}else qe.debug("ignore activatedListener for there is no one")}n._tryReloadOnPauseAndErrorWhenVisible("userInteract")}}),qe.debug("build ".concat(r," pool size"),i),this.mediaElementCount=i,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(We,Ye):null===(r=e.target)||void 0===r||r.setAttribute(We,Je)})}));for(var a=1;a<=i;a++){var s=this._createElement("".concat(r,"-").concat(a));this.mediaElementPool.push(s),this.allElements.add(s)}document.addEventListener("click",this._onUserInteraction,!0),document.addEventListener("touchstart",this._onUserInteraction,!0),document.addEventListener("visibilitychange",this._tryReloadOnPauseAndErrorWhenVisibleTriggerByVisible,!0),this.mediaPlaybackCheckInterval=e.addTimer(function(){n.hasActivated&&n._tryReloadOnPauseAndErrorWhenVisible("intervalCheck")},4e3,"interval")},[{key:"addAtttribute",value:function(e){if(e.autoplay=!0,e.setAttribute(ce,"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())?qe.info("".concat(this.mediaKind," pop label=").concat(Ke(t)," for ").concat(e)):(t=this._createElement("".concat(this.mediaKind,"-").concat(++this.mediaElementCount)),qe.info("".concat(this.mediaKind," create new videoEl for no more video element in pool"))),this.mediaElementsInUse.push(t),this._resetMediaElement(t),t.addEventListener("error",this._elementDefaultErrorHandler),t.addEventListener("pause",this._elementDefaultPauseHandler),t.addEventListener("play",this._elementDefaultPlayHandler),t.rtcPurpose=e||"",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&&(qe.debug("".concat(this.mediaKind," pushed"),Ke(e)),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(e){var t,r=document.createElement(this.mediaKind);return null===(t=this.observer)||void 0===t||t.observe(r),this.addAtttribute(r),r.setAttribute(ce,e),r}},{key:"_resetMediaElement",value:function(e){Qe.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}}])}(),$e=function(){return Ce||et(),Ce},Xe=function(){return _e||et(),_e};window.getAudioElementPool=$e,window.getVideoElementPool=Xe;var Ze=e.Environment.isIOS()||e.Environment.isAndroid()?9:25,et=function(){Ce||(Ce=new ze("audio",2)),_e||(_e=new ze("video",Ze))},tt=e.getReporter().getLoggerWithPrefix("[rtc-actx]"),rt=null,it=function(){if(rt||(rt=new AudioContext),"running"!==rt.state){var e=setTimeout(function(){var e="timeout for resume audioContext, probably page still has no user gesture like click or touch";console.error(e),tt.error(e)},2e3);rt.resume().finally(function(){clearTimeout(e)})}return rt},nt=function(e){var t=e.getAudioTracks(),r=it().createMediaStreamDestination();return t.forEach(function(e){it().createMediaStreamSource(new MediaStream([e])).connect(r)}),r.stream.getAudioTracks()[0]},ot=function(e,t){t.connect(e),e.fftSize=2048,e.smoothingTimeConstant=.4;var r=new Float32Array(e.fftSize);if(e.getFloatTimeDomainData)e.getFloatTimeDomainData(r);else{var i=new Uint8Array(e.fftSize);e.getByteTimeDomainData(i);for(var n=0;n<r.length;++n)r[n]=i[n]/128-1}for(var o=0,a=0;a<r.length;a++)o+=r[a]*r[a];return Math.max(10*Math.log10(o/r.length)+100,0)/100},at=function(e){var t=document.createElement("canvas"),r=t.getContext("2d"),i=e.videoHeight,n=e.videoWidth;return t.width=n,t.height=i,r.drawImage(e,0,0,n,i),t.toDataURL("image/png")},st=$e(),ct=Xe(),ut=e.getReporter().getLoggerWithPrefix("[rtc-playerMgr]"),dt=u(function t(r,i,n,a){var s=this;o(this,t),Object.defineProperty(this,"mediaEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"playerConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"mediaWrapperEl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"track",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotMediaStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"snapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"checkSwitchSnapshotInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lastCheckResult",{enumerable:!0,configurable:!0,writable:!0,value:{msTrackPlayable:!1,elPlaying:!1}}),Object.defineProperty(this,"isPlayerPlaying",{enumerable:!0,configurable:!0,writable:!0,value:function(){return s.mediaEl&&s.mediaEl.currentTime>0&&!s.mediaEl.paused&&!s.mediaEl.ended&&s.mediaEl.readyState>=2}}),Object.defineProperty(this,"snapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r=s.track.getMediaStreamTrack(),i="live"===(null==r?void 0:r.readyState)&&(null==r?void 0:r.enabled)&&!(null!=r&&r.muted);if(be._holdVideoLastFrame&&(i&&(null===(e=s.mediaEl)||void 0===e||null===(e=e.srcObject)||void 0===e||null===(t=e.getVideoTracks)||void 0===t||null===(t=t.call(e))||void 0===t?void 0:t[0])===r)){var n=s.canvas.getContext("2d");n.clearRect(0,0,s.canvas.width,s.canvas.height);var o=s.mediaEl.videoHeight,a=s.mediaEl.videoWidth;s.canvas.width===a&&s.canvas.height===o||(s.canvas.width=a,s.canvas.height=o),n.drawImage(s.mediaEl,0,0,a,o)}}}),Object.defineProperty(this,"checkSwitchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,i,n,o,a=s.track.getMediaStreamTrack(),c="live"===(null==a?void 0:a.readyState)&&(null==a?void 0:a.enabled)&&!(null!=a&&a.muted);c===s.lastCheckResult.msTrackPlayable&&s.isPlayerPlaying()===s.lastCheckResult.elPlaying||ut.info("rtcTrackId=".concat(s.track.getTrackId()," play change trackPlayable=").concat(c," isPlaying=").concat(s.isPlayerPlaying()),{msTrackReadyState:null==a?void 0:a.readyState,msTrackEnabled:null==a?void 0:a.enabled,msTrackMuted:null==a?void 0:a.muted,elCurrentTime:null===(e=s.mediaEl)||void 0===e?void 0:e.currentTime,elPaused:null===(t=s.mediaEl)||void 0===t?void 0:t.paused,elEnded:null===(r=s.mediaEl)||void 0===r?void 0:r.ended,elReadyState:null===(i=s.mediaEl)||void 0===i?void 0:i.readyState});(s.lastCheckResult={msTrackPlayable:c,elPlaying:s.isPlayerPlaying()},be._holdVideoLastFrame)&&(c&&(null===(n=s.mediaEl)||void 0===n||null===(n=n.srcObject)||void 0===n||null===(o=n.getVideoTracks)||void 0===o||null===(o=o.call(n))||void 0===o?void 0:o[0])!==a?s.switchOriginVideo():c||s.mediaEl.srcObject===s.snapshotMediaStream||s.switchSnapshot())}}),Object.defineProperty(this,"startCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){"video"===s.track.trackMediaType&&(ut.info("startCheckPlayState trackid=",s.track.getTrackId()),s.snapshotInterval=setInterval(s.snapshot,300),s.checkSwitchSnapshotInterval=setInterval(s.checkSwitchSnapshot,150))}}),Object.defineProperty(this,"stopCheckPlayState",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;ut.info("stopCheckPlayState trackid=",null===(e=s.track)||void 0===e||null===(t=e.getTrackId)||void 0===t?void 0:t.call(e)),clearInterval(s.snapshotInterval),clearInterval(s.checkSwitchSnapshotInterval)}}),Object.defineProperty(this,"playVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t;ut.info("playVideo",s.track.getTrackId(),null===(t=s.mediaWrapperEl)||void 0===t?void 0:t.getAttribute(pe)),s.mediaWrapperEl.appendChild(s.mediaEl),s.mediaEl.pause();var r=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=r,s.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play video error trackid=",null===(r=s.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))}),s.stopCheckPlayState(),s.startCheckPlayState()}}),Object.defineProperty(this,"playAudio",{enumerable:!0,configurable:!0,writable:!0,value:function(){var t=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=t,s.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play audio error trackid=",null===(r=s.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))}),s.stopCheckPlayState(),s.startCheckPlayState()}}),Object.defineProperty(this,"stopPlay",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;if(ut.info("stopPlay",s.track.getTrackId(),null===(e=s.mediaWrapperEl)||void 0===e?void 0:e.getAttribute(pe)),s.stopCheckPlayState(),s.mediaEl&&s.track){var r,i;if(s.mediaEl.pause(),null!==(t=s.mediaWrapperEl)&&void 0!==t&&t.contains(s.mediaEl))null===(r=s.mediaWrapperEl)||void 0===r||null===(i=r.removeChild)||void 0===i||i.call(r,s.mediaEl);s.mediaEl.srcObject=null,s.canvas=null,"audio"===s.track.trackMediaType?st.pushElement(s.mediaEl):ct.pushElement(s.mediaEl)}}}),Object.defineProperty(this,"switchSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:function(){ut.info("switchSnapshot trackid",s.track.getTrackId()),s.mediaEl.srcObject=s.snapshotMediaStream,s.mediaEl.play().catch(function(t){ut.info("snapshot play error, trackid",s.track.getTrackId(),e.tryJsonStringify(t))})}}),Object.defineProperty(this,"switchOriginVideo",{enumerable:!0,configurable:!0,writable:!0,value:function(){setTimeout(function(){var t,r,i=s.track.getMediaStreamTrack();if("live"===(null==i?void 0:i.readyState)&&(null==i?void 0:i.enabled)&&!(null!=i&&i.muted)&&(null===(t=s.mediaEl)||void 0===t||null===(t=t.srcObject)||void 0===t||null===(r=t.getVideoTracks)||void 0===r||null===(r=r.call(t))||void 0===r?void 0:r[0])!==i){ut.info("switchOriginVideo trackid",s.track.getTrackId());var n=s.track.sfuStream||new MediaStream([s.track.getMediaStreamTrack()]);s.mediaEl.srcObject=n,s.mediaEl.play().catch(function(t){ut.info("switchOriginVideo play error, trackid",s.track.getTrackId(),e.tryJsonStringify(t))})}},1e3)}}),this.mediaWrapperEl=a,this.mediaWrapperEl&&!this.mediaWrapperEl.getAttribute(pe)&&this.mediaWrapperEl.setAttribute(pe,"container_".concat(t.containerRtcLabelAcc++)),this.track=r,this.playerConfig=i,this.mediaEl=n,this.mediaEl.setAttribute(le,this.track.getTrackId()),this.canvas=document.createElement("canvas"),this.canvas.setAttribute(le,this.track.getTrackId()),this.snapshotMediaStream=this.canvas.captureStream(4)});Object.defineProperty(dt,"containerRtcLabelAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var lt=new(function(){return u(function e(){o(this,e),Object.defineProperty(this,"playControllerArr",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.playControllerArr=[]},[{key:"getElement",value:function(e){return this.playControllerArr.filter(function(t){var r;return(null===(r=t.track)||void 0===r?void 0:r.getTrackId())===e.getTrackId()}).map(function(e){return e.mediaEl})}},{key:"getPlayCtrls",value:function(e){return this.playControllerArr.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,i){var n,o=this;ut.info("call play",t.getTrackId(),r instanceof HTMLElement?r.tagName:r,i);var 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=i||{},l=d.mirror,p=d.fit;if((n=this.playControllerArr.find(function(e){return e.mediaWrapperEl===u}))&&(null===(c=n.track)||void 0===c?void 0:c.getTrackId())!==(null==t?void 0:t.getTrackId()))return this.stopPlay(n.track,r),void this.play(t,r,i);if(n)n.mediaEl.pause(),!t.sourceMirror!=!l?n.mediaEl.style.transform="scaleX(-1)":n.mediaEl.style.transform="",p&&(n.mediaEl.style.objectFit=p),n.mediaEl.srcObject=s,n.mediaEl.play().catch(function(t){var r,i;"AbortError"!==t.name&&ut.error("play video error trackid=",null===(r=n.track)||void 0===r||null===(i=r.getTrackId)||void 0===i?void 0:i.call(r),e.tryJsonStringify(t))});else{var f,v=null===(f=this.getPlayCtrls(t))||void 0===f?void 0:f.length;if(v>3){var m,h=["DingRTC WARN: possible memory leak. More than 3 HTMLElement containers are playing the same track.","Please call track.stop to stop playing HTMLElements that will unmount in DOM.","TrackId:",t.getTrackId()];(m=console).warn.apply(m,h),ut.info.apply(ut,h.concat([v]))}(function(e,t){if(e.style.width="100%",e.style.height="100%",t){var r=t.mirror,i=t.fit;!0===r&&(e.style.transform="scaleX(-1)"),i&&(e.style.objectFit=i)}})((n=new dt(t,i,Xe().popElement(),u)).mediaEl,{mirror:!t.sourceMirror!=!l,fit:p}),n.playVideo(),this.playControllerArr.push(n)}}else(n=this.playControllerArr.find(function(e){var r;return(null===(r=e.track)||void 0===r?void 0:r.getTrackId())===t.getTrackId()}))?(n.mediaEl.pause(),n.mediaEl.srcObject=s,ut.info("element loaded",t.getTrackId()),n.mediaEl.load()):((n=new dt(t,null,$e().popElement(),null)).playAudio(),this.playControllerArr.push(n));n.mediaEl.paused&&n.mediaEl.play().catch(function(t){"NotAllowedError"===t.name?(ut.error("autoplay failed",e.tryJsonStringify(t)),e.EventBus.emit("autoplay-failed",o)):"AbortError"!==t.name&&ut.warn("".concat(a," play error"),e.tryJsonStringify(t))})}},{key:"isPlaying",value:function(e){return this.playControllerArr.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.isPlayerPlaying()})}},{key:"stopPlay",value:function(e,t){var r;ut.info("call stop play",e.getTrackId());var i=this.findDom(t),n=this.playControllerArr.filter(function(r){var n;return(null===(n=r.track)||void 0===n?void 0:n.getTrackId())===(null==e?void 0:e.getTrackId())&&(!t||r.mediaWrapperEl===i)});if(n.length){n.forEach(function(e){e.stopPlay()});var o=this.playControllerArr.filter(function(e){return!n.includes(e)});(r=this.playControllerArr).splice.apply(r,[0,this.playControllerArr.length].concat(te(o)))}}},{key:"findDom",value:function(e){if(!e)return null;var t="string"==typeof e?document.querySelector(e):e;return document.contains(t)?t:null}}])}()),pt=function(){return lt};function ft(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ft=function(){return!!e})()}window.playerMgr=lt;var vt=e.getReporter(),mt=vt.trace,ht=vt.getLoggerWithPrefix("[rtc-track]"),gt=ht,bt=pt(),yt=function(){function t(r,i){var n,a,s,c;return o(this,t),a=this,s=l(s=t),n=d(a,ft()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(n,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"logger",{enumerable:!0,configurable:!0,writable:!0,value:mt}),Object.defineProperty(n,"sourceNode",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"analyser",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackSettings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sfuStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"mediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"trackId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"sourceMirror",{enumerable:!0,configurable:!0,writable:!0,value:!1}),r?(n.trackMediaType=r.kind,n.trackSettings=r.getSettings()):i&&(n.trackMediaType="audio"),"audio"===n.trackMediaType&&(n.analyser=it().createAnalyser()),n.trackId="".concat(n.trackMediaType,"_").concat(e.createUuid(6)),n.setMediaStreamTrack(r,i),n}return f(t,e.EventEmitter),u(t,[{key:"isPlaying",get:function(){return bt.isPlaying(this)}},{key:"emit",value:function(e){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return ht.info("track emit event",e,null==i?void 0:i[0]),(o="emit",a=this,s=3,c=re(l(t.prototype),o,a),2&s&&"function"==typeof c?function(e){return c.apply(a,e)}:c)([e].concat(i));var o,a,s,c}},{key:"getTrackId",value:function(){return this.trackId}},{key:"setMediaStreamTrack",value:function(t,r){var i=this,n=this.mediaStreamTrack;if(n&&(n.onended=null),t||r){var o;if(n&&t&&(t.enabled=n.enabled),"audio"===this.trackMediaType)if(this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),t)this.sourceNode=null===(o=it())||void 0===o?void 0:o.createMediaStreamSource(new MediaStream([t]));else if(r){var a,s=nt(r);this.sourceNode=null===(a=it())||void 0===a?void 0:a.createMediaStreamSource(new MediaStream([s]))}t?(this.mediaStreamTrack=t,this.mediaStreamTrack.onended=function(){i.source===exports.VideoSourceInfo.SCREENCAST?i.logger.sendEvent("SCREEN_DEVICE_STOP"):i.source===exports.AudioSourceInfo.MIC?new e.DingRTCError(e.ErrorCode.MicInterrupt):i.source===exports.VideoSourceInfo.CAMERA&&new e.DingRTCError(e.ErrorCode.CameraInterrupt)}):r&&(this.sfuStream=r)}}},{key:"replaceTrack",value:function(e,t){gt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0)}},{key:"replaceTrackInner",value:function(e,t,r){this.setMediaStreamTrack(e,t),this.emit(de,"replace",this),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){console.error("The API stop is deprecated. Use stopPlay to stop playing or use close to destroy mediaStream track"),gt.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),bt.stopPlay(this,e)}},{key:"stopPlay",value:function(e){gt.info("stop play track ".concat(this.getTrackId()),e instanceof HTMLElement?e.tagName:e),bt.stopPlay(this,e)}},{key:"innnerPlay",value:function(e){var t=this,r=e.mediaWrapperElement,i=e.config;e.updated?bt.getPlayCtrls(this).forEach(function(e){e.mediaWrapperEl?bt.findDom(e.mediaWrapperEl)?bt.play(t,e.mediaWrapperEl,e.playerConfig):bt.stopPlay(t,e.mediaWrapperEl):bt.play(t,e.mediaWrapperEl,e.playerConfig)}):bt.play(this,r,i);if("audio"===this.trackMediaType){var n=it();"running"!==n.state&>.error("audioContext not running",n.state)}}},{key:"getMediaStreamTrack",value:function(){return this.mediaStreamTrack}}])}();function kt(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 i,n,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=(i=o.call(r)).done)&&(s.push(i.value),s.length!==t);c=!0);}catch(e){u=!0,n=e}finally{try{if(!c&&null!=r.return&&(a=r.return(),Object(a)!==a))return}finally{if(u)throw n}}return s}}(e,t)||ee(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var St,Pt=function(e){return e.width>1920&&e.height>1080},Tt=function(e){var t;if(!e)return be.simulcast;var r=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),i=(null==r?void 0:r.width)||e.trackSettings.width,n=(null==r?void 0:r.height)||e.trackSettings.height;return be.simulcast&&e.source===exports.VideoSourceInfo.CAMERA&&!Pt({width:i,height:n})};function wt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Et(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?wt(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}!function(e){e[e.LLD=0]="LLD",e[e.LD=1]="LD",e[e.SD=2]="SD",e[e.HD=3]="HD",e[e.FHD=4]="FHD",e[e.QHD=5]="QHD"}(St||(St={}));var It=X(X(X(X(X(X({},St.LLD,"lld"),St.LD,"ld"),St.SD,"sd"),St.HD,"hd"),St.FHD,"fhd"),St.QHD,"qhd"),Mt={high:[2764800,4915200],QHD:[2764800,4915200],FHD:[1228800,2764800],HD:[307200,1228800],SD:[76800,307200],LD:[0,76800],low:[0,76800]},Ot=function(e,t){var r=At(e,t),i=function(e,t){var r={high:z.QHD,low:z.LD,QHD:z.QHD,FHD:z.FHD,HD:z.HD,SD:z.SD,LD:z.LD},i=r[e]||z.None,n=Mt[e],o=t[t.length-1].width*t[t.length-1].height;if(o<n[0]){var a=Object.entries(Mt).find(function(e){var t=kt(e,2);t[0];var r=t[1];return o>r[0]&&o<=r[1]});i=r[kt(a,1)[0]]}return i}(e,t);return{resolution:r,resolutionLevel:i}},Rt=function(e){return{0:"LLD",1:"LD",2:"LD",4:"SD",8:"HD",16:"FHD",32:"QHD"}[e]},At=function(e,t){var r=Mt[e],i=t.length,n=t[t.length-1];if(("FHD"===e||"high"===e)&&Pt(n))return n;if(t[0].width*t[0].height>Mt.FHD[1])return t[0];for(var o=0;i>o;o++){var a=t[o].width*t[o].height;if(a>=r[0]&&r[1]>=a)return t[o]}for(var s=i-1;s>=0;s--){var c=t[s].width*t[s].height;if(r[1]>c)return t[s]}return t[0]},xt=[49152,76800,307200,1228800,2764800,4915200],Ct=[200,350,1e3,1800,2828,5600],_t=[[256,144],[320,180],[640,360],[1280,720],[1920,1080],[2560,1440]],Dt=[[256,192],[320,240],[640,480],[1280,960],[1920,1440],[2560,1920]],jt=function(e,t){var r=St.FHD,i=e*t;return i<=xt[St.LLD]?r=St.LLD:i<=xt[St.LD]?r=St.LD:i<=xt[St.SD]?r=St.SD:i<=xt[St.HD]?r=St.HD:i<=xt[St.FHD]?r=St.FHD:i<=xt[St.QHD]&&(r=St.QHD),r},Lt=function(e,t,r,i){var n=0,o=0;if(i<=r)return[n=e,o=t];if(t>e){var a=[e,t];t=a[0],e=a[1]}if(16*t==9*e)n=_t[r][0],o=_t[r][1];else if(4*t==3*e)n=Dt[r][0],o=Dt[r][1];else{var s=Math.sqrt(1*_t[r][0]*_t[r][1]/e/t);s=1*(n=(n=Math.round(e*s))+15&-16)/e,o=Math.round(t*s)}return[n,o]},Nt=function(e,t,r){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!i){var n=1;30!==r&&(n=Math.sqrt(r/30));var o=Ct[jt(e,t)];i=Math.round(Math.max(n*o,50))}return i},Vt=function(e){var t=e.width,r=e.height,i=e.frameRate,n=e.maxBitrate,o=e.resolutionLevel,a=jt(t,r),s=[],c=a>=St.HD?3:2,u=function(e){var o=kt(Lt(t,r,e,a),2),s=o[0],c=o[1],u=Ct[e]/Ct[a],d=1/(c/r);return{targetWidth:s,rid:It[e],targetHeight:c,minBitrate:50,maxFramerate:i,maxBitrate:Math.round(Math.max(30,n*u)),scaleResolutionDownBy:d}};a>St.LLD&&s.push(Et({activeForBitrateMap:!1,activeForRealuse:Math.pow(2,St.LLD)===o},u(St.LLD))),a>St.LD&&s.push(Et({activeForBitrateMap:c>1,activeForRealuse:Math.pow(2,St.LD)===o},u(St.LD))),a>St.SD&&s.push(Et({activeForBitrateMap:c>2,activeForRealuse:Math.pow(2,St.SD)===o},u(St.SD))),a===St.FHD?(s.push(Et({activeForBitrateMap:!1,activeForRealuse:!1},u(St.HD))),s.push(Et({activeForBitrateMap:!0,activeForRealuse:be.republish?Math.pow(2,4)===o||o===Math.pow(2,3):Math.pow(2,4)===o},u(St.FHD)))):s.push(Et({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},Ft=function(e,t){var r=jt(e,t);return Math.pow(2,r)},Ut=function(e){var t,r=e.getMaxBitrate(),i=null===(t=e.getMediaStreamTrack())||void 0===t?void 0:t.getSettings(),n=(null==i?void 0:i.width)||e.trackSettings.width,o=(null==i?void 0:i.height)||e.trackSettings.height,a=(null==i?void 0:i.frameRate)||e.trackSettings.frameRate,s=!Tt(e),c={resolutionLevel:Ft(n,o),encodings:[]};return s?c.encodings=[{maxFramerate:a,maxBitrate:r,scaleResolutionDownBy:1,activeForBitrateMap:!0,activeForRealuse:!0,rid:"",minBitrate:Math.round((r+30)/2),targetWidth:n,targetHeight:o}]:be.republish?c.encodings=Vt({width:1920,height:1080,frameRate:30,maxBitrate:Nt(1920,1080,30),resolutionLevel:c.resolutionLevel}):c.encodings=Vt({width:n,height:o,frameRate:a,maxBitrate:r,resolutionLevel:c.resolutionLevel}),c};function Gt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Bt(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Gt(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Gt(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ht(e,t,r){return t=l(t),d(e,qt()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function qt(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(qt=function(){return!!e})()}function Wt(e,t,r,i){var n=re(l(e.prototype),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}var Yt=pt(),Jt=e.getReporter().getLoggerWithPrefix("[rtc-localtrack]"),Qt=function(){function t(e){var r;if(o(this,t),r=Ht(this,t,[e]),Object.defineProperty(r,"muted",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"maxBitrate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"isClosed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),e){var i=e.muted;r.muted=i}return r.enabled=!0,r}return f(t,yt),u(t,[{key:"setMediaStreamTrack",value:function(e){var r=this;Wt(t,"setMediaStreamTrack",this,3)([e]),e&&(this.trackSettings=e.getSettings(),e.onended=function(){r.stopPlay(),r.close&&setTimeout(function(){return r.close()},200),r.emit("track-ended")})}},{key:"play",value:function(e,t){Jt.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,t),this.innnerPlay({mediaWrapperElement:e,config:t})}},{key:"setEnabled",value:function(t){var r,i=this;return Jt.info("setEnabled",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.enabled=t,t?this.updateNewTrack().then(function(e){return i.emit(de,"unmute"),e}):(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"),this.emit(de,"mute"),Promise.resolve()))}},{key:"close",value:function(){var e;Jt.info("".concat(this.source," track:").concat(this.getTrackId()," close")),this.isClosed||(this.isClosed=!0,this.isPlaying&&this.stopPlay(),this.emit(de,"stop",this),null===(e=this.mediaStreamTrack)||void 0===e||e.stop(),this.setMediaStreamTrack(null),this.sourceNode=null,this.analyser=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 Jt.info("setMuted",t),this.isClosed?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState)):(this.muted=t,this.mediaStreamTrack.enabled=!t,this.emit(de,t?"mute":"unmute"),Promise.resolve())}},{key:"getAudioTrack",value:function(){var t=this;return Jt.debug("gengrate new audioTrack"),new Promise(function(r,i){var n;Le({audio:Bt({source:t.source},t.config)}).then(function(e){n=e.getAudioTracks()[0]}).catch(function(t){try{var r=it().createOscillator(),o=it().createMediaStreamDestination();r.connect(o),n=o.stream.getAudioTracks()[0]}catch(r){Jt.error("gengrate new audioTrack error",e.parseAudioDeviceError(t)),i(e.parseAudioDeviceError(t))}}).finally(function(){n&&r(n)})})}},{key:"getVideoTrack",value:function(){var t=this;return Jt.info("gengrate new videoTrack",this.config),new Promise(function(r,i){var n,o=Bt({source:t.source},t.config);t.config.facingMode&&t.config.deviceId&&(Jt.info("ignore deviceId param to create videoTrack because facingMode is",t.config.facingMode),delete o.deviceId),Le({video:o,audio:!1}).then(function(e){n=e.getVideoTracks()[0],r(n)}).catch(function(t){Jt.error("gengrate new videoTrack error",e.parseVideoDeviceError(t)),i(e.parseVideoDeviceError(t))})})}},{key:"updateNewTrack",value:function(){var e=this,t=this.getMediaStreamTrack();return t.onended=null,Jt.info("stop oldTrack first"),t.stop(),"audio"===this.trackMediaType?this.getAudioTrack().then(function(t){return e.replaceTrackInner(t,null,!0),e.emit(de,"localMixedAudioReplaceTrack",e)}):"video"===this.trackMediaType?this.getVideoTrack().then(function(t){return e.replaceTrackInner(t,null,!0)}):void 0}},{key:"setDevice",value:(r=n($.mark(function e(t){var r,i,n;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(Jt.info("setDevice",t),!this.isClosed){e.next=1;break}return e.abrupt("return");case 1:if(!(this instanceof $t)||"user"!==t&&"environment"!==t){e.next=2;break}this.config.facingMode=t,e.next=4;break;case 2:if((this.config.deviceId||(null===(r=this.mediaStreamTrack)||void 0===r||null===(r=r.getSettings())||void 0===r?void 0:r.deviceId)||(null===(i=this.mediaStreamTrack)||void 0===i||null===(n=i.getConstraints)||void 0===n||null===(n=n.call(i))||void 0===n?void 0:n.deviceId))!==t){e.next=3;break}return e.abrupt("return");case 3:this.config.deviceId=t;case 4:return e.abrupt("return",this.updateNewTrack());case 5:case"end":return e.stop()}},e,this)})),function(e){return r.apply(this,arguments)})},{key:"getTrackLabel",value:function(){if(Jt.info("getTrackLabel"),!this.isClosed)return this.mediaStreamTrack.label}},{key:"getMaxBitrate",value:function(){if(!this.isClosed)return this.maxBitrate}}]);var r}(),Kt=function(){function t(e,r){var i;if(o(this,t),(i=Ht(this,t,[e])).config=r,e){var n=e.getSettings(),a=n.width,s=n.height;i.maxBitrate=Nt(a,s,r.frameRate,r.maxBitrate)}return i}return f(t,Qt),u(t,[{key:"optimizationMode",get:function(){return this.config.optimizationMode}},{key:"setEncoderConfiguration",value:(r=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f,v,m,h;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(Jt.info("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration"),r),i=r.dimension,n=r.frameRate,o=r.maxBitrate,a=r.optimizationMode,s=r.mirror,!n||!Number.isNaN(n)){t.next=1;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid frameRate")));case 1:if(!i||oe[i]){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"invalid dimension")));case 2:if(!s!=!this.config.mirror&&(this.emit(de,"mirror",s),this.config.mirror=s),a&&a!==this.optimizationMode&&(this.config.optimizationMode=a,this.emit(de,"optimizationMode")),c=!1,i&&this.config.dimension!==i&&(this.config.dimension=i,c=!0),n&&this.config.frameRate!==Math.min(30,n)&&(this.config.frameRate=Math.min(30,n),c=!0),o&&this.maxBitrate!==o&&(c=!0),c){t.next=3;break}return t.abrupt("return",Promise.resolve());case 3:return u=Bt({frameRate:this.config.frameRate},De(this.config.dimension)),d=this.getMediaStreamTrack(),t.prev=4,t.next=5,null==d?void 0:d.applyConstraints(u);case 5:p=null===(l=this.getMediaStreamTrack())||void 0===l?void 0:l.getSettings(),f=p.width,v=p.height,this.maxBitrate=Nt(f,v,this.config.frameRate,o),Jt.info("after applyConstraints",u,this.maxBitrate,e.getPlainMediaTrackInfo(d)),this.emit(de,"republish",this),t.next=7;break;case 6:throw t.prev=6,h=t.catch(4),m=e.parseVideoDeviceError(h),Jt.error("videoTrack ".concat(this.getTrackId()," setEncoderConfiguration error"),m),m;case 7:case"end":return t.stop()}},t,this,[[4,6]])})),function(e){return r.apply(this,arguments)})},{key:"getCurrentFrameData",value:function(){return Jt.info("getCurrentFrameData"),this.isClosed||!this.isPlaying?null:at(Yt.getElement(this)[0])}},{key:"play",value:function(e,r){return Jt.info("play track ".concat(this.getTrackId()),(null==e?void 0:e.tagName)||e,r),Wt(t,"play",this,3)([e,r])}}]);var r}(),zt=function(){function e(t){return o(this,e),Ht(this,e,[t])}return f(e,Qt),u(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Yt.getElement(this)[0]&&(Yt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Yt.getElement(this)[0]?Yt.getElement(this)[0].volume:void 0}},{key:"getVolumeLevel",value:function(){return this.isClosed?0:ot(this.analyser,this.sourceNode)}},{key:"play",value:function(){return Jt.info("local audio play"),Wt(e,"play",this,3)([])}},{key:"replaceTrack",value:function(e,t){Jt.info("replaceTrack",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(e,null,!0),this.emit(de,"localMixedAudioReplaceTrack",this)}}])}(),$t=function(){function e(t,r){var i;return o(this,e),(i=Ht(this,e,[t,r])).setSource(exports.VideoSourceInfo.CAMERA),i}return f(e,Kt),u(e)}(),Xt=function(){function e(t,r){var i;return o(this,e),(i=Ht(this,e,[t])).config=r,i.setSource(exports.AudioSourceInfo.MIC),i.analyser=it().createAnalyser(),i}return f(e,zt),u(e,[{key:"setVolume",value:function(e){Jt.info("setVolume",e),this.isClosed||Yt.getElement(this)[0]&&(Yt.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(Jt.info("getVolume"),!this.isClosed)return Yt.getElement(this)[0]?Yt.getElement(this)[0].volume:void 0}}])}(),Zt=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createMicrophoneAudioTrack",r),i={AEC:!0,AGC:!0,ANS:!0},o=(n=r||i).AEC,a=void 0===o||o,s=n.AGC,c=void 0===s||s,u=n.ANS,d=void 0===u||u,t.prev=1,t.next=2,Le({video:!1,audio:{deviceId:null==r?void 0:r.deviceId,source:exports.AudioSourceInfo.MIC,AEC:a,AGC:c,ANS:d}});case 2:return l=t.sent,p=l.getAudioTracks()[0],Jt.info("MicrophoneAudioTrack created",e.getPlainMediaTrackInfo(p)),t.abrupt("return",new Xt(p,Object.assign({},r,{AEC:a,AGC:c,ANS:d})));case 3:throw t.prev=3,f=t.catch(1),e.parseAudioDeviceError(f);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e){return t.apply(this,arguments)}}(),er=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createCameraVideoTrack",r),i=r.deviceId,n=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=1,t.next=2,Le({video:{deviceId:i,source:exports.VideoSourceInfo.CAMERA,frameRate:u,dimension:a,facingMode:n},audio:!1});case 2:return d=t.sent,l=d.getVideoTracks()[0],Jt.info("CameraVideoTrack created",e.getPlainMediaTrackInfo(l)),l.addEventListener("ended",function(){return Jt.info("cam track ended",l.id)}),l.addEventListener("unmute",function(){return Jt.info("cam track unmute",l.id)}),l.addEventListener("mute",function(){return Jt.info("cam track mute",l.id)}),t.abrupt("return",new $t(l,Object.assign({},r,{frameRate:u,dimension:a,optimizationMode:c})));case 3:throw t.prev=3,p=t.catch(1),e.parseVideoDeviceError(p);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e){return t.apply(this,arguments)}}(),tr=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return Jt.info("createScreenVideoTrack config",t),e.abrupt("return",rr(t,"noAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),rr=function(){var t=n($.mark(function t(r,i){var n,o,a,s,c,u,d,l,p,f,v,m,h,g;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("_createScreenVideoTrack",r,i),n=r.displaySurface,o=void 0===n?"monitor":n,a=r.dimension,s=void 0===a?"VD_1920x1080":a,c=r.optimizationMode,u=void 0===c?"detail":c,d=Math.min(r.frameRate||5,30),t.prev=1,t.next=2,Le({video:{source:exports.VideoSourceInfo.SCREENCAST,displaySurface:o,frameRate:d,dimension:s},audio:"withAudio"===i});case 2:return l=t.sent,f=l.getVideoTracks()[0],Jt.info("ScreenVideoTrack created",e.getPlainMediaTrackInfo(f)),f.addEventListener("ended",function(){return Jt.info("screen video track ended",f.id)}),f.addEventListener("unmute",function(){return Jt.info("screen video track unmute",f.id)}),f.addEventListener("mute",function(){return Jt.info("screen video track mute",f.id)}),(v=new Kt(f,Object.assign({},r,{frameRate:d,dimension:s,optimizationMode:u}))).setSource(exports.VideoSourceInfo.SCREENCAST),(h=null===(p=l.getAudioTracks())||void 0===p?void 0:p[0])&&((m=new zt(h)).setSource(exports.AudioSourceInfo.SCREENCAST),Jt.info("ScreenAudioTrack created",e.getPlainMediaTrackInfo(h)),h.addEventListener("ended",function(){return Jt.info("screen audio track ended",h.id)}),h.addEventListener("unmute",function(){return Jt.info("screen audio track unmute",h.id)}),h.addEventListener("mute",function(){return Jt.info("screen audio track mute",h.id)})),t.abrupt("return",m?[v,m]:[v]);case 3:throw t.prev=3,g=t.catch(1),e.parseScreenShareError(g);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e,r){return t.apply(this,arguments)}}(),ir=function(){var e=n($.mark(function e(t){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return Jt.info("createScreenVideoAndAudioTrack",t),e.abrupt("return",rr(t,"withAudio"));case 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),nr=function(){var t=n($.mark(function t(r,i){var n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return Jt.info("createMicrophoneAndCameraTracks",r,i),n=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=i||l).AEC,v=void 0===f||f,m=p.AGC,h=void 0===m||m,g=p.ANS,b=void 0===g||g,t.prev=1,t.next=2,Le({video:{deviceId:o,source:exports.VideoSourceInfo.CAMERA,frameRate:n,dimension:c,facingMode:a},audio:{deviceId:null==i?void 0:i.deviceId,source:exports.AudioSourceInfo.MIC,AEC:v,AGC:h,ANS:b}});case 2:return y=t.sent,k=y.getVideoTracks()[0],S=y.getAudioTracks()[0],Jt.info("CameraVideoTrack and MicrophoneTrack created",e.getPlainMediaStreamInfo(y)),k.addEventListener("ended",function(){return Jt.info("cam track ended",k.id)}),k.addEventListener("unmute",function(){return Jt.info("cam track unmute",k.id)}),k.addEventListener("mute",function(){return Jt.info("cam track mute",k.id)}),S.addEventListener("ended",function(){return Jt.info("mic track ended",S.id)}),S.addEventListener("unmute",function(){return Jt.info("mic track unmute",S.id)}),S.addEventListener("mute",function(){return Jt.info("mic track mute",S.id)}),P=new $t(k,Object.assign({},r,{frameRate:n,dimension:c,optimizationMode:d})),T=new Xt(S,Object.assign({},Object.assign({},i,{AEC:v,AGC:h,ANS:b}))),t.abrupt("return",[P,T]);case 3:throw t.prev=3,w=t.catch(1),e.parseVideoDeviceError(w);case 4:case"end":return t.stop()}},t,null,[[1,3]])}));return function(e,r){return t.apply(this,arguments)}}(),or=function(){var t=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=p.length>1&&void 0!==p[1]?p[1]:exports.VideoSourceInfo.CAMERA,Jt.info("createCustomVideoTrack",r,e.getPlainMediaTrackInfo(r.mediaStreamTrack)),o=(n=r||{}).mediaStreamTrack,a=n.dimension,s=void 0===a?"VD_640x480":a,c=n.optimizationMode,u=void 0===c?"balanced":c,d=Math.min(r.frameRate||15,30),o instanceof MediaStreamTrack&&"video"===o.kind){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing video mediaStreamTrack");case 1:return Jt.info("createCustomVideoTrack for",e.getPlainMediaTrackInfo(o)),o.addEventListener("ended",function(){return Jt.info("custom video track ended",o.id)}),o.addEventListener("unmute",function(){return Jt.info("custom video track unmute",o.id)}),o.addEventListener("mute",function(){return Jt.info("custom video track mute",o.id)}),(l=new Kt(o,Object.assign({},r,{frameRate:d,dimension:s,optimizationMode:u}))).setSource(i),t.abrupt("return",l);case 2:case"end":return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}(),ar=function(){var t=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=a.length>1&&void 0!==a[1]?a[1]:"mic",Jt.info("createCustomAudioTrack",r,i,e.getPlainMediaTrackInfo(r.mediaStreamTrack)),(n=(r||{}).mediaStreamTrack)instanceof MediaStreamTrack&&"audio"===n.kind){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"missing audio mediaStreamTrack");case 1:return Jt.info("createCustomAudioTrack succeed"),n.addEventListener("ended",function(){return Jt.info("custom audio track ended",n.id)}),n.addEventListener("unmute",function(){return Jt.info("custom audio track unmute",n.id)}),n.addEventListener("mute",function(){return Jt.info("custom audio track mute",n.id)}),(o=new zt(n)).setSource(i),t.abrupt("return",o);case 2:case"end":return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}();function sr(e,t,r,i){var n=re(l(e.prototype),t,r);return 2&i&&"function"==typeof n?function(e){return n.apply(r,e)}:n}function cr(e,t,r){return t=l(t),d(e,ur()?Reflect.construct(t,r||[],l(e).constructor):t.apply(e,r))}function ur(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ur=function(){return!!e})()}var dr,lr=e.getReporter().getLoggerWithPrefix("[rtc-remotetrack]"),pr=pt(),fr=function(){function e(t,r,i){var n;return o(this,e),n=cr(this,e,[t,i]),Object.defineProperty(n,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"subscription",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.userId=r,n}return f(e,yt),u(e,[{key:"getUserId",value:function(){return lr.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)}}])}(),vr=function(){function t(e,r,i){var n;return o(this,t),n=cr(this,t,[e,r,i]),Object.defineProperty(n,"deviceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n.deviceId="",n}return f(t,fr),u(t,[{key:"getMediaStreamTrack",value:function(){return be.audioSFU?nt(this.sfuStream):sr(t,"getMediaStreamTrack",this,3)([])}},{key:"replaceStream",value:function(e,t){lr.info("replaceRemote Audio",e,t),t&&this.isPlaying&&this.stopPlay(),this.replaceTrackInner(null,e)}},{key:"setVolume",value:function(e){lr.info("setVolume",e),pr.getElement(this)[0]&&(pr.getElement(this)[0].volume=e)}},{key:"getVolume",value:function(){if(lr.info("getVolume"),pr.getElement(this)[0])return pr.getElement(this)[0].volume}},{key:"setSpeaker",value:function(t){var r=this;return lr.info("setSpeaker",t),new Promise(function(i,n){var o,a=pr.getElement(r)[0];a||n(new e.DingRTCError(e.ErrorCode.InvaildState,"please playout audio first")),a.setSinkId||n(new e.DingRTCError(e.ErrorCode.SpeakerSetNotSupported)),null===(o=a.setSinkId)||void 0===o||o.call(a,t).then(function(){r.deviceId=t,i()}).catch(function(t){n(e.parseAudioDeviceError(t))})})}},{key:"getVolumeLevel",value:function(){return ot(this.analyser,this.sourceNode)}},{key:"play",value:function(){return lr.info("remote audio play"),sr(t,"innnerPlay",this,3)([{}])}}])}(),mr=function(){function e(t,r){return o(this,e),cr(this,e,[t,r])}return f(e,fr),u(e,[{key:"play",value:function(t,r){return lr.info("remote video play",this.getTrackId()),sr(e,"innnerPlay",this,3)([{mediaWrapperElement:t,config:r}])}},{key:"setSourceMirror",value:function(t){t!==this.sourceMirror&&(lr.info("remote video track set Mirror",t),this.sourceMirror=t,this.isPlaying&&sr(e,"innnerPlay",this,3)([{updated:!0}]))}},{key:"getCurrentFrameData",value:function(){return lr.info("getCurrentFrameData"),this.isPlaying?at(pr.getElement(this)[0]):null}}])}();!function(e){var t,r,i,n,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",(i=e.SyncResponseCode||(e.SyncResponseCode={}))[i.SYNC_OK=0]="SYNC_OK",i[i.SYNC_PART_SUC=10]="SYNC_PART_SUC",i[i.SYNC_DATA_SIZE_LIMITED=11]="SYNC_DATA_SIZE_LIMITED",i[i.SYNC_NOT_SUPPORT_TYPE=12]="SYNC_NOT_SUPPORT_TYPE",i[i.SYNC_NOT_FOUND=13]="SYNC_NOT_FOUND",i[i.SYNC_CHANNEL_NOT_EXIST=14]="SYNC_CHANNEL_NOT_EXIST",i[i.SYNC_INTERNAL_ERROR=15]="SYNC_INTERNAL_ERROR",(n=e.GroupUpdate||(e.GroupUpdate={}))[n.GROUP_UPDATE_AUDIO_STREAM_LOST=0]="GROUP_UPDATE_AUDIO_STREAM_LOST",n[n.GROUP_UPDATE_AUDIO_STREAM_RECOVER=1]="GROUP_UPDATE_AUDIO_STREAM_RECOVER",n[n.GROUP_UPDATE_ADD_PARTICIPANTS=2]="GROUP_UPDATE_ADD_PARTICIPANTS",n[n.GROUP_UPDATE_REMOVE_PARTICIPANTS=3]="GROUP_UPDATE_REMOVE_PARTICIPANTS",n[n.GROUP_UPDATE_SET_PROPERTIES=4]="GROUP_UPDATE_SET_PROPERTIES",n[n.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"}(dr||(dr={}));var hr={options:{syntax:"proto3"},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:"int32",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}}}}}}},gr=e.getProtobufRoot(hr),br=gr.lookupType("signal_msg.Response"),yr=gr.lookupType("signal_msg.BatchNotification"),kr=gr.lookupType("signal_msg.MediaMessage"),Sr=gr.lookupType("signal_msg.StreamNotification");gr.lookupType("signal_msg.ProgressNotification");var Pr=gr.lookupType("signal_msg.ServerFailoverNotification"),Tr=gr.lookupType("signal_msg.PublishRequest"),wr=gr.lookupType("signal_msg.SoacRequest"),Er=gr.lookupType("signal_msg.UnpublishRequest"),Ir=gr.lookupType("signal_msg.StreamControlRequest"),Mr=gr.lookupType("signal_msg.SubscribeRequest"),Or=gr.lookupType("signal_msg.SetStreamPropertiesRequest"),Rr=gr.lookupType("signal_msg.UnsubscribeRequest"),Ar=gr.lookupType("signal_msg.SubscriptionControlRequest"),xr=gr.lookupType("signal_msg.CreatePeerConnectionRequest"),Cr=gr.lookupType("signal_msg.ClosePeerConnectionRequest"),_r=gr.lookupType("signal_msg.BatchPublishRequest"),Dr=gr.lookupType("signal_msg.BatchUnpublishRequest"),jr=gr.lookupType("signal_msg.BatchSubscribeRequest"),Lr=gr.lookupType("signal_msg.BatchUnsubscribeRequest"),Nr=gr.lookupType("signal_msg.JoinGroupRequest"),Vr=gr.lookupType("signal_msg.SetGroupPropertiesRequest"),Fr=gr.lookupType("signal_msg.DismissGroupRequest"),Ur=gr.lookupType("signal_msg.LeaveGroupRequest"),Gr=gr.lookupType("signal_msg.SyncDataRequest"),Br=gr.lookupType("signal_msg.SyncDataByIdsRequest"),Hr=gr.lookupType("signal_msg.GroupChangeLog"),qr=gr.lookupType("signal_msg.GroupListChangeLog"),Wr=gr.lookupType("signal_msg.SetParticipantPropertiesRequest"),Yr=gr.lookupType("signal_msg.QueryStreamsVerRequest"),Jr=gr.lookupType("signal_msg.QueryStreamsRequest");function Qr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Qr=function(){return!!e})()}var Kr=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,Qr()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.channel=e,r.rpcId=0,r.reporter=e.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-signal]"),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",Sr.decode(t)):"serverFailover"===e?this.emit("serverFailover",Pr.decode(t)):"media-message"===e?this.emit("media-message",kr.decode(t)):"group"===e?this.emit("group",Hr.decode(t)):"group-list"===e&&this.emit("group-list",qr.decode(t))}},{key:"handleBatchNotifyEvent",value:function(e){var t=this;yr.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=xr.encode(e).finish();return this.rpc("create-peer-connection",t,e).then(function(e){return e.createPeerConnectionResponse})}},{key:"closePeerConnection",value:function(e){var t=Cr.encode(e).finish();return this.rpc("close-peer-connection",t,e)}},{key:"batchSubscribe",value:function(e){var t=jr.encode(e).finish();return this.rpc("batch-subscribe",t,e).then(function(e){return e.errorMsg})}},{key:"setGroupProperties",value:function(e){var t=Vr.encode(e).finish();return this.rpc("set-group-properties",t,e).then(function(e){return e.setGroupPropertiesResponse})}},{key:"batchUnSubscribe",value:function(e){var t=Lr.encode(e).finish();return this.rpc("batch-unsubscribe",t,e)}},{key:"batchPublish",value:function(e){var t=_r.encode(e).finish();return this.rpc("batch-publish",t,e).then(function(e){return e.errorMsg})}},{key:"batchUnPublish",value:function(e){var t=Dr.encode(e).finish();return this.rpc("batch-unpublish",t,e)}},{key:"publish",value:function(e){var t=Tr.encode(e).finish();return this.rpc("publish",t,e).then(function(e){return e.publishResponse})}},{key:"setParticipantProperties",value:function(e){var t=Wr.encode(e).finish();return this.rpc("set-participant-properties",t,e)}},{key:"soac",value:function(e){var t=wr.encode(e).finish();return this.rpc("soac",t,e)}},{key:"unpublish",value:function(e){var t=Er.encode(e).finish();return this.rpc("unpublish",t,e)}},{key:"streamControl",value:function(e){var t=Ir.encode(e).finish();return this.rpc("stream-control",t,e)}},{key:"setStreamProperties",value:function(e){var t=Or.encode(e).finish();return this.rpc("set-stream-properties",t,e)}},{key:"subscribe",value:function(e){var t=Mr.encode(e).finish();return this.rpc("subscribe",t,e).then(function(e){return e.subscribeResponse})}},{key:"unsubscribe",value:function(e){var t=Rr.encode(e).finish();return this.rpc("unsubscribe",t,e)}},{key:"subscriptionControl",value:function(e){var t=Ar.encode(e).finish();return this.rpc("subscription-control",t,e)}},{key:"getStreamsVer",value:function(e){var t=Yr.encode(e).finish();return this.rpc("query-streams-ver",t,e).then(function(e){return e.queryStreamsVerResponse})}},{key:"getStreams",value:function(e){var t=Jr.encode(e).finish();return this.rpc("query-streams",t,e).then(function(e){return e.queryStreamsResponse})}},{key:"joinGroup",value:function(e){var t=Nr.encode(e).finish();return this.rpc("join-group",t,e).then(function(e){return e.joinGroupResponse})}},{key:"leaveGroup",value:function(e){var t=Ur.encode(e).finish();return this.rpc("leave-group",t,e).then(function(e){return e.leaveGroupResponse})}},{key:"dismissGroup",value:function(e){var t=Fr.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(e,t){var r=this,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;return new Promise(function(n,o){var a=r.rpcId++;r.logger.info("rtc rpcId ".concat(a,":").concat(e," param"),i),r.channel.signaling.rpc(e,t,i).then(function(t){var i=br.decode(t);i.code===dr.Result.Ok?(r.logger.info("rtc rpcId ".concat(a,":").concat(e," result====>"),i),n(i)):(r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),i),o(i))}).catch(function(t){r.logger.error("rtc rpcId ".concat(a,":").concat(e," error====>"),t),o(t)})})}}])}();function zr(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(zr=function(){return!!e})()}var $r=function(){function t(){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,zr()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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 Xr(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Zr(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xr(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xr(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}function ri(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ri=function(){return!!e})()}var ii={timestamp:0,audioLevel:0,bytesSent:0,packetsSent:0,packetsLost:0,roundTripTime:0},ni={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},oi=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,ri()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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({},ni),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({},ii),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,i=Object.assign({source:this.source,trackStats:[]},ni,this.connection.peerConnectionStats);if(i.timestamp=Date.now(),this.track){var n=this.track.getMediaStreamTrack().getSettings(),o=n.width,a=n.height,s=n.frameRate;i.captureFramesPerSecond=s===1/0?0:s||0,i.captureFrameWidth=o||0,i.captureFrameHeight=a||0}var c=new Map,u=Ve(i,this.lastVideoSendInfo);return t.forEach(function(t){if(/outboundrtp|outbound-rtp/i.test(t.type)){var n=c.get(t.ssrc)||{},o=r.lastVideoSendInfo.trackStats.get(t.ssrc)||{};if(n.sendFrameWidth=t.frameWidth||0,n.sendFrameHeight=t.frameHeight||0,n.framesSent=t.framesSent||0,n.framesEncoded=t.framesEncoded||0,n.targetBitrate=t.targetBitrate||0,n.qpSum=t.qpSum||0,n.bytesSent=t.bytesSent||0,n.packetsSent=t.packetsSent||0,n.packetsSentForLost=n.packetsSent||0,n.sentTimestamp=t.timestamp||0,n.totalEncodeTime=t.totalEncodeTime||0,n.keyFramesEncoded=t.keyFramesEncoded||0,n.firCount=t.firCount||0,n.pliCount=t.pliCount||0,n.retransmittedBytesSent=t.retransmittedBytesSent||0,n.retransmittedPacketsSent=t.retransmittedPacketsSent||0,n.qualityLimitationReason=t.qualityLimitationReason||"",n.web_powerEfficientEncoder=t.powerEfficientEncoder||"",n.web_encoderImplementation=t.encoderImplementation||"",n.web_qualityLimitationResolutionChanges=t.qualityLimitationResolutionChanges>=0?t.qualityLimitationResolutionChanges:-1,n.web_codecId=t.codecId||"",n.sendFramesPerSecond=t.framesPerSecond||0,n.sendFrameWidth>i.maxSendFrameWidth){if(i.maxSendFrameWidth=n.sendFrameWidth,!n.sendFramesPerSecond&&o){var a=Ue(n.framesSent||n.framesEncoded,o.framesSent||o.framesEncoded);n.sendFramesPerSecond=Math.round(a/u)}if(n.framesEncoded){var s=Ue(n.framesEncoded,null==o?void 0:o.framesEncoded);i.encodeFramesPerSecond=Math.round(s/u)}i.sendFramesPerSecond=n.sendFramesPerSecond}c.set(t.ssrc,n),i.targetBitrate=n.targetBitrate,i.totalBytesSent+=n.bytesSent,i.totalPacketsSent+=n.packetsSent,i.totalEncodedTime+=n.totalEncodeTime,i.totalFramesEncoded+=n.framesEncoded,i.totalFramesSent+=n.framesSent,i.totalQpSum+=n.qpSum,i.maxSendFrameHeight=Math.max(n.sendFrameHeight,i.maxSendFrameHeight),c.set(t.ssrc,n)}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),i.totalFramesEncoded+=d.framesEncoded,i.totalEncodedTime+=d.totalEncodeTime,i.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,i.totalPacketsLost+=l.packetsLost,l.packetsLost===(p.packetsLost||0)&&(l.packetsSentForLost=p.packetsSentForLost||0,l.lostTimestamp=p.lostTimestamp||0),c.set(t.ssrc,l)}}),i.trackStats=c,i}},{key:"getLayersMetricInfo",value:function(e){var t,r=[],i=ei(e.trackStats.entries());try{for(i.s();!(t=i.n()).done;){var n=kt(t.value,2),o=n[0],a=n[1],s=this.lastVideoSendInfo.trackStats.get(o)||{},c=Ue(a.framesSent,s.framesSent),u=Ue(a.framesEncoded,s.framesEncoded),d=Ue(a.keyFramesEncoded,s.keyFramesEncoded),l=Ue(a.retransmittedBytesSent,s.retransmittedBytesSent),p=Ue(a.retransmittedPacketsSent,s.retransmittedPacketsSent),f=Ue(a.firCount,s.firCount),v=Ue(a.pliCount,s.pliCount),m=Ue(a.packetsSent,s.packetsSent),h=Ue(a.packetsSentForLost,s.packetsSentForLost),g=Ue(a.lostTimestamp,s.lostTimestamp),b=Ue(a.sentTimestamp,s.sentTimestamp),y=Ue(a.packetsLost,s.packetsLost),k=Ue(a.totalEncodeTime,s.totalEncodeTime),S=Ue(a.qpSum,s.qpSum),P=a.qualityLimitationReason,T=a.sendFrameWidth,w=Zr(Zr({sendFrameHeight:a.sendFrameHeight,sendFrameWidth:T,qualityLimitationReason:P,web_powerEfficientEncoder:a.web_powerEfficientEncoder,web_encoderImplementation:a.web_encoderImplementation,web_qualityLimitationResolutionChanges:a.web_qualityLimitationResolutionChanges,web_codecId:a.web_codecId},a),{},{deltaQbSum:S,deltaPacketsSent:m,deltaPacketsLost:y,deltaFramesSent:c,deltaTimestampForLost:g,deltaFramesEncoded:u,deltaKeyFramesEncoded:d,deltaFirCount:f,deltaEncodedTime:k,deltaPliCount:v,deltaTimestampForSent:b,deltaPacketsSentForLost:h,deltaRetransmittedBytesSent:l,deltaRetransmittedPacketsSent:p});r.push(w)}}catch(e){i.e(e)}finally{i.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,t){var r={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 i,n=this.getLayersMetricInfo(e),o=n.tracksStatInfo,a=n.totalBytesSent,s=n.totalFramesEncoded,c=n.totalEncodedTime;o.length>1&&(r.attr_stream_options+="sim:".concat(o.length,"/"));for(var u={attr_encoded_framerate_sim:[],attr_enc_key_frames_sim:[],attr_fir_count_sim:[],attr_pli_count_sim:[],attr_quality_limitation_reason_sim:[],web_powerEfficientEncoder_sim:[],web_encoderImplementation_sim:[],web_qualityLimitationResolutionChanges_sim:[],web_codecId_sim:[],attr_retx_bytes_sim:[],attr_retx_packets_sim:[],attr_resolution_sim:[],attr_encode_qp_sim:[]},d=[],l=0,p=Ue(e.timestamp,this.lastVideoSendInfo.timestamp),f=!0,v=0;v<o.length;v++){var m=o[v];u.attr_enc_key_frames_sim.push(m.deltaKeyFramesEncoded),u.attr_fir_count_sim.push(m.deltaFirCount),u.attr_pli_count_sim.push(m.deltaPliCount),u.attr_quality_limitation_reason_sim.push(m.qualityLimitationReason),u.web_powerEfficientEncoder_sim.push(m.web_powerEfficientEncoder),u.web_encoderImplementation_sim.push(m.web_encoderImplementation),u.web_qualityLimitationResolutionChanges_sim.push(m.web_qualityLimitationResolutionChanges),u.web_codecId_sim.push(m.web_codecId),u.attr_retx_bytes_sim.push(m.deltaRetransmittedBytesSent),u.attr_retx_packets_sim.push(m.deltaRetransmittedPacketsSent),u.attr_resolution_sim.push({count:m.deltaFramesSent||m.deltaFramesEncoded,index:v,resolution:"".concat(m.sendFrameWidth,"*").concat(m.sendFrameHeight)});var h=m.deltaFramesEncoded||m.deltaFramesSent;f&&(f=0===h),u.attr_encoded_framerate_sim.push(X({},v,Math.round(1e3*h/p))),u.attr_encode_qp_sim.push(X({},v,Math.round((m.deltaQbSum||0)/(h||Number.EPSILON))));var g=m.deltaTimestampForLost,b=m.deltaTimestampForSent,y=m.deltaPacketsLost,k=m.deltaPacketsSentForLost;if(y&&k&&g&&b){var S=y/g/(k/b);d.push(Math.max(Math.min(S,1),0))}}for(var P=0,T=Object.entries(u);P<T.length;P++){var w=kt(T[P],2),E=w[0],I=w[1];r[E]=I.length?JSON.stringify(I):""}var M=0,O=Ue(s,this.lastVideoSendInfo.totalFramesEncoded),R=Ue(c,this.lastVideoSendInfo.totalEncodedTime);O&&R&&(M=Math.round(1e3*R/O));var A=Ue(a,this.lastVideoSendInfo.totalBytesSent);r.attr_duration_ms=p,r.attr_bitrate=p>0?Math.min(Math.round(8*A*1e3/p),2e7):0,r.attr_enc_average_elapsed_ms=M,this.videoSendReport=r,f&&(r.attr_resolution_sim="null",r.attr_encoded_framerate_sim="null");var x={web_dtlsState:(null===(i=te(t.values()).find(function(e){return"transport"===e.type}))||void 0===i?void 0:i.dtlsState)||""};this.emit("video-send-stream",Object.assign(x,this.videoSendReport)),d.length&&(l=Math.min(Math.round(d.reduce(function(e,t){return t+e},0)/d.length*255),255)),this.bweReport={attr_duration_ms:p,attr_rtt:Math.round(e.roundTripTime||0),attr_reported_bitrate:Math.max(0,Math.min(e.availableOutgoingBitrate||0,2e7)),attr_lossrate:l},this.emit("bwe",Object.assign({},this.bweReport))}this.lastVideoSendInfo=e}},{key:"extractAudioMetrics",value:function(e){var t=this,r=Object.assign({},ii,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 i=t.track.getMediaStreamTrack().getSettings(),n=i.channelCount,o=i.sampleRate;r.channels=n,r.sampleRate=o}}),r}},{key:"makeAudioReport",value:function(e){this.lastAudioSendInfo.timestamp>0&&e.timestamp&&(this.audioSendReport={attr_duration_ms:Math.round(Ue(e.timestamp,this.lastAudioSendInfo.timestamp)),attr_bitrate:Math.round(8*Ue(e.bytesSent,this.lastAudioSendInfo.bytesSent)*1e3/Ue(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,t.originStats)})}},{key:"getStats",value:function(){var t,r,i=this,n=this.tranceiver,o=this.pc;if(!o||null==n||null===(t=n.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(n.sender.track))||void 0===r?void 0:r.then(function(e){return{videoMetrics:i.source?i.extractVideoMetrics(e):void 0,audioMetrics:i.source?void 0:i.extractAudioMetrics(e),originStats:e}})}}])}();function ai(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 si(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)?si(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 si(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ci(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ci=function(){return!!e})()}var ui={timestamp:0,packetsLost:0,packetsReceived:0,bytesReceived:0,audioLevel:0,decodingNormal:0,roundTripTime:0},di={packetsLost:0,packetsReceived:0,framesDropped:0,frameHeight:0,frameWidth:0,framesDecoded:0,framesReceived:0,timestamp:0,framesPerSecond:0,bytesReceived:0,roundTripTime:0},li=function(){function t(r){var i,n,a,s,c;o(this,t),a=this,s=l(s=t),n=d(a,ci()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(n,"videoReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"audioReceiveReport",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastVideoReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"lastAudioReceiveInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"source",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportFlag",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"firstReportTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"tranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(n,"connection",{enumerable:!0,configurable:!0,writable:!0,value:void 0});var u=r.connection,p=r.transceiver,f=r.uid,v=r.stream,m=r.transceivers;return n.connection=u,n.pc=u.pc,n.tranceiver=p,n.tranceivers=m,n.firstReportTimer=e.addTimer(function(){n.getStats().then(function(e){n.makeFirstReport(e)})},400,"interval"),n.source="mcu"!==f&&(null===(i=v.media)||void 0===i||null===(i=i.video)||void 0===i?void 0:i.source),n.videoReceiveReport={attr_duration_ms:0,attr_bitrate:0,attr_current_delay:0,attr_stream_options:"",attr_resolution:"",attr_dec_frames:0,attr_decode_qp:0,attr_fraction_lost:0,attr_network_framerate:0,attr_render_delay:0,attr_dec_key_frames:-1},n.lastVideoReceiveInfo=Object.assign({},di),n.firstReportFlag={audioFirstPacket:!1,videoFirstPacket:!1,audioFirstFrame:!1},n.lastAudioReceiveInfo=Object.assign({},ui),n.audioReceiveReport={attr_duration_ms:0,attr_delay_estimate:0,attr_bitrate:0},n}return f(t,$r),u(t,[{key:"extractAudioMetrics",value:function(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=Object.assign({},ui,this.connection.peerConnectionStats);return i.timestamp=Date.now(),e.forEach(function(e){e.isRemote||(/inboundrtp|inbound-rtp/i.test(e.type)?(i.bytesReceived=e.bytesReceived||0,i.packetsReceived=e.packetsReceived||0,r||(i.packetsLost===(t.lastAudioReceiveInfo.packetsLost||0)?i.packetsReceivedForLost=t.lastAudioReceiveInfo.packetsReceived||0:i.packetsReceivedForLost=i.packetsReceived||0),i.packetsLost=e.packetsLost||0,i.audioLevel=e.audioLevel||0,i.decodingNormal=Number(e.googDecodingNormal||0)):/track/i.test(e.type)&&(i.audioLevel=e.audioLevel))}),i}},{key:"extractMultipleAudioMetrics",value:function(e){var t=this,r=e.map(function(e){return t.extractAudioMetrics(e,!0)}),i=Object.assign({},ui,this.connection.peerConnectionStats);i.timestamp=Date.now();var n,o=ai(r);try{for(o.s();!(n=o.n()).done;){var a=n.value;i.bytesReceived+=a.bytesReceived||0,i.packetsLost+=a.packetsLost||0,i.packetsReceived+=a.packetsReceived||0,i.audioLevel=Math.max(i.audioLevel,a.audioLevel||0),i.decodingNormal=Math.max(i.decodingNormal,a.decodingNormal||0)}}catch(e){o.e(e)}finally{o.f()}return i.packetsLost===(this.lastAudioReceiveInfo.packetsLost||0)?i.packetsReceivedForLost=this.lastAudioReceiveInfo.packetsReceived||0:i.packetsReceivedForLost=i.packetsReceived||0,i}},{key:"extractVideoMetrics",value:function(e){var t=this,r=Object.assign({source:this.source},di,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 i;null!==(i=e.mimeType)&&void 0!==i&&i.includes("video")&&(r.sdpFmtpLine=e.sdpFmtpLine)}}),r}},{key:"makeAudioReport",value:function(e){if(this.lastAudioReceiveInfo.timestamp>0&&e.timestamp){var t=Math.round(Ue(e.timestamp,this.lastAudioReceiveInfo.timestamp)),r=Ue(e.packetsLost,this.lastAudioReceiveInfo.packetsLost),i=Ue(e.packetsReceivedForLost,this.lastAudioReceiveInfo.packetsReceivedForLost),n=Ue(e.bytesReceived,this.lastAudioReceiveInfo.bytesReceived),o=0;try{o=Math.max(r/i,0)}catch(e){o=0}isNaN(o)&&(o=0),this.audioReceiveReport={attr_delay_estimate:0,attr_duration_ms:t,attr_bitrate:Math.round(8*n/(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,i=t.pliCount,n=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(n>0&&e.timestamp){var f=Ue(e.timestamp,n);if(e.bytesReceived-u>=0){var v=Ue(e.packetsLost,a),m=Ue(e.packetsReceivedForLost,d),h=0;try{h=Math.round(v/m*255)}catch(e){h=0}isNaN(h)&&(h=0);var g=Ue(e.framesDecoded,s);this.videoReceiveReport={attr_network_framerate:Math.round(1e3*g/f),attr_dec_frames:g,attr_dec_key_frames:e.keyFramesDecoded,attr_decode_qp:0,attr_render_delay:0,attr_current_delay:0,attr_dropped_count:Ue(e.framesDropped,c),attr_fir_count:Ue(e.firCount,r),attr_freeze_count:Ue(e.freezeCount,o),attr_pli_count:Ue(e.pliCount,i),attr_retx_bytes:Ue(e.retransmittedBytesReceived,l),attr_retx_packets:Ue(e.retransmittedPacketsReceived,p),attr_bitrate:Math.round(8*Ue(e.bytesReceived,u)*1e3/f),attr_stream_options:"audio:false/video:".concat(this.source,"/resolution:").concat(e.frameWidth,"*").concat(e.frameHeight,"/"),attr_fraction_lost:Math.max(0,Math.min(h,255)),attr_resolution:JSON.stringify([{count:g,resolution:"".concat(e.frameWidth,"*").concat(e.frameHeight)}]),attr_duration_ms:Math.round(f)},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,i=r.audioFirstFrame,n=r.audioFirstPacket,o=r.videoFirstPacket,a=t.audioMetrics,s=t.videoMetrics;if(a&&s){if((i||-1===(null==a?void 0:a.decodingNormal))&&n&&o)return void(this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null))}else if(a){if((i||-1===(null==a?void 0:a.decodingNormal))&&n)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&&!n&&(this.emit("audio-first-packet"),this.firstReportFlag.audioFirstPacket=!0),Number(null==a?void 0:a.decodingNormal)>0&&!i&&(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,i=this.tranceiver,n=this.tranceivers,o=this.pc;if(!(o&&(null!=n&&n.length||null!=i&&i.receiver.track)))return Promise.resolve({});if(null==o||!o.getStats)throw new e.DingRTCError(e.ErrorCode.BrowserNotSupported,"getStats is not supported");if(n&&n.length){var a=n.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!=i&&null!==(t=i.receiver)&&void 0!==t&&t.track?o.getStats(i.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,i,n;(r="stop",i=this,"function"==typeof(n=re(l(t.prototype),r,i))?function(e){return n.apply(i,e)}:n)([]),this.firstReportTimer&&(e.removeTimer(this.firstReportTimer,"interval"),this.firstReportTimer=null)}}])}();function pi(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return fi(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?fi(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function fi(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function vi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function mi(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?vi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):vi(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 gi=e.getReporter().getLoggerWithPrefix("[rtc-subs]"),bi=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,hi()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"subIdAcc",{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,"rtcSignaling",{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,"logger",{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}),Object.defineProperty(r,"targetMediaType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logTrackEnded",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track ended",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackUnmute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track unmute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"logTrackMute",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.state===Y.Processing&&r.logger.info("sub track mute",null==e||null===(t=e.target)||void 0===t?void 0:t.id,r.subIdAcc)}}),Object.defineProperty(r,"updateTransceiverListeners",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t;null!==(e=r.transceiver)&&void 0!==e&&null!==(e=e.receiver)&&void 0!==e&&e.transport?(r.transceiver.receiver.transport.onerror=r._onDtlsError,r.transceiver.receiver.transport.onstatechange=r._onDtlsStateChange,null!==(t=r.transceiver)&&void 0!==t&&null!==(t=t.receiver)&&void 0!==t&&t.transport.iceTransport&&(r.transceiver.receiver.transport.iceTransport.onselectedcandidatepairchange=r._onSelectedCandidatePairChange.bind(r,r.transceiver.receiver))):r.logger.info("browser version low, no dtls transport to watch")}}),Object.defineProperty(r,"_onDtlsError",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t;r.logger.error("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_error"),null==e||null===(t=e.error)||void 0===t?void 0:t.errorDetail)}}),Object.defineProperty(r,"_onDtlsStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(){r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," dtls_state_change"),r.transceiver.receiver.transport.state)}}),Object.defineProperty(r,"_onSelectedCandidatePairChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t,i=null==e||null===(t=e.transport)||void 0===t||null===(t=t.iceTransport)||void 0===t?void 0:t.getSelectedCandidatePair();r.logger.info("".concat(r.id," ").concat(r.uid," ").concat(r.subIdAcc," selected_candidate_pair_change"),i)}}),r.subIdAcc="subIdAcc-".concat(t.subIdAcc++);var s=e.connection,c=e.stream,u=e.uid,p=e.resolutionInfo,f=e.userConfigResolution,v=e.targetMediaType;return r.connection=s,r.targetMediaType=v,r.resolutionInfo=p,r.userConfigResolution=f,r.rtcSignaling=s.rtcSignaling,r.stream=c,r.uid=u,r.reporter=s.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtc-subs]"),r.connection.once("ended",function(){r.clear()}),r.videoStatsMap=new Map,r.audioStatsMap=new Map,r.metricsMap=new Map,r.state=Y.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,i=this;if(be.audioSFU&&"audio"===e.kind){var n,o=null===(n=this.transceivers)||void 0===n?void 0:n.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!=o&&o.includes(e.id)&&(e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute)),this._stream=this._stream||new MediaStream([]),this._stream.addTrack(e)}else if(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)){e.removeEventListener("ended",this.logTrackEnded),e.removeEventListener("unmute",this.logTrackUnmute),e.removeEventListener("mute",this.logTrackMute),e.addEventListener("ended",this.logTrackEnded),e.addEventListener("unmute",this.logTrackUnmute),e.addEventListener("mute",this.logTrackMute),this._stream=new MediaStream([e]);var a=document.createElement("video");a.onloadeddata=function(){a.srcObject=null,i.handleVideoFirstFrame()},a.srcObject=this._stream}}},{key:"mediaStream",get:function(){return this._stream||this.connection.mcuAudioStream}},{key:"stop",value:function(){var e=this;if(this.state===Y.Processing)return this.clear(),this.rtcSignaling.unsubscribe({subscriptionId:this.id}).catch(function(t){e.logger.warn("negative ack for unsubscribing, ".concat(t))})}},{key:"mute",value:function(e){return this.rtcSignaling.subscriptionControl({subscriptionId:this.id,operation:"pause",track:e})}},{key:"unmute",value:function(e){return this.rtcSignaling.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=yi(this.stream,e),t||(this.userConfigResolution=e),this.rtcSignaling.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()}},{key:"clear",value:function(){this.state!==Y.End&&(this.reset(),this.state=Y.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 li(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 li(this),this.onMonitor()}},{key:"handleVideoFirstFrame",value:function(){this.reporter.trace.videoFirstFrame({sessionId:this.id,remoteStreamId:this.stream.id,attr_elapse_time:Date.now()-this.startTime,remoteUserId:this.uid}),this.logger.info("video-first-frame sessionId=".concat(this.id))}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,i=e.videoMetrics;if(r){var n,o=(null===(n=this.metricsMap.get(t))||void 0===n?void 0:n.audioMetrics)||{},a=Ve(r,o),s=Ue(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(i){var u,d,l=(null===(u=this.metricsMap.get(t))||void 0===u?void 0:u.videoMetrics)||{},p=Ve(i,l),f=Ue(i.bytesReceived,l.bytesReceived),v={codec:this.connection.peerConnectionStats.videoCodec||i.codec,receiveResolution:{width:i.frameWidth,height:i.frameHeight},receiveBitrate:8*f/p,decodeFrameRate:Math.round(Ue(null==i?void 0:i.framesDecoded,l.framesDecoded)/p),receiveFrameRate:Math.round(Ue(null==i?void 0:i.framesReceived,l.framesReceived)/p),receiveFramesDropped:Ue(null==i?void 0:i.framesDropped,l.framesDropped),receiveBytes:i.bytesReceived,receivePackets:i.packetsReceived,receivePacketsLost:i.packetsLost,rtt:i.roundTripTime,timestamp:i.timestamp},m=this.connection.subSdpFmtpLines.some(function(e){return e.includes("64")}),h=(null===(d=this.stream.media)||void 0===d||null===(d=d.video)||void 0===d?void 0:d.source)===exports.VideoSourceInfo.CAMERA&&f>3e4&&0===v.decodeFrameRate;"network"===t&&(this.stucked&&h?m&&v.receiveFramesDropped>0&&!be.downlinkForbidHighProfile&&this.connection.handleHighProfileFallback():this.stucked=h),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(mi({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}),this.monitor.on("audio-recv-stream",function(t){e.reporter.metric.audioRecvStream(mi({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}),e.logger.info("video-first-packet sessionId=".concat(e.id))}),this.monitor.on("video-recv-stream",function(t){e.reporter.metric.videoRecvStream(mi({sessionId:e.id,remoteStreamId:e.stream.id,remoteUserId:e.uid},t))}))}}])}();Object.defineProperty(bi,"subIdAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var yi=function(e,t){if(!t)return null;var r=t.resolutionLevel,i=e.media.video.highestResolutionLevel;if(i&&i<r){var n=Rt(i);return Ot(n,ke(e))}return t},ki=function(e){var t,r={audio:[],video:[]},i=pi(e);try{for(i.s();!(t=i.n()).done;){var n=t.value,o=n.stream,a=n.error,s=n.resolutionInfo,c=n.targetMediaType;if(a)gi.error("skip subscribe",o,a);else{var u=Si(o,s,c),d=u.audio,l=u.video;if("audio"===c&&d){var p=mi(mi({},d),{},{trackId:o.media.audio.trackId,ssrcGroup:[{ssrc:ji()}]});be.audioSFU&&(p.ssrcGroup=new Array(6).fill(0).map(function(){return{ssrc:ji()}})),r.audio.push(p)}else if("video"===c&&l){var f,v;r.video.push(mi(mi({},l),{},{trackId:null===(f=o.media)||void 0===f||null===(f=f.video)||void 0===f?void 0:f.trackId,ssrcGroup:null===(v=o.media)||void 0===v||null===(v=v.video)||void 0===v?void 0:v.ssrcGroup,subSsrcGroup:{ssrc:ji(),rtxSsrc:ji()}}))}}}}catch(e){i.e(e)}finally{i.f()}return r},Si=function(e,t,r){var i=e.id,n=e.media,o=n.audio,a=n.video,s={};if(o&&"audio"===r)s.audio={from:i};else if(a&&"video"===r){var c;s.video={from:i,format:null===(c=n.video)||void 0===c?void 0:c.format,parameters:yi(e,t)}}return s},Pi=function(){var e=n($.mark(function e(t,r){var i,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=[],o={},t.forEach(function(e,t){var n=e.stream,a=e.error,s=e.uid,c=e.resolutionInfo,u=e.targetMediaType;if(i[t]={stream:n,error:a,uid:s,resolutionInfo:c},!a){var d=new bi({connection:r,uid:s,userConfigResolution:c,resolutionInfo:c&&yi(n,c),stream:n,targetMediaType:u});o[n.id]=d}}),s=new Promise(function(e,s){a=function(){var a=n($.mark(function a(){var c;return $.wrap(function(a){for(;;)switch(a.prev=a.next){case 0:if((c=ki(t)).audio.length||c.video.length){a.next=1;break}return gi.info("batchSubscribe no valid media to sub"),a.abrupt("return",e(i));case 1:return a.next=2,Bi(r,c,o);case 2:r.rtcSignaling.batchSubscribe({connectionId:r.id,propertiesJsonStr:JSON.stringify({opusExtendInbandFec:!0,type:be.audioSFU?"selective":"mixed"}),supportTemporalLayer:!1,media:c}).then(function(){var r=n($.mark(function r(n){var a,s,c,u,d,l;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:if(a=n.detailStatus,"ok"===(s=n.globalStatus)){r.next=1;break}return i.forEach(function(e){e.error=e.error||Se(e.stream,s)}),r.abrupt("return",e(i));case 1:c=pi(a),r.prev=2,d=$.mark(function e(){var r,n,a,s,c,d;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=u.value,n=r.id,a=r.msg,s=r.origin,c=o[s.id],d=t.findIndex(function(e){return e.stream.id===s.id}),"ok"===a&&c?(c.id=n,i[d].id=n,i[d].subscription=c):"ok"!==a&&(i[d].error=Se(c.stream,a));case 1:case"end":return e.stop()}},e)}),c.s();case 3:if((u=c.n()).done){r.next=5;break}return r.delegateYield(d(),"t0",4);case 4:r.next=3;break;case 5:r.next=7;break;case 6:r.prev=6,l=r.catch(2),c.e(l);case 7:return r.prev=7,c.f(),r.finish(7);case 8:e(i);case 9:case"end":return r.stop()}},r,null,[[2,6,7,8]])}));return function(e){return r.apply(this,arguments)}}()).catch(s);case 3:case"end":return a.stop()}},a)}));return function(){return a.apply(this,arguments)}}()}),r.addTask(a),e.abrupt("return",s);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ti=function(){var e=n($.mark(function e(t,r){var i,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=new Promise(function(e,o){i=function(){var i=n($.mark(function i(){var n,a;return $.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return n=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}),i.next=1,Yi(r,t);case 1:r.rtcSignaling.batchUnSubscribe({connectionId:r.id,audio:n,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(o);case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()}),r.addTask(i),e.abrupt("return",o);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function wi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Ei(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?wi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):wi(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Ii(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return 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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}var Oi=e.getReporter().getLoggerWithPrefix("[rtc-sdp]"),Ri={motion:"maintain-framerate",detail:"maintain-resolution",balanced:"balanced"},Ai=0,xi=0,Ci=0,_i=new Set,Di=function(e,t){var r=Math.log2(e+1);t>2147483647>>r||(xi=e,Ai=(t<<r|2147483648)>>>0)},ji=function(){if(0==Ai||0==xi)return 0;var e=Math.min(xi+1,1e4);do{var t=Ai+(xi&Ci++);if(0!=t&&!_i.has(t))return t}while(--e>0);return 0},Li=function(t,r){var i,n;if((null===(i=t.rids)||void 0===i?void 0:i.length)>1)return e.Environment.isFirefox()&&(r=Gi(r)),r.rids=null===(n=t.rids)||void 0===n?void 0:n.map(function(e){return{direction:"recv",id:e.id}}),r.simulcast={dir1:"recv",list1:t.simulcast.list1},r},Ni=function(){var e=n($.mark(function e(r){var i,n,o,a,s,c,u;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.connection,n=r.transceiver,o=i.remoteSDP,a=i.pc,e.next=1,a.createOffer();case 1:return s=e.sent,e.next=2,a.setLocalDescription(s);case 2:return i.localSDP=t.parse(s.sdp),c=i.localSDP.media.find(function(e){return e.mid==n.mid}),u=o.media.find(function(e){return e.mid==n.mid}),Li(c,u),e.next=3,a.setRemoteDescription({type:"answer",sdp:t.write(o)});case 3:i.remoteSDP=o;case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),Vi=function(){var r=n($.mark(function r(i,n){var o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return o=i.pc,a=i.idToTransceiverMap,s=i.remoteSDP,c=new MediaStream(n.map(function(e){return e.getMediaStreamTrack()})),u=n.map(function(e){var t={direction:"sendonly"};if(e instanceof Kt){var r=Ut(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 n=i.pc.addTransceiver(e.getMediaStreamTrack()||e.trackMediaType,t);if(e instanceof Kt&&n.sender.setParameters){var o=e.optimizationMode,s=n.sender.getParameters();s.degradationPreference=Ri[o]||"balanced";var c=parseFloat(new URLSearchParams(location.search).get("times"))||0;c&&(Oi.info("adjustUplinkSDPWhenPublish maxBitrate times",c),s.encodings.forEach(function(e){if(e.maxBitrate){var t=e.maxBitrate;e.maxBitrate=e.maxBitrate*c,Oi.info("adjustUplinkSDPWhenPublish update maxBitrate",t,e.maxBitrate,e)}})),Oi.info("adjustUplinkSDPWhenPublish setParameters",s),n.sender.setParameters(s)}return a.set(e.getTrackId(),n),n}),r.next=1,o.createOffer();case 1:return d=r.sent,l=t.parse(d.sdp),r.next=2,o.setLocalDescription(d);case 2:i.localSDP=l,s.groups[0].mids=i.localSDP.groups[0].mids,p=Ii(u),r.prev=3,v=$.mark(function t(){var r,i,n,o,a,c,u;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:r=f.value,i=s.media.find(function(e){return e.type===r.sender.track.kind}),e.Environment.isFirefox()&&"video"===i.type&&(delete i.rids,delete i.simulcast),n=Ei(Ei({},i),{},{ext:te(i.ext),mid:r.mid}),o=l.media.find(function(e){return e.mid==r.mid}),a=new URLSearchParams(location.search).get("startkbs")||2e3,c=new URLSearchParams(location.search).get("minkbs"),u=new URLSearchParams(location.search).get("maxkbs"),Oi.info("startkbs, minkbs, maxkbs",a,c,u),n.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&&be.highStartBitrate?t.push("x-google-start-bitrate=".concat(a)):t.push("x-google-start-bitrate=500"),c&&t.push("x-google-min-bitrate=".concat(c)),u&&t.push("x-google-max-bitrate=".concat(u)),e.config=t.join(";")}}),Li(o,n),s.media.push(n);case 1:case"end":return t.stop()}},t)}),p.s();case 4:if((f=p.n()).done){r.next=6;break}return r.delegateYield(v(),"t0",5);case 5:r.next=4;break;case 6:r.next=8;break;case 7:r.prev=7,m=r.catch(3),p.e(m);case 8:return r.prev=8,p.f(),r.finish(8);case 9:return window.remoteSDP=s,r.next=10,o.setRemoteDescription({type:"answer",sdp:t.write(s)});case 10:return i.remoteSDP=s,r.abrupt("return",{localSDP:i.localSDP,stream:c});case 11:case"end":return r.stop()}},r,null,[[3,7,8,9]])}));return function(e,t){return r.apply(this,arguments)}}(),Fi=function(){var e=n($.mark(function e(r,i){var n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.pc,o=r.remoteSDP,i.map(function(e){return e.transceiver}).forEach(function(e){if(e){n.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=1,n.createOffer();case 1:return a=e.sent,s=t.parse(a.sdp),e.next=2,n.setLocalDescription(a);case 2:return r.localSDP=s,o.groups[0].mids=s.groups[0].mids,r.remoteSDP=o,e.next=3,n.setRemoteDescription({type:"answer",sdp:t.write(o)});case 3:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ui=function(t,r,i){var n=t.ssrc,o=t.rtxSsrc;!function(e){e.ssrc&&_i.add(e.ssrc),e.rtxSsrc&&_i.add(e.rtxSsrc)}(t),r.ssrcGroups=[],o&&r.ssrcGroups.push({semantics:"FID",ssrcs:"".concat(n," ").concat(o)}),r.ssrcs=[],[n,o].filter(function(e){return void 0!==e}).forEach(function(t){r.ssrcs.push({attribute:"msid",value:"".concat(i," v").concat(n),id:t},{attribute:"cname",value:e.createUuid(),id:t})})},Gi=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},Bi=function(){var e=n($.mark(function e(r,i,n){var o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w,E,I,M,O,R,A,x,C,_,D,j,L,N,V,F,U,G,B,H,q;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(c=r.pc,u=r.idToTransceiverMap,d=r.remoteSDP,l=r.idToTransceiversMap,p=d.media.find(function(e){return"video"===e.type}),f=d.media.find(function(e){return"audio"===e.type}),v=null===(o=p.ssrcs)||void 0===o?void 0:o.find(function(e){return"msid"===e.attribute}).value.split(" ")[0],null!==(a=i.audio)&&void 0!==a&&a[0])if(h=null===(m=i.audio)||void 0===m?void 0:m[0],g=h.from,be.audioSFU){if(l.get(g)){b=Ii(l.get(g));try{for(b.s();!(y=b.n()).done;)y.value.direction="recvonly"}catch(e){b.e(e)}finally{b.f()}k=d.media.filter(function(e){return"audio"===e.type}),S=Ii(k);try{for(S.s();!(P=S.n()).done;)P.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"})}),l.set(g,r.mcuAudioTranceivers);n[g].addTransceivers(l.get(g))}else u.get(g)||u.set(g,r.mcuAudioTranceiver),u.get(g).direction="recvonly",f.direction="sendonly",n[g].addTransceiver(u.get(g));T=Ii(i.video),e.prev=1,E=$.mark(function e(){var r,i,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(r=w.value,i=r.from,o=u.get(i)){e.next=1;break}u.set(i,c.addTransceiver("video",{direction:"recvonly"})),e.next=5;break;case 1:if("inactive"===o.direction){e.next=4;break}return o.direction="inactive",e.next=2,c.createOffer();case 2:return a=e.sent,e.next=3,c.setLocalDescription(a);case 3:return d.media.find(function(e){return e.mid==o.mid}).direction="inactive",e.next=4,c.setRemoteDescription({type:"answer",sdp:t.write(d)});case 4:u.get(i).direction="recvonly";case 5:n[i].addTransceiver(u.get(i));case 6:case"end":return e.stop()}},e)}),T.s();case 2:if((w=T.n()).done){e.next=4;break}return e.delegateYield(E(),"t0",3);case 3:e.next=2;break;case 4:e.next=6;break;case 5:e.prev=5,H=e.catch(1),T.e(H);case 6:return e.prev=6,T.f(),e.finish(6);case 7:return e.next=8,c.createOffer();case 8:return I=e.sent,M=t.parse(I.sdp),d.groups[0].mids=M.groups[0].mids,e.next=9,c.setLocalDescription(I);case 9:r.localSDP=M,be.audioSFU&&i.audio[0]&&(O=i.audio[0],R=O.ssrcGroup,A=O.from,l.get(A).forEach(function(e,t){var r,i=null===(r=R[t])||void 0===r?void 0:r.ssrc,n=d.media.find(function(t){var r=t.mid,i=t.type;return r==e.mid&&"audio"===i});n||(n=Ei(Ei({},f),{},{mid:e.mid}),d.media.push(n)),n.ssrcs=Qi(i,v),n.direction="sendonly"})),x=Ii(i.video),e.prev=10,_=$.mark(function e(){var t,r,i,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=C.value,r=t.from,i=t.subSsrcGroup,o=u.get(r),(a=d.media.find(function(e){var t=e.mid,r=e.type;return t==o.mid&&"video"===r}))||((a=Ei({},p)).mid=o.mid,d.media.push(a)),a.direction="sendonly",n[r].ssrc=null==i?void 0:i.ssrc,Ui(i,a,v);case 1:case"end":return e.stop()}},e)}),x.s();case 11:if((C=x.n()).done){e.next=13;break}return e.delegateYield(_(),"t1",12);case 12:e.next=11;break;case 13:e.next=15;break;case 14:e.prev=14,q=e.catch(10),x.e(q);case 15:return e.prev=15,x.f(),e.finish(15);case 16:return Oi.info("sub remoteSDP before remove high profile",t.write(d)),qi(d),r.remoteSDP=d,D=t.write(d),Oi.info("sub remoteSDP after remove high profile",D),e.next=17,c.setRemoteDescription({type:"answer",sdp:D});case 17:null!==(s=i.audio)&&void 0!==s&&s[0]&&(L=null===(j=i.audio)||void 0===j?void 0:j[0],N=L.from,be.audioSFU||n[N].addTransceiver(u.get(N))),V=Ii(i.video);try{for(V.s();!(F=V.n()).done;)G=F.value,B=G.from,null===(U=n[B])||void 0===U||U.updateTransceiverListeners()}catch(e){V.e(e)}finally{V.f()}case 18:case"end":return e.stop()}},e,null,[[1,5,6,7],[10,14,15,16]])}));return function(t,r,i){return e.apply(this,arguments)}}(),Hi=function(e){Wi(e,function(e){return!/profile-level-id=42e01f/i.test(e)&&/profile-level-id/i.test(e)})},qi=function(e){Wi(e,function(e){return/profile-level-id=64/i.test(e)&&/profile-level-id/i.test(e)})},Wi=function(e,t){e.media.forEach(function(e){if("video"===e.type){var r=e.rtp.filter(function(e){return"H264"===e.codec}).filter(function(r){return e.fmtp.find(function(e){return e.payload===r.payload&&t((null==e?void 0:e.config)||"")})}),i=new Map;e.fmtp.forEach(function(e){/apt=\d+/i.test(e.config)&&i.set(e.payload,e.config.split("=")[1])}),Oi.info("rtxPayloadMap",Array.from(i.entries())),e.rtp=e.rtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===i.get(e.payload)})}),e.fmtp=e.fmtp.filter(function(e){return!r.find(function(t){return t.payload===e.payload||"".concat(t.payload)===i.get(e.payload)})}),e.payloads=e.payloads.split(" ").map(function(e){return e.trim()}).filter(function(e){return!r.find(function(t){return"".concat(t.payload)===e||"".concat(t.payload)===i.get(parseInt(e))})}).join(" "),e.rtcpFb=e.rtcpFb.filter(function(e){return!r.find(function(t){return parseInt("".concat(t.payload))===parseInt("".concat(e.payload))||"".concat(t.payload)===i.get(parseInt("".concat(e.payload)))})})}})},Yi=function(){var e=n($.mark(function e(r,i){var n,o,a,s,c,u,d,l,p,f,v,m;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:n=r.pc,o=r.remoteSDP,a=[],s=Ii(i);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,te(l))}catch(e){s.e(e)}finally{s.f()}return a.forEach(function(e){e.direction="inactive"}),e.next=1,n.createOffer();case 1:return p=e.sent,e.next=2,n.setLocalDescription(p);case 2:r.localSDP=t.parse(p.sdp),f=$.mark(function e(){var t;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=m[v],o.media.find(function(e){return e.mid==t.mid}).direction="inactive";case 1:case"end":return e.stop()}},e)}),v=0,m=a;case 3:if(!(v<m.length)){e.next=5;break}return e.delegateYield(f(),"t0",4);case 4:v++,e.next=3;break;case 5:return r.remoteSDP=o,e.next=6,n.setRemoteDescription({type:"answer",sdp:t.write(o)});case 6:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),Ji=function(e,t){var r=t.media;return e.media.forEach(function(e){var t=e.mid,i=e.ssrcGroups,n=void 0===i?[]:i,o=e.ssrcs,a=void 0===o?[]:o,s=e.type,c=r.findIndex(function(e){return e.mid==t&&e.type===s});c>-1&&(r[c]=Ei(Ei({},r[c]),{},{ssrcGroups:n,ssrcs:a}))}),t},Qi=function(t,r){return[{attribute:"msid",value:"".concat(r," v").concat(t),id:t},{attribute:"cname",value:e.createUuid(),id:t}]},Ki=function(r,i,n){var o=i.direction,a=i.remoteSDP;Oi.info("origin answer for createpc",i.id,r);var s=t.parse(r);s.media.forEach(function(t){t.candidates.forEach(function(t){t.generation=0,t["network-cost"]=e.isPrivateIP(t.ip)?10:1e3})}),n&&(s=function(e,t){var r=t.media.find(function(e){return"audio"===e.type}),i=t.media.find(function(e){return"video"===e.type});return e.media.forEach(function(t,n){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[n]=Ei(Ei({},r),{},{mid:o,ssrcs:u}):"video"===t.type&&(e.media[n]=Ei(Ei({},i),{},{mid:o,ssrcGroups:s,ssrcs:u}),l.length&&(e.media[n].rids=l,e.media[n].simulcast={dir1:"recv",list1:l.map(function(e){return"~".concat(e.id)}).join(";")}))}),e}(a,s));var c=s.media.find(function(e){return"video"===e.type});if("uplink"===o&&e.Environment.isFirefox()&&be.simulcast&&(c.ext=c.ext.filter(function(e){return!e.uri.includes("rtp-stream-id")})),!c.ssrcs&&"downlink"===o){var u=ji(),d=s.msidSemantic.token;c.ssrcs=Qi(u,d)}be.preferH264CbProfile&&Hi(s),i.remoteSDP=s;var l=t.write(s);return Oi.info("final answer for createpc",i.id,l),l},zi=function(r,i){var n=i.direction,o=t.parse(r);if(qi(o),be.preferH264CbProfile&&Hi(o),be.disableTransportCC&&"uplink"===n&&function(e){e.media.forEach(function(e){e.ext=e.ext.filter(function(e){return!e.uri.includes("transport-wide-cc")}),e.rtcpFb=e.rtcpFb.filter(function(e){return"transport-cc"!==e.type})})}(o),"downlink"===n&&!be.downlinkForbidHighProfile){var a=[];o.media.find(function(e){return"video"===e.type}).fmtp.forEach(function(e){var t=e.config;t.includes("profile-level-id")&&a.push(t)}),i.subSdpFmtpLines=a}if(e.Environment.isFirefox()&&(o=Xi(o)),"uplink"===n&&e.Environment.isFirefox()&&be.simulcast){var s=o.media.find(function(e){return"video"===e.type});Gi(s)}return i.localSDP=o,o},$i=function(e){var t=e.localSDP,r=e.remoteSDP,i=e.sessionManager,n=e.mcuAudioTranceiver,o=e.pc,a=e.idToTransceiverMap,s=e.idToTransceiversMap,c=e.direction,u=t.media.slice(2),d=te(i.sessions.values());if("downlink"===c){var l=r.media.slice(2),p=d.filter(function(e){return e instanceof bi}),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&&!be.audioSFU&&(a.set(f.id,n),f.addTransceiver(n));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}),i=p.find(function(e){return(null==e?void 0:e.ssrc)===(null==r?void 0:r.ssrcs[0].id)}),n=o.addTransceiver(e.type,t);"recvonly"===e.direction&&("video"===e.type&&i?(a.set(i.stream.id,n),i.addTransceiver(n)):"audio"===e.type&&v.push(n))}),v.length&&f&&(e.mcuAudioTranceivers=v,s.set(f.id,v),f.addTransceivers(v))}else{var m=d.filter(function(e){return e instanceof an});u.forEach(function(e){var t={direction:e.direction},r=m.find(function(t){return t.mid==e.mid});if("sendonly"===e.direction&&r){var i=r.tracks[0],n=(null==i?void 0:i.getMediaStreamTrack())||(null==i?void 0:i.trackMediaType);if(i instanceof Kt){var s=Ut(i).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(n,t);a.set(i.getTrackId(),c),r.addTransceiver(c)}else o.addTransceiver(e.type,t)})}},Xi=function(e){return function(e,t){if(e){var r,i=e.fmtp,n=e.payloads,o=e.rtp,a=e.rtcpFb,s=[],c={},u=Ii(i);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,m=Ii(f);try{for(m.s();!(v=m.n()).done;){var h=kt(v.value.split("="),2),g=h[0],b=h[1];c[p][g]=b}}catch(e){m.e(e)}finally{m.f()}}}catch(e){u.e(e)}finally{u.f()}for(var y in c){var k=c[y];(t(k)||s.includes(+k.apt))&&s.push(parseInt(y))}if(s.length){for(var S=i.length-1;S>=0;S--){var P=i[S].payload;s.includes(P)&&i.splice(S,1)}for(var T=o.length-1;T>=0;T--)s.includes(o[T].payload)&&o.splice(T,1);for(var w=a.length-1;w>=0;w--)s.includes(parseInt("".concat(a[w].payload)))&&a.splice(w,1);e.payloads=n.split(" ").map(Number).filter(function(e){return!s.includes(e)}).join(" ")}}}(e.media.find(function(e){return"video"===e.type}),function(e){return e["profile-level-id"]&&!e["packetization-mode"]}),e};function Zi(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function en(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Zi(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Zi(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function tn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return rn(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?rn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,s=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){s=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(s)throw o}}}}function rn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function nn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(nn=function(){return!!e})()}var on=e.getReporter().getLoggerWithPrefix("[publication]"),an=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,nn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"rtcSignaling",{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,"logger",{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,"rtcStreamMuted",{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.rtcSignaling=s.rtcSignaling,r.uid=c,r.reporter=s.reporter,r.logger=r.reporter.getLoggerWithPrefix("[rtp-publication]"),r.state=Y.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),p.forEach(function(e){e.on(de,r.handleTracEvent)}),p[0]instanceof Kt&&(r.encodings=Ut(p[0]).encodings),r.state=Y.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!==Y.Processing?Promise.resolve():un([this],{connection:this.connection}).catch(function(r){t.clear(),t.logger.warn("negative ack for unpublish, ".concat(e.tryJsonStringify(r)))})}},{key:"mute",value:(i=n($.mark(function e(){var t,r,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===Y.Processing&&"muted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore mute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!0,this.id),this.rtcStreamMuted="muted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"pause",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,i=e.catch(2),this.logger.error("mute error",this.id,i),this.rtcStreamMuted="unmuted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return i.apply(this,arguments)})},{key:"unmute",value:(r=n($.mark(function e(){var t,r,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.tracks.length&&this.state===Y.Processing&&"unmuted"!==this.rtcStreamMuted){e.next=1;break}return this.logger.info("ignore unmute for tracks=".concat(this.tracks.length," state=").concat(this.state," curRtcStreamMuted=").concat(this.rtcStreamMuted)),e.abrupt("return");case 1:return t=this.tracks[0].trackMediaType,this.reporter.trace.localControl(t,!1,this.id),this.rtcStreamMuted="unmuted",e.prev=2,e.next=3,this.rtcSignaling.streamControl({streamId:this.id,operation:"play",data:t});case 3:return r=e.sent,e.abrupt("return",r);case 4:e.prev=4,i=e.catch(2),this.logger.error("unmute error",this.id,i),this.rtcStreamMuted="muted";case 5:case"end":return e.stop()}},e,this,[[2,4]])})),function(){return r.apply(this,arguments)})},{key:"initInner",value:function(e){this.id=e;var t=this.tracks[0],r=this.connection.idToTransceiverMap.get(t.getTrackId());this.addTransceiver(r),"video"===t.trackMediaType&&t.config.mirror&&this.handleMirror(t.config.mirror)}},{key:"handleMirror",value:function(e){return this.rtcSignaling.setStreamProperties({streamId:this.id,propertiesJsonStr:JSON.stringify({mirror:!!e})})}},{key:"handleRepublish",value:function(e){var t=this,r=this.connection,i=this.transceiver,o=e.getMediaStreamTrack().getSettings(),a=o.width,s=o.height,c=Ft(a,s);this.rtcSignaling.streamControl({streamId:this.id,operation:"updateResolution",highestResolutionLevel:c});var u=function(e,t){var r=jt(e,t),i=function(i){var n=kt(Lt(e,t,i,r),2);n[0];var o=1/(n[1]/t);return Math.max(o,1)};return{ld:i(St.LD),sd:i(St.SD),fhd:i(r)}}(a,s);r.addTask(n($.mark(function e(){var r;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t.logger.info("scales",u),(r=i.sender.getParameters()).encodings.forEach(function(e){e.scaleResolutionDownBy=u[e.rid]}),t.logger.info("handleRepublish setParameters",r),e.abrupt("return",i.sender.setParameters(r).then(function(){console.log(i.sender.getParameters().encodings)}));case 1:case"end":return e.stop()}},e)})))}},{key:"handleTracEvent",value:function(e,t){var r,i=this,n={replace:function(){return i.replaceTrack(t.getMediaStreamTrack())},mute:function(){return i.mute()},unmute:function(){return i.unmute()},republish:function(){be.republish?i.handleRepublish(t):i.stop().then(function(){i.connection.sessionManager.serviceManager.client.publish([t])})},stop:function(){return i.stop()},optimizationMode:function(){return i.updateOptionzationMode()},mirror:function(){return i.handleMirror(t)}};return null===(r=n[e])||void 0===r?void 0:r.call(n)}},{key:"clear",value:function(){var e=this;this.state!==Y.End&&(this.monitor&&(this.monitor.stop(),this.monitor.removeAllListeners(),this.monitor=null),this.tracks.forEach(function(t){t.off(de,e.handleTracEvent)}),this.tracks=[],this.metricsMap.clear(),this.audioStatsMap.clear(),this.videoStatsMap.clear(),this.state=Y.End,this.emit("ended"))}},{key:"applyOptions",value:function(e){var t=this,r=e[0],i=r.index,n=r.bitrate;if(this.logger.debug("applyOptions",e),!(i<this.feedbackIndex||this.state!==Y.Processing)){this.feedbackIndex=i;var o=this.transceiver;this.connection.addTask(function(){return new Promise(function(r){var i,a=0===n,s=!1,c=o.sender.getParameters(),u=e.map(function(e){return e.rid}),d=tn(c.encodings);try{for(d.s();!(i=d.n()).done;){var l,p=i.value,f=tn(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()}return t.logger.info("encodings",c.encodings),s&&t.logger.info("applyOptions setParameters",c),o.sender.setParameters(c).then(function(){return Ni(t).then(r)})})})}}},{key:"updateOptionzationMode",value:function(){var e,t=this,r=this.tracks,i=this.transceiver,n=this.connection;if(r[0]instanceof Kt&&null!=i&&null!==(e=i.sender)&&void 0!==e&&e.setParameters){var o=r[0].optimizationMode;n.addTask(function(){var e=i.sender.getParameters();return e.degradationPreference=Ri[o]||"balanced",t.logger.info("updateOptionzationMode setParameters",e),i.sender.setParameters(e),Ni(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=Y.Processing,this.feedbackIndex=-1,this.monitor=new oi(this),this.onMonitor()}},{key:"replaceTrack",value:function(e){var t;if(this.transceiver){null===(t=this.transceiver.sender.track)||void 0===t||t.stop();try{this.transceiver.sender.replaceTrack(e)}catch(e){this.logger.error("_DEV_TODO_","sender replaceTrack error",e)}}}},{key:"handleMetrics",value:function(e,t){var r=e.audioMetrics,i=e.videoMetrics;if(r){var n,o=(null===(n=this.metricsMap.get(t))||void 0===n?void 0:n.audioMetrics)||{},a=Ve(r,o),s=Ue(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(i){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=Ve(i,f),m=Ue(i.totalBytesSent,f.totalBytesSent),h={codec:this.connection.peerConnectionStats.videoCodec||i.codec,sendFrameRate:Math.round(i.sendFramesPerSecond),captureFrameRate:i.captureFramesPerSecond,encodeFrameRate:i.encodeFramesPerSecond,qpSum:i.totalQpSum||0,targetBitrate:i.targetBitrate,encodeLayers:p.length,sendLayers:p.filter(function(e){return e.active}).length,outgingBitrate:i.availableOutgoingBitrate,sendResolution:{width:i.maxSendFrameWidth,height:i.maxSendFrameHeight},captureResolution:{width:i.captureFrameWidth,height:i.captureFrameHeight},sendBytes:i.totalBytesSent,sendPackets:i.totalPacketsSent,sendPacketsLost:i.totalPacketsLost,timestamp:i.timestamp,rtt:this.connection.peerConnectionStats.roundTripTime||i.roundTripTime,sendBitrate:8*m/v};this.videoStatsMap.set(t,h)}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(en({sessionId:e.id},t))}),this.monitor.on("video-send-stream",function(t){e.reporter.metric.videoSendStream(en({sessionId:e.id},t))}),this.monitor.on("bwe",function(t){e.reporter.metric.bwe(en({sessionId:e.id},t))})}}]);var r,i}(),sn=function(){var e=n($.mark(function e(t,r){var i,n,o,a,s,c=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=c.length>2&&void 0!==c[2]?c[2]:["common"],n={},e.next=1,Vi(r,t);case 1: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)n.audio=[{source:"mic",autoMix:i,trackId:t,msid:s.id,uplinkSsrcGroup:[{ssrc:Number(o.ssrcs[0].id)}]}];else if(e instanceof Kt){var c;n.video=n.video||[];var u=o.ssrcGroups,d=void 0===u?[]:u,l=Ut(e),p=l.encodings,f=l.resolutionLevel;p.length>1&&(d=p.map(function(){return{semantics:"FID",ssrcs:"".concat(ji()," ").concat(ji())}}));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])}}),m=p[p.length-1],h={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(m.maxBitrate),resolution:{width:m.targetWidth,height:m.targetHeight},framerate:m.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}}})};n.video.push(h)}}),e.abrupt("return",n);case 2:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}(),cn=function(e){var t=e.tracks,r=e.connection,i=e.labels,o=e.existedPublications,a=void 0===o?[]:o,s=e.mixedLocalAudioTrack,c={videoPubResultArr:[]},u=[];t.forEach(function(t){var r;if("audio"!==t.trackMediaType||t.source!==exports.AudioSourceInfo.MIC&&t.source!==exports.AudioSourceInfo.SCREENCAST)c.videoPubResultArr.push({publication:new an(en(en({},e),{},{tracks:[t]})),track:t});else{var i=a.find(function(e){var t,r,i;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(i=e.tracks)||void 0===i?void 0:i[0].source)===exports.AudioSourceInfo.SCREENCAST)}),n=u.find(function(e){var t,r,i;return"audio"===(null===(t=e.tracks)||void 0===t?void 0:t[0].trackMediaType)&&((null===(r=e.tracks)||void 0===r?void 0:r[0].source)===exports.AudioSourceInfo.MIC||(null===(i=e.tracks)||void 0===i?void 0:i[0].source)===exports.AudioSourceInfo.SCREENCAST)});i?(i.tracks.push(t),r=i):n?(n.tracks.push(t),r=n):r=new an(en(en({},e),{},{tracks:[s]})),c.audioPubResult={publication:r,track:t}}});var d=t.filter(function(e){return"audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST)});d.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC?s.setMicAudioTrack(e):s.setScreenAudioTrack(e)});var l=[],p=t.filter(function(e){return!("audio"===e.trackMediaType&&(e.source===exports.AudioSourceInfo.MIC||e.source===exports.AudioSourceInfo.SCREENCAST))});if(l.push.apply(l,te(p)),d.length&&(null==s||s.updateMixedAudioTrackToPub(),s.isPublished()||l.push(s)),l.length){var f,v=new Promise(function(e,t){f=function(){var o=n($.mark(function o(){var a,u;return $.wrap(function(o){for(;;)switch(o.prev=o.next){case 0:return o.next=1,sn(l,r,i);case 1:return a=o.sent,u={connectionId:r.id,media:a,simulcast:Tt(l.find(function(e){return e.source===exports.VideoSourceInfo.CAMERA})),simulcastVersion:"1.0",clientType:"web",supportTemporalLayer:!1,type:"webrtc"},o.abrupt("return",r.rtcSignaling.batchPublish(u).then(function(){var t=n($.mark(function t(r){var i,n,o,a,u,l;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=r.detailStatus,"ok"===(n=r.globalStatus)){t.next=1;break}return c.videoPubResultArr.forEach(function(e){e.error=Pe(e.track,n)}),c.audioPubResult&&(c.audioPubResult.error=Pe(c.audioPubResult.track,n)),t.abrupt("return",e(c));case 1:o=tn(i),t.prev=2,u=$.mark(function e(){var t,r,i,n,o,u,l;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=a.value,r=t.id,i=t.origin,n=t.msg,s.getTrackId()===i.id?c.audioPubResult&&(o=c.audioPubResult.publication,"ok"===n&&o?(o.initInner(r),s.setPublication(o),d.forEach(function(e){(null==e?void 0:e.source)===exports.AudioSourceInfo.MIC&&e.muted&&e.emit(de,"mute")})):"ok"!==n&&(c.audioPubResult.error=Pe(c.audioPubResult.track,n))):(u=c.videoPubResultArr.find(function(e){return e.track.getTrackId()===i.id}),l=(u||{}).publication,"ok"===n&&l?l.initInner(r):"ok"!==n&&(u.error=Pe(u.track,n)));case 1:case"end":return e.stop()}},e)}),o.s();case 3:if((a=o.n()).done){t.next=5;break}return t.delegateYield(u(),"t0",4);case 4:t.next=3;break;case 5:t.next=7;break;case 6:t.prev=6,l=t.catch(2),o.e(l);case 7:return t.prev=7,o.f(),t.finish(7);case 8:e(c);case 9:case"end":return t.stop()}},t,null,[[2,6,7,8]])}));return function(e){return t.apply(this,arguments)}}()).catch(function(e){on.info("batchPublishStart error",e),t(e)}));case 2:case"end":return o.stop()}},o)}));return function(){return o.apply(this,arguments)}}()});return r.addTask(f),v}return Promise.resolve({videoPubResultArr:[],audioPubResult:void 0})},un=function(){var e=n($.mark(function e(t,r){var i,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return o=new Promise(function(e,o){i=function(){var i=n($.mark(function i(){var n,a;return $.wrap(function(i){for(;;)switch(i.prev=i.next){case 0:return n=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}),i.next=1,Fi(r.connection,t);case 1:r.connection.rtcSignaling.batchUnPublish({connectionId:r.connection.id,audio:n,video:a}).then(function(){t.forEach(function(e){e.clear()}),e(void 0)}).catch(o);case 2:case"end":return i.stop()}},i)}));return function(){return i.apply(this,arguments)}}()}),r.connection.addTask(i),e.abrupt("return",o);case 1:case"end":return e.stop()}},e)}));return function(t,r){return e.apply(this,arguments)}}();function dn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(dn=function(){return!!e})()}var ln={audioCodec:"",videoCodec:"",roundTripTime:-1,availableOutgoingBitrate:-1},pn=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,dn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"connectionMetrics",{enumerable:!0,configurable:!0,writable:!0,value:Object.assign({},ln)}),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),i="";return t.forEach(function(t){var n;if(!t.isRemote)if(/local-candidate/i.test(t.type)&&t.id===i)e.Environment.networkType=(null!==(n=t.networkType)&&void 0!==n?n:e.Environment.networkType).replace("vpn","unknown");else if(/candidate-pair/i.test(t.type)&&"succeeded"===t.state)i=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 fn(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 vn(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)?vn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 vn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function mn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(mn=function(){return!!e})()}var hn=function(){function r(i){var a,s,c,u,p,f;o(this,r),s=this,c=l(c=r),a=d(s,mn()?Reflect.construct(c,[],l(s).constructor):c.apply(s,u)),Object.defineProperty(a,"pc",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"state",{enumerable:!0,configurable:!0,writable:!0,value:J.New}),Object.defineProperty(a,"processingExchangeSdp",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"peerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"createPeerConnectionPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"peerConnectionStats",{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,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"createPeerConnectionTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"idToTransceiverMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioTranceiver",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"idToTransceiversMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"mcuAudioTranceivers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"localSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"remoteSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"subSdpFmtpLines",{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,"prevId",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(a,"offerSDP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"clientFailoverTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"audioSfuSsrcs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"enquenTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"direction",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"startSinglePC",{enumerable:!0,configurable:!0,writable:!0,value:(p=n($.mark(function e(){var t,r=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=r.length>0&&void 0!==r[0]&&r[0],"uplink"===a.direction?(a.pc.addTransceiver("audio",{direction:"sendonly"}),a.pc.addTransceiver("video",{direction:"sendonly"})):(a.mcuAudioStream=null,a.mcuAudioTranceiver=a.pc.addTransceiver("audio",{direction:"recvonly"}),a.pc.addTransceiver("video",{direction:"recvonly"})),t&&$i(a),e.next=1,a.exchangeSdpForCreatePc(t);case 1:a.state=J.Idle,a.enquenTask.start();case 2:case"end":return e.stop()}},e)})),function(){return p.apply(this,arguments)})}),Object.defineProperty(a,"onIceGatheringStateChange",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.target.iceGatheringState;a.logger.info("connectionId:".concat(a.id," ice gathering state: ").concat(t))}}),Object.defineProperty(a,"exchangeSdpForCreatePc",{enumerable:!0,configurable:!0,writable:!0,value:(f=n($.mark(function r(){var i,o,s,c,u,d,l,p,f,v=arguments;return $.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return i=v.length>0&&void 0!==v[0]&&v[0],a.processingExchangeSdp=!0,r.prev=1,r.next=2,a.pc.createOffer();case 2:return o=r.sent,a.logger.info("connectionId:".concat(a.id," origin offer"),o),i&&(o.sdp=t.write(Ji(a.localSDP,t.parse(o.sdp)))),s=zi(o.sdp,a),a.offerSDP=s,o={type:"offer",sdp:t.write(s)},r.next=3,a.pc.setLocalDescription(o);case 3:return a.logger.info("connectionId:".concat(a.id," set local sdp success")),c={direction:"downlink"!==a.direction?"in":"out",sdpOffer:o.sdp,connectionId:a.id,isFailover:i,optionsJsonStr:JSON.stringify({supportCVO:1})},i&&((u=t.parse(o.sdp)).media=u.media.slice(0,2),u.groups=[{mids:"0 1",type:"BUNDLE"}],c.sdpOffer=t.write(u)),d=function(){var t=n($.mark(function t(){var r,i,n,o;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,"connected"===(null===(r=a.sessionManager)||void 0===r||null===(r=r.serviceManager)||void 0===r||null===(r=r.client)||void 0===r?void 0:r.connectionState)){t.next=1;break}throw new Error("signaling disconnected");case 1:if(c.isFailover||!a.prevId){t.next=3;break}return t.next=2,a.stopSinglePC(!0);case 2:a.id="".concat(a.direction,"_").concat(e.createUuid()),c.connectionId=a.id;case 3:return a.prevId=a.id,t.next=4,a.rtcSignaling.createPeerConnection(c);case 4:return i=t.sent,n=i.sdpAnswer,a.logger.info("connectionId:".concat(a.id," receive answer success")),t.abrupt("return",n);case 5:throw t.prev=5,o=t.catch(0),a.logger.error("connectionId:".concat(a.id," signal createpc failed: ").concat(o)),o;case 6:case"end":return t.stop()}},t,null,[[0,5]])}));return function(){return t.apply(this,arguments)}}(),r.next=4,Ge({fn:d,times:3,interval:2e3});case 4:return l=r.sent,p=Ki(l,a,i),r.next=5,a.pc.setRemoteDescription({sdp:p,type:"answer"});case 5:r.next=7;break;case 6:return r.prev=6,f=r.catch(1),a.logger.error("connectionId:".concat(a.id," Failed to exchangeSDP. Message: ").concat(f.message)),a.fireEndedEvent(),r.abrupt("return",Promise.reject(f));case 7:return r.prev=7,a.processingExchangeSdp=!1,r.finish(7);case 8:case"end":return r.stop()}},r,null,[[1,6,7,8]])})),function(){return f.apply(this,arguments)})}),a.pc=null;var v=i.direction,m=i.sessionManager;return a.rtcSignaling=m.serviceManager.rtcSignaling,a.sessionManager=m,a.reporter=m.reporter,a.logger=a.reporter.getLoggerWithPrefix("[rtc-peerconn]"),a.enquenTask=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],r=0,i=!1,n=function(){for(;r<e&&t.length;){r++;var i=t.shift();i&&i().finally(function(){r--,n()})}};return{add:function(e){t.push(e),i&&n()},start:function(){i=!0,n()}}}(),a.subSdpFmtpLines=[],a.direction=v,a.idToTransceiverMap=new Map,a.idToTransceiversMap=new Map,a.createPeerConnection(),a.id="".concat(a.direction,"_").concat(e.createUuid()),a}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.rtcSignaling.closePeerConnection({connectionId:this.id,direction:"downlink"===this.direction?"out":"in"})}},{key:"closePeerConnection",value:function(){this.pc&&(this.logger.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?be.audioSFU?this.emit("track",t,r[0]):this.mcuAudioStream=new MediaStream([t]):this.emit("track",t)}},{key:"fireEndedEvent",value:function(){this.state!==J.Ended&&(this.state=J.Ended,this.emit("ended"))}},{key:"onIceConnectionStateChange",value:function(){var e=this.pc.iceConnectionState;this.logger.info("connectionId:".concat(this.id," ICE connection state changed to ").concat(e))}},{key:"onIceCandidate",value:function(e){var t,r=(t=null==e?void 0:e.candidate)?{address:t.address,candidate:t.candidate,component:t.component,foundation:t.foundation,port:t.port,priority:t.priority,protocol:t.protocol,relatedAddress:t.relatedAddress,relatedPort:t.relatedPort,relayProtocol:t.relayProtocol,sdpMLineIndex:t.sdpMLineIndex,sdpMid:t.sdpMid,tcpType:t.tcpType,type:t.type,usernameFragment:t.usernameFragment}:t;this.logger.info("connectionId:".concat(this.id," onIceCandidate"),r)}},{key:"clearPcForReoffer",value:(i=n($.mark(function t(){var r;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.state!==J.New){t.next=1;break}return t.abrupt("return",Promise.reject());case 1:return this.logger.info("connectionId:".concat(this.id,": start client reoffer")),t.prev=2,t.next=3,this.stopSinglePC(!0);case 3:this.removeAllListeners(),t.next=5;break;case 4:t.prev=4,r=t.catch(2),this.logger.info("connectionId:".concat(this.id," client reoffer close failed ").concat(e.tryJsonStringify(r)));case 5:this.closePeerConnection();case 6:case"end":return t.stop()}},t,this,[[2,4]])})),function(){return i.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.logger.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!==J.New&&(t.logger.info("connectionId:".concat(t.id,": emit reoffer")),t.emit("reoffer"))},1e3)):"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.serviceManager.iceConfig,r=t.username,i=t.password,n=t.port,o=t.iceServerList,a={bundlePolicy:"max-bundle",iceTransportPolicy:"all",sdpSemantics:"unified-plan"};if(o.length){var s,c=[],u=fn(o);try{for(u.s();!(s=u.n()).done;){var d=s.value;c.push("turn:".concat(d,":").concat(n,"?transport=udp"),"turn:".concat(d,":").concat(n,"?transport=tcp"))}}catch(e){u.e(e)}finally{u.f()}e.Environment.isFirefox()&&c.splice(4,2),a.iceServers=[{urls:c,username:r,credential:i}]}return this.logger.info("PeerConnectionConfig",a),a}},{key:"createPeerConnection",value:function(){var t=this;this.pc?this.logger.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.processingExchangeSdp||(t.logger.info("connectionId:".concat(t.id,": emit reoffer")),t.emit("reoffer"))},be.connectPcTimeoutMs))}},{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.onicecandidate=function(t){e.onIceCandidate(t)},this.pc.onconnectionstatechange=function(){e.onConnectionStateChange()},this.pc.onicegatheringstatechange=function(t){e.onIceGatheringStateChange(t)},this.monitor=new pn(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:"reoffer",value:function(){return this.state===J.New?Promise.reject():(this.logger.info("connectionId:".concat(this.id," start reoffer")),this.closePeerConnection(),this.idToTransceiverMap=new Map,this.idToTransceiversMap=new Map,this.createPeerConnection(),this.state=J.New,this.startSinglePC(!0))}},{key:"handleHighProfileFallback",value:function(){be.downlinkForbidHighProfile=!0,this.logger.info("connectionId:".concat(this.id," start reoffer for disable highProfile")),this.emit("reoffer")}},{key:"handleVideoSubStucked",value:function(e){this.logger.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 i}();function gn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(gn=function(){return!!e})()}var bn=function(){function t(r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,gn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"_micAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"_screenAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"mixedAudioTrackResult",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(i,"publication",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"serviceManager",{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,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"trackMediaType",{enumerable:!0,configurable:!0,writable:!0,value:"audio"}),Object.defineProperty(i,"audioContext",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"selfMicMutedProperty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"isPublished",{enumerable:!0,configurable:!0,writable:!0,value:function(){return!!i.publication}}),Object.defineProperty(i,"setPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(e){i.logger.info("setPublication",null==e?void 0:e.id),i.publication=e}}),Object.defineProperty(i,"getPublication",{enumerable:!0,configurable:!0,writable:!0,value:function(){return i.publication}}),Object.defineProperty(i,"micTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:i._audioTrackInnerEventHandler.bind(i,exports.AudioSourceInfo.MIC)}),Object.defineProperty(i,"screenAudioTrackEventHandler",{enumerable:!0,configurable:!0,writable:!0,value:i._audioTrackInnerEventHandler.bind(i,exports.AudioSourceInfo.SCREENCAST)}),Object.defineProperty(i,"updateMixedAudioTrackToPub",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e,t,r,n,o,a,s;i.logger.info("updateMixTrack",null===(e=i._micAudioTrack)||void 0===e?void 0:e.getTrackId(),null===(t=i._screenAudioTrack)||void 0===t?void 0:t.getTrackId()),null===(r=i.mixedAudioTrackResult)||void 0===r||null===(r=r.mixedTrack)||void 0===r||r.stop(),i.mixedAudioTrackResult=i.mixAudioTracks(null===(n=i._micAudioTrack)||void 0===n?void 0:n.getMediaStreamTrack(),null===(o=i._screenAudioTrack)||void 0===o?void 0:o.getMediaStreamTrack()),null===(a=i.publication)||void 0===a||a.replaceTrack(null===(s=i.mixedAudioTrackResult)||void 0===s?void 0:s.mixedTrack)}}),Object.defineProperty(i,"clear",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;i.logger.info("clear"),null===(e=i.mixedAudioTrackResult)||void 0===e||null===(e=e.mixedTrack)||void 0===e||e.stop(),i._micAudioTrack=null,i._screenAudioTrack=null,i.publication=void 0}}),Object.defineProperty(i,"getMediaStreamTrack",{enumerable:!0,configurable:!0,writable:!0,value:function(){var e;return(null===(e=i.mixedAudioTrackResult)||void 0===e?void 0:e.mixedTrack)||null}}),i.logger=r.reporter.getLoggerWithPrefix("[rtc-mixedAudioTrack]"),i.serviceManager=r,i._trackId="audio_".concat(e.createUuid(6)),i}return f(t,e.EventEmitter),u(t,[{key:"getTrackId",value:function(){return this._trackId}},{key:"getScreenAudioTrack",value:function(){return this._screenAudioTrack}},{key:"setScreenAudioTrack",value:function(e){var t,r,i;(this.logger.info("setScreenAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._screenAudioTrack)||void 0===t||t.off(de,this.screenAudioTrackEventHandler),this._screenAudioTrack=e,null===(r=this._screenAudioTrack)||void 0===r||r.on(de,this.screenAudioTrackEventHandler),e)?e.muted||(this.notifyScreenAudioEnabled(!0),null===(i=this.publication)||void 0===i||i.unmute()):this.notifyScreenAudioEnabled(!1)}},{key:"getMicAudioTrack",value:function(){return this._micAudioTrack}},{key:"setMicAudioTrack",value:function(e){var t,r;this.logger.info("setMicAudioTrack",null==e?void 0:e.getTrackId()),null===(t=this._micAudioTrack)||void 0===t||t.off(de,this.micTrackEventHandler),this._micAudioTrack=e,null===(r=this._micAudioTrack)||void 0===r||r.on(de,this.micTrackEventHandler),this._micAudioTrack&&(this._micAudioTrack.muted&&!this.selfMicMutedProperty?(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0)):!this._micAudioTrack.muted&&this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)))}},{key:"_audioTrackInnerEventHandler",value:function(e,t){if("localMixedAudioReplaceTrack"===t)this.updateMixedAudioTrackToPub();else if("stop"===t){var r,i,n;if(e===exports.AudioSourceInfo.MIC?this.setMicAudioTrack(null):this.setScreenAudioTrack(null),this.updateMixedAudioTrackToPub(),null===(r=this.mixedAudioTrackResult)||void 0===r||!r.mixedTrack)if(this.logger.warn("mixedAudioTrackResult is null, stop pub audio, pubid=",null===(i=this.publication)||void 0===i?void 0:i.id),this.publication)null===(n=this.publication)||void 0===n||n.stop(),this.publication=null}else if("mute"===t){e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!1):this.selfMicMutedProperty||(this.setSelfMicMutedProperty(!0),this.notifyMicDeviceMuted(!0));var o=e===exports.AudioSourceInfo.MIC?this._screenAudioTrack:this._micAudioTrack;o&&!o.muted&&o.enabled||this.publication.mute()}else"unmute"===t?(e===exports.AudioSourceInfo.SCREENCAST?this.notifyScreenAudioEnabled(!0):this.selfMicMutedProperty&&(this.setSelfMicMutedProperty(!1),this.notifyMicDeviceMuted(!1)),this.publication.unmute()):this.logger.info("unhandled action",t)}},{key:"setSelfMicMutedProperty",value:function(e){this.selfMicMutedProperty=e}},{key:"notifyMicDeviceMuted",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({mute_audio_record:e?1:0}))}},{key:"notifyScreenAudioEnabled",value:function(e){return this.serviceManager.rtcUserManager.notifyParticipantProperties(JSON.stringify({enable_sys_audio:e?1:0}))}},{key:"mixAudioTracks",value:function(e,t){var r;if(!e&&!t)return null;var i=it();this.audioContext=i;var n=i.createMediaStreamDestination();return e&&i.createMediaStreamSource(new MediaStream([e])).connect(n),t&&i.createMediaStreamSource(new MediaStream([t])).connect(n),{mixedTrack:null===(r=n.stream.getAudioTracks())||void 0===r?void 0:r[0],isOriginTrack:!1}}}])}();function yn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function kn(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){X(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 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 Pn(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)?Pn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Pn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Tn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Tn=function(){return!!e})()}var wn=2e3,En=function(){function t(e,r){var i,a,s,c,u,p,f;return o(this,t),a=this,s=l(s=t),i=d(a,Tn()?Reflect.construct(s,[],l(a).constructor):s.apply(a,c)),Object.defineProperty(i,"client",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(i,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"networkQualityInterval",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"lastChannelNetworkQuality",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"uplink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"downlink",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamIdToSessionId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"mixedLocalAudioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"republishPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"resubscribePromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"handleRepublish",{enumerable:!0,configurable:!0,writable:!0,value:(u=n($.mark(function e(){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:i.republishPromise=i._handleRepub(),i.republishPromise.finally(function(){i.republishPromise=null});case 1:case"end":return e.stop()}},e)})),function(){return u.apply(this,arguments)})}),Object.defineProperty(i,"handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(p=n($.mark(function e(){var t,r=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=r.length>0&&void 0!==r[0]&&r[0],i.resubscribePromise=i._handleResubscribe(t),i.resubscribePromise.finally(function(){i.resubscribePromise=null});case 1:case"end":return e.stop()}},e)})),function(){return p.apply(this,arguments)})}),Object.defineProperty(i,"_handleResubscribe",{enumerable:!0,configurable:!0,writable:!0,value:(f=n($.mark(function e(){var t,r,n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T,w,E,I,M,O,R,A,x,C,_,D,j,L,N,V,F,U,G,B=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r=B.length>0&&void 0!==B[0]&&B[0],i.logger.info("handle resub fromServer=",r),n=r?"server":"client",o=[],a=Sn(i.sessions.values());try{for(a.s();!(s=a.n()).done;)(c=s.value)instanceof bi&&c.state===Y.Processing&&(u=null,c.stream.media.video?(d=i.serviceManager.rtcUserManager.users.get(c.uid),u="camera"===c.stream.media.video.source?null==d?void 0:d.videoTrack:null==d?void 0:d.auxiliaryTrack):c.stream.media.audio?u=i.serviceManager.remoteAudioTrack:i.logger.error("unknown media type for resub",c.stream),o.push({stream:c.stream,uid:c.uid,targetMediaType:c.targetMediaType,resolutionInfo:c.userConfigResolution,session:c,track:u}))}catch(e){a.e(e)}finally{a.f()}if(l=o.map(function(e){return e.uid}).join(),o.length){i.logger.info("resubscribe start ".concat(l)),i.client.emit("media-reconnect-start",i.client.userId),p=Sn(o);try{for(p.s();!(f=p.n()).done;)h=f.value,i.logger.info("emitted sub-media-reconnect-started",null===(v=h.track)||void 0===v?void 0:v.getTrackId()),i.client.emit("sub-media-reconnect-started",null===(m=h.track)||void 0===m?void 0:m.getTrackId())}catch(e){p.e(e)}finally{p.f()}}g=null===(t=i.downlink)||void 0===t?void 0:t.id,b=Date.now(),y=b+45e3,k=!1,S=i.serviceManager.rtcUserManager.currentSelfPid,P=0;case 1:if(!(P<23&&Date.now()<=y)){e.next=10;break}if(!((T=Date.now())<b+P*wn)){e.next=2;break}return e.next=2,Be(b+P*wn-T);case 2:if(i.logger.debug("resub round=".concat(P,", channelconnect=").concat(i.serviceManager.internalChannel.connectionState)),"connected"===i.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",9);case 3:return e.prev=3,i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferStart")),e.next=4,null===(w=i.downlink)||void 0===w?void 0:w.clearPcForReoffer();case 4:if(i.downlink=null,!o.length){e.next=7;break}return e.next=5,i.batchSubscribe(o);case 5:if(E=e.sent,i.serviceManager.rtcUserManager.currentSelfPid===S){e.next=6;break}return i.logger.error("abort resubscribe for selfCurrentPid changed from to",S,i.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 6:I=Sn(E);try{for(I.s();!(M=I.n()).done;)O=M.value,R=O.subscription,A=O.error,R&&!A&&i.handleResubSuccess(R)}catch(e){I.e(e)}finally{I.f()}i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferSuccess")),i.logger.debug("resub round=".concat(P," resubscribe ").concat(l," success")),i.client.emit("media-reconnect-end",l),x=Sn(o);try{for(x.s();!(C=x.n()).done;)j=C.value,i.logger.info("emitted sub-media-reconnect-succeeded",null===(_=j.track)||void 0===_?void 0:_.getTrackId()),i.client.emit("sub-media-reconnect-succeeded",null===(D=j.track)||void 0===D?void 0:D.getTrackId())}catch(e){x.e(e)}finally{x.f()}case 7:return k=!0,e.abrupt("continue",10);case 8:if(e.prev=8,G=e.catch(3),i.logger.debug("resub round=".concat(P," resubscribe failed for"),G),i.serviceManager.rtcUserManager.currentSelfPid===S){e.next=9;break}return i.logger.error("abort resubscribe for selfCurrentPid changed from to",S,i.serviceManager.rtcUserManager.currentSelfPid),e.abrupt("return");case 9:P++,e.next=1;break;case 10:if(!k){if(i.reporter.trace.connectionsEvent(g,"".concat(n,"ReofferFailed")),i.downlink.clearPcForReoffer(),i.downlink=null,o.length){i.client.emit("media-reconnect-end",l),L=Sn(o);try{for(L.s();!(N=L.n()).done;)U=N.value,i.logger.info("emitted sub-media-reconnect-failed",null===(V=U.track)||void 0===V?void 0:V.getTrackId()),i.client.emit("sub-media-reconnect-failed",null===(F=U.track)||void 0===F?void 0:F.getTrackId())}catch(e){L.e(e)}finally{L.f()}}o.forEach(function(e){if(i.removeSession(e.session.id),"audio"===e.session.targetMediaType){var t,r;null===(t=i.serviceManager.remoteAudioTrack)||void 0===t||t.stopPlay(),null===(r=i.serviceManager.remoteAudioTrack)||void 0===r||null===(r=r.getMediaStreamTrack())||void 0===r||r.stop(),i.serviceManager.remoteAudioTrack=null}else{var n,o,a,s,c=i.serviceManager.rtcUserManager.users.get(e.session.uid);"camera"===e.session.stream.media.video.source?(null===(n=c.videoTrack)||void 0===n||n.stopPlay(),null===(o=c.videoTrack)||void 0===o||null===(o=o.getMediaStreamTrack())||void 0===o||o.stop(),c.videoTrack=null):(null===(a=c.auxiliaryTrack)||void 0===a||a.stopPlay(),null===(s=c.auxiliaryTrack)||void 0===s||null===(s=s.getMediaStreamTrack())||void 0===s||s.stop(),c.auxiliaryTrack=null)}})}case 11:case"end":return e.stop()}},e,null,[[3,8]])})),function(){return f.apply(this,arguments)})}),i.serviceManager=r,i.client=e,i.reporter=r.reporter,i.logger=i.reporter.getLoggerWithPrefix("[rtc-sessionMgr]"),i.streamIdToSessionId=new Map,i.sessions=new Map,i.mixedLocalAudioTrack=new bn(r),i.handleMediaMessage=i.handleMediaMessage.bind(i),i.handleServerFailover=i.handleServerFailover.bind(i),i}return f(t,e.EventEmitter),u(t,[{key:"getOrCreatePeerConnection",value:(k=n($.mark(function e(t){var r=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("uplink"!==t){e.next=3;break}if(this.uplink){e.next=2;break}return this.uplink=new hn({direction:t,sessionManager:this}),e.next=1,this.uplink.startSinglePC();case 1:this.uplink.on("reoffer",this.handleRepublish),this.uplink.on("ended",function(){r.uplink=null});case 2:return e.abrupt("return",this.uplink);case 3:if(this.downlink){e.next=5;break}return this.downlink=new hn({direction:t,sessionManager:this}),e.next=4,this.downlink.startSinglePC();case 4:this.downlink.on("reoffer",this.handleResubscribe),this.downlink.on("ended",function(){r.downlink=null});case 5:return e.abrupt("return",this.downlink);case 6:case"end":return e.stop()}},e,this)})),function(e){return k.apply(this,arguments)})},{key:"_handleRepub",value:(y=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m,h,g,b,y,k,S,P,T;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("handle repub"),r=te(this.client.localTracks),this.mixedLocalAudioTrack.clear(),r.length){this.client.emit("media-reconnect-start",this.client.userId),i=Sn(r);try{for(i.s();!(n=i.n()).done;)o=n.value,this.logger.info("emitted pub-media-reconnect-started",o.getTrackId()),this.client.emit("pub-media-reconnect-started",o.getTrackId())}catch(e){i.e(e)}finally{i.f()}}a=null===(t=this.uplink)||void 0===t?void 0:t.id,s=Date.now(),c=s+45e3,u=!1,d=0,d=0;case 1:if(!(d<23&&Date.now()<=c||"disconnected"!==this.serviceManager.internalChannel.connectionState)){e.next=9;break}if(!((l=Date.now())<s+d*wn)){e.next=2;break}return e.next=2,Be(s+d*wn-l);case 2:if(this.logger.debug("repub round=".concat(d,", channelconnect=").concat(this.serviceManager.internalChannel.connectionState)),"connected"===this.serviceManager.internalChannel.connectionState){e.next=3;break}return e.abrupt("continue",8);case 3:return e.prev=3,this.reporter.trace.connectionsEvent(a,"clientReofferStart"),this.logger.info("repub round=".concat(d,", clearPcForReoffer start ").concat(r.map(function(e){return e.trackMediaType}).join())),e.next=4,null===(p=this.uplink)||void 0===p?void 0:p.clearPcForReoffer();case 4:if(this.uplink=null,this.logger.info("repub round=".concat(d,", batchPublish start ").concat(r.map(function(e){return e.trackMediaType}).join())),!r.length){e.next=6;break}return e.next=5,this.batchPublish(r);case 5:this.logger.info("".concat(this.client.userId," batchPublish finished for repub")),this.logger.info("emitted media-reconnect-end",this.client.userId),this.client.emit("media-reconnect-end",this.client.userId),f=Sn(r);try{for(f.s();!(v=f.n()).done;)m=v.value,this.logger.info("emitted pub-media-reconnect-succeeded",m.getTrackId()),this.client.emit("pub-media-reconnect-succeeded",m.getTrackId())}catch(e){f.e(e)}finally{f.f()}case 6:return this.reporter.trace.connectionsEvent(a,"clientReofferSuccess"),u=!0,e.abrupt("continue",9);case 7:e.prev=7,P=e.catch(3),this.logger.error("".concat(this.client.userId," republish failed for"),P);case 8:d++,e.next=1;break;case 9:if(this.logger.info("break from repub loop roundNum, connectionstate",d,this.serviceManager.internalChannel.connectionState),u){e.next=14;break}if(this.reporter.trace.connectionsEvent(a,"clientReofferFailed"),"connected"!==this.serviceManager.internalChannel.connectionState){e.next=13;break}return e.prev=10,this.logger.info("unpub all tracks after repub failed"),e.next=11,this.serviceManager.unpublish(r);case 11:e.next=13;break;case 12:e.prev=12,T=e.catch(10),this.logger.info("err for unpub after repub failed",T);case 13:if(null===(h=this.uplink)||void 0===h||h.clearPcForReoffer(),this.uplink=null,r.length){this.client.emit("media-reconnect-end",this.client.userId),g=Sn(r);try{for(g.s();!(b=g.n()).done;)y=b.value,(k=this.streamIdToSessionId.get(y.getTrackId()))&&(this.logger.info("clear old publication for repub failed",k),null===(S=this.sessions.get(k))||void 0===S||S.clear(),this.sessions.delete(k)),this.logger.info("emitted pub-media-reconnect-failed",y.getTrackId()),this.client.emit("pub-media-reconnect-failed",y.getTrackId())}catch(e){g.e(e)}finally{g.f()}}case 14:case"end":return e.stop()}},e,this,[[3,7],[10,12]])})),function(){return y.apply(this,arguments)})},{key:"handleStuckResubscribe",value:(b=n($.mark(function e(t){var r,i,n,o,a,s,c,u,d,l,p,f;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("connected"===this.serviceManager.internalChannel.connectionState){e.next=1;break}return this.logger.info("ignore for inner not connected"),e.abrupt("return");case 1:r=[],i=Sn(t);try{for(i.s();!(n=i.n()).done;)(o=n.value)instanceof bi&&o.state===Y.Processing&&(r.push({stream:o.stream,uid:o.uid,targetMediaType:o.targetMediaType,resolutionInfo:o.userConfigResolution,session:o,profileFallback:!0}),this.removeSession(o.id))}catch(e){i.e(e)}finally{i.f()}return a=r.map(function(e){return e.uid}).join(),this.client.emit("media-reconnect-start",a),this.logger.info("resubscribe ".concat(a," start")),e.prev=2,e.next=3,this.batchUnscribe(r);case 3:return e.next=4,this.batchSubscribe(r);case 4:s=e.sent,c=Sn(s);try{for(c.s();!(u=c.n()).done;)d=u.value,l=d.subscription,p=d.error,l&&!p&&this.handleResubSuccess(l)}catch(e){c.e(e)}finally{c.f()}this.client.emit("media-reconnect-end",a),e.next=6;break;case 5:e.prev=5,f=e.catch(2),this.logger.debug("".concat(this.client.userId," resubscribe failed for"),f),this.client.emit("media-reconnect-end",a),this.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",this.client.connectionState,"network_error");case 6:case"end":return e.stop()}},e,this,[[2,5]])})),function(e){return b.apply(this,arguments)})},{key:"getSessionByStreamId",value:function(e){return e?this.sessions.get(this.streamIdToSessionId.get(e)):null}},{key:"handleResubSuccess",value:function(e){var t,r=e.uid,i=e.mediaStream,n=(null===(t=e.stream.media.video)||void 0===t?void 0:t.source)===exports.VideoSourceInfo.SCREENCAST,o=i.getAudioTracks()[0],a=i.getVideoTracks()[0],s=o?"audio":n?"screen":"camera";if(this.logger.debug("".concat(r," resubscribe ").concat(s," success")),o&&this.serviceManager.remoteAudioTrack){var c,u;if(be.audioSFU)null===(c=(u=this.serviceManager.remoteAudioTrack).replaceStream)||void 0===c||c.call(u,i);else this.serviceManager.remoteAudioTrack.replaceTrack(o)}else{var d=this.serviceManager.rtcUserManager.remoteUsers.find(function(e){return e.userId===r});a&&null!=d&&d.auxiliaryTrack&&n?d.auxiliaryTrack.replaceTrack(a):a&&null!=d&&d.videoTrack&&!n&&d.videoTrack.replaceTrack(a)}}},{key:"handleServerFailover",value:function(e){var t=this;this.logger.debug("serverFailover",e);var r,i=e.actions,n=Sn(void 0===i?[]:i);try{var o=function(){var e,i,n=r.value,o=n.actionName,a=n.connectionId;if("reoffer"!==o)return 1;if(a===(null===(e=t.uplink)||void 0===e?void 0:e.id)){var s=t.uplink,c=t.client,u=c.userId,d=c.localTracks;t.client.emit("media-reconnect-start",u),t.reporter.trace.connectionsEvent(a,"serverReofferStart"),s.reoffer().then(function(){t.logger.info("".concat(u," republish ").concat(d.map(function(e){return e.trackMediaType}).join()," success")),t.reporter.trace.connectionsEvent(a,"serverReofferSuccess"),t.client.emit("media-reconnect-end",u)}).catch(function(e){t.logger.debug("".concat(t.client.userId," republish failed for"),e),t.reporter.trace.connectionsEvent(a,"serverReofferFailed"),t.serviceManager.rtcSignaling.emit("connection-state-change","disconnected",t.client.connectionState,"network_error")})}else a===(null===(i=t.downlink)||void 0===i?void 0:i.id)&&t.handleResubscribe(!0)};for(n.s();!(r=n.n()).done;)o()}catch(e){n.e(e)}finally{n.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?B.BAD:e>30||t>450?B.POOR:e>20||t>300?B.NORMAL:e>10||t>200?B.GOOD:e>=0||t>=0?B.GREAT:B.UNKNOWN}},{key:"checkChannelNetworkQuality",value:(g=n($.mark(function e(){var t,r=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(0!==(t=te(this.sessions.values())).length){e.next=1;break}return this.emit("network-quality",B.UNKNOWN,B.UNKNOWN),e.abrupt("return");case 1: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=2;break}return this.emit("network-quality",B.DISCONNECTED,B.DISCONNECTED),e.abrupt("return");case 2:Promise.all([this.getLocalVideoStats(),this.getLocalAudioStats(),this.getRemoteAudioStats(),this.getRemoteVideoStats()]).then(function(e){var t=kt(e,4),i=t[0],n=t[1],o=t[2],a=t[3],s=0,c=0,u=0,d=0,l=0,p=0;if(i){var f=i.camera,v=i.auxiliary;f&&(c+=f.sendPacketsLost,s+=f.sendPackets,l=Math.max(l,f.rtt||0)),v&&(c+=v.sendPacketsLost,s+=v.sendPackets,l=Math.max(l,v.rtt||0))}for(var m in n&&(c+=n.sendPacketsLost||0,s+=n.sendPackets||0,l=Math.max(l,n.rtt||0)),o&&(u+=o.receivePacketsLost||0,d+=o.receivePackets||0,p=Math.max(p,o.rtt||0)),a){var h=a[m],g=h.camera,b=h.auxiliary;g&&(u+=g.receivePacketsLost,d+=g.receivePackets,p=Math.max(p,g.rtt||0)),b&&(u+=b.receivePacketsLost,d+=b.receivePackets,p=Math.max(p,b.rtt||0))}var y=-1,k=-1,S={timestamp:Date.now(),totalUplinkPacketsLost:c,totalUplinkPacketsSent:s,totalDownlinkPacketsLost:u,totalDownlinkPacketsRecv:d};if(s){var P,T,w=c-((null===(P=r.lastChannelNetworkQuality)||void 0===P?void 0:P.totalUplinkPacketsLost)||0);if(w<0&&(w=c),S.totalUplinkPacketsSentForLost=(null===(T=r.lastChannelNetworkQuality)||void 0===T?void 0:T.totalUplinkPacketsSentForLost)||0,0!==w){var E;S.totalUplinkPacketsSentForLost=s;var I=s-((null===(E=r.lastChannelNetworkQuality)||void 0===E?void 0:E.totalUplinkPacketsSentForLost)||0);I<0&&(I=s),y=w/I}}if(d){var M,O,R,A,x=u-((null===(M=r.lastChannelNetworkQuality)||void 0===M?void 0:M.totalDownlinkPacketsLost)||0);x<0&&(x=u),S.totalDownlinkPacketsRecvForLost=(null===(O=r.lastChannelNetworkQuality)||void 0===O?void 0:O.totalDownlinkPacketsRecvForLost)||0,null===(R=r.lastChannelNetworkQuality)||void 0===R||R.totalDownlinkPacketsRecvForLost,x&&(u!==((null===(A=r.lastChannelNetworkQuality)||void 0===A?void 0:A.totalDownlinkPacketsLost)||0)&&(S.totalDownlinkPacketsRecvForLost=d),k=x/d)}r.emit("network-quality",r.getNetworkQuality(Math.min(100*y,100),l),r.getNetworkQuality(Math.min(100*k,100),p)),r.lastChannelNetworkQuality=S});case 3:case"end":return e.stop()}},e,this)})),function(){return g.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),this.mixedLocalAudioTrack.getPublication()===r&&this.mixedLocalAudioTrack.clear())}},{key:"batchPublish",value:(h=n($.mark(function e(t,r){var i,n,o,a,s,c,u,d,l,p=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=Date.now(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return n=e.sent,o=te(this.sessions.values()).filter(function(e){return e instanceof an}),e.next=2,cn({uid:this.client.userId,tracks:t,connection:n,labels:r,existedPublications:o,mixedLocalAudioTrack:this.mixedLocalAudioTrack});case 2:a=e.sent,s=te(a.videoPubResultArr),a.audioPubResult&&s.push(a.audioPubResult),c=Sn(s),e.prev=3,d=$.mark(function e(){var t,r,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=u.value,r=t.error,n=t.publication,o=t.track,r?p.reporter.trace.publish(!1,o,"",Date.now()-i):((a=p.streamIdToSessionId.get(o.getTrackId()))&&(p.logger.info("clear old publication before set new one",a),null===(s=p.sessions.get(a))||void 0===s||s.clear(),p.sessions.delete(a)),p.addSession(o.getTrackId(),n),p.reporter.trace.publish(!0,o,n.id,Date.now()-i),p.reporter.trace.publish(!1,o,n.id,Date.now()-i),n.on("ended",function(){p.removeSession(n.id)}));case 1:case"end":return e.stop()}},e)}),c.s();case 4:if((u=c.n()).done){e.next=6;break}return e.delegateYield(d(),"t0",5);case 5:e.next=4;break;case 6:e.next=8;break;case 7:e.prev=7,l=e.catch(3),c.e(l);case 8:return e.prev=8,c.f(),e.finish(8);case 9:case"end":return e.stop()}},e,this,[[3,7,8,9]])})),function(e,t){return h.apply(this,arguments)})},{key:"batchUnPublish",value:(m=n($.mark(function e(t){var r,i=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t.length){e.next=1;break}return this.logger.info("batchUnPublish sessions is empty"),e.abrupt("return",Promise.resolve());case 1:return e.next=2,this.getOrCreatePeerConnection("uplink");case 2:return r=e.sent,e.abrupt("return",un(t,{connection:r}).then(function(){var e,r=Sn(t);try{for(r.s();!(e=r.n()).done;){var n,o,a=e.value;i.streamIdToSessionId.delete(null===(n=a.tracks)||void 0===n||null===(n=n[0])||void 0===n||null===(o=n.getTrackId)||void 0===o?void 0:o.call(n)),i.removeSession(a.id)}}catch(e){r.e(e)}finally{r.f()}}));case 3:case"end":return e.stop()}},e,this)})),function(e){return m.apply(this,arguments)})},{key:"batchSubscribe",value:function(e){var t,r=this,i=Date.now(),o=0,a=function(){var e=n($.mark(function e(t){var i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.getOrCreatePeerConnection("downlink");case 1:return i=e.sent,e.abrupt("return",Pi(t,i).then(function(){var e=n($.mark(function e(i){var n,s,c,u;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:for(n=new Map,s=[],c=0;c<i.length;c++)"RoomBusy"===(null===(u=i[c].error)||void 0===u?void 0:u.message)&&(s.push(t[c]),n.set(s.length-1,c));if(!(s.length&&o<=3)){e.next=3;break}return o++,e.next=1,He(1);case 1:if("connected"!==r.client.connectionState){e.next=3;break}return e.next=2,a(s);case 2:e.sent.forEach(function(e,t){var r=n.get(t);i[r]=e});case 3:return e.abrupt("return",i);case 4:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}()));case 2:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}(),s=Sn(e);try{for(s.s();!(t=s.n()).done;){var c=t.value,u=c.stream,d=c.uid,l=c.resolutionInfo;(null==u?void 0:u.id)&&this.reporter.trace.subscribe({subPhase:"init",capabilities:null==u?void 0:u.media,remoteStreamId:null==u?void 0:u.id,remoteUserId:d,elapse:0,sessionId:"",resolutionInfo:l})}}catch(e){s.e(e)}finally{s.f()}return a(e).then(function(e){var t,n=Sn(e);try{var o=function(){var e=t.value,n=e.error,o=e.subscription,a=e.id,s=e.stream,c=e.uid,u=e.resolutionInfo;if(o){r.reporter.trace.subscribe({subPhase:"success",capabilities:s.media,remoteStreamId:s.id,remoteUserId:c,elapse:Date.now()-i,sessionId:a,resolutionInfo:u});var d,l=r.streamIdToSessionId.get(s.id);if(l)r.logger.info("clear old subscription before set new one",l),null===(d=r.sessions.get(l))||void 0===d||d.clear(),r.sessions.delete(l);r.addSession(s.id,o),o.on("ended",function(){r.logger.info("remove subscription for ended",a),r.removeSession(a)})}n&&(r.logger.error("batchSubscribe error",s,n),(null==s?void 0:s.id)&&r.reporter.trace.subscribe({subPhase:"failed",capabilities:(null==s?void 0:s.media)||{},remoteStreamId:null==s?void 0:s.id,remoteUserId:c,elapse:Date.now()-i,sessionId:"",resolutionInfo:u}))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}return r.logger.info("batchSubscribe result",null==e?void 0:e.map(function(e){var t,r;return{error:null==e?void 0:e.error,uid:null==e?void 0:e.uid,streamId:null==e||null===(t=e.stream)||void 0===t?void 0:t.id,sessionId:null==e||null===(r=e.subscription)||void 0===r?void 0:r.id}})),e})}},{key:"batchUnscribe",value:(v=n($.mark(function e(t){var r,i,n,o,a=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Array(t.length),i=[],n={},t.forEach(function(e,t){var o=e.error,s=e.stream,c=e.session;r[t]={},o?(r[t].error=o,a.logger.error("batchUnscribe error",o,s)):(n[null==s?void 0:s.id]=t,i.push(c))}),e.next=1,this.getOrCreatePeerConnection("downlink");case 1:return o=e.sent,e.abrupt("return",Ti(i,o).then(function(){for(var e=0,t=i;e<t.length;e++){var n=t[e];a.removeSession(n.id)}return r}));case 2:case"end":return e.stop()}},e,this)})),function(e){return v.apply(this,arguments)})},{key:"clear",value:function(){var t,r,i=this;this.sessions.forEach(function(e){i.removeSession(e.id)}),this.mixedLocalAudioTrack.clear(),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.serviceManager.rtcSignaling.off("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.off("serverFailover",this.handleServerFailover)}},{key:"start",value:(p=n($.mark(function e(){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.startNetworkQualityTimer(),e.next=1,this.getOrCreatePeerConnection("uplink");case 1:return this.uplink=e.sent,e.next=2,this.getOrCreatePeerConnection("downlink");case 2:this.downlink=e.sent,this.serviceManager.rtcSignaling.on("media-message",this.handleMediaMessage),this.serviceManager.rtcSignaling.on("serverFailover",this.handleServerFailover);case 3: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",B.DISCONNECTED,B.DISCONNECTED):"connected"!==t.client.connectionState?t.emit("network-quality",B.BAD,B.BAD):"connected"===t.client.connectionState?t.checkChannelNetworkQuality():t.emit("network-quality",B.UNKNOWN,B.UNKNOWN)},2e3,"interval")}},{key:"getLocalAudioStats",value:(c=n($.mark(function e(){var t,r,i,n=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=n.length>0&&void 0!==n[0]?n[0]:"network",i=te(this.sessions.values()).filter(function(e){var t,r;return e instanceof an&&"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=1,Promise.all(i.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=i[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return c.apply(this,arguments)})},{key:"getLocalVideoStats",value:(s=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m,h=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return i=h.length>0&&void 0!==h[0]?h[0]:"network",n=te(this.sessions.values()).filter(function(e){var t;return e instanceof an&&"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=1,Promise.all(n.map(function(e){return e.getMetrics(i)}));case 1: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(";"))||[],i=r.findIndex(function(e){return e.includes("profile-level-id")});return r[i].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:te(new Set(o(a))),downlinkProfile:te(new Set(o(s)))},u=Sn(n),e.prev=2,u.s();case 3:if((d=u.n()).done){e.next=6;break}if(l=d.value,p=l.videoStatsMap.get(i)){e.next=4;break}return e.abrupt("continue",5);case 4:f=l.tracks,v=f[0].source===exports.VideoSourceInfo.SCREENCAST,c[v?"auxiliary":"camera"]=p;case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,m=e.catch(2),u.e(m);case 8:return e.prev=8,u.f(),e.finish(8);case 9:return e.abrupt("return",c);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return s.apply(this,arguments)})},{key:"getRemoteVideoStats",value:(a=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=v.length>0&&void 0!==v[0]?v[0]:"network",r=te(this.sessions.values()).filter(function(e){var t;return e instanceof bi&&"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=1,Promise.all(r.map(function(e){return e.getMetrics(t)}));case 1:i={},n=Sn(r),e.prev=2,n.s();case 3:if((o=n.n()).done){e.next=6;break}if(s=o.value,c=s.videoStatsMap,u=s.uid,d=s.stream,l=c.get(t)){e.next=4;break}return e.abrupt("continue",5);case 4:p=(null===(a=d.media.video)||void 0===a?void 0:a.source)===exports.VideoSourceInfo.SCREENCAST?"auxiliary":"camera",i[u]=kn(kn({},i[u]||{}),{},X({},p,l));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,f=e.catch(2),n.e(f);case 8:return e.prev=8,n.f(),e.finish(8);case 9:return e.abrupt("return",i);case 10:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return a.apply(this,arguments)})},{key:"getRemoteAudioStats",value:(i=n($.mark(function e(){var t,r,i,n=arguments;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=n.length>0&&void 0!==n[0]?n[0]:"network",i=te(this.sessions.values()).filter(function(e){var t;return e instanceof bi&&"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=1,Promise.all(i.map(function(e){return e.getMetrics(r)}));case 1:return e.abrupt("return",(null===(t=i[0])||void 0===t?void 0:t.audioStatsMap.get(r))||{});case 2:case"end":return e.stop()}},e,this)})),function(){return i.apply(this,arguments)})},{key:"handleMediaMessage",value:(r=n($.mark(function e(t){var r,i,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.debug("remote feedback: ",t.payload),r=JSON.parse(t.payload),Array.isArray(r)&&0!==r.length){e.next=1;break}return e.abrupt("return");case 1:i=te(this.sessions.values()).filter(function(e){return e instanceof an&&e.state===Y.Processing&&e.tracks[0].source===exports.VideoSourceInfo.CAMERA}),n=Sn(i),e.prev=2,a=$.mark(function e(){var t,i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=o.value,(i=r.filter(function(e){return e.mid==t.transceiver.mid})).length&&t.applyOptions(i);case 1:case"end":return e.stop()}},e)}),n.s();case 3:if((o=n.n()).done){e.next=5;break}return e.delegateYield(a(),"t0",4);case 4:e.next=3;break;case 5:e.next=7;break;case 6:e.prev=6,s=e.catch(2),n.e(s);case 7:return e.prev=7,n.f(),e.finish(7);case 8:case"end":return e.stop()}},e,this,[[2,6,7,8]])})),function(e){return r.apply(this,arguments)})}]);var r,i,a,s,c,p,v,m,h,g,b,y,k}();function In(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return 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 i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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,i=Array(t);r<t;r++)i[r]=e[r];return i}function On(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(On=function(){return!!e})()}var Rn={name:"name"},An=function(){function t(e){var r,i,n,a;return o(this,t),i=this,n=l(n=t),r=d(i,On()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"serviceManager",{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}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.serviceManager=e,r.logger=r.serviceManager.reporter.getLoggerWithPrefix("[rtc-groupMgr]"),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.serviceManager.rtcUserManager.currentSelfPid,t=new Set;return this.groups.forEach(function(r){var i=r.participants,n=r.id;i.some(function(t){return t.pid===e})&&t.add(n)}),t}},{key:"parseGroup",value:function(e){var t,r=this,i=e.id,n=e.properties,o=e.participants;return{id:i,name:(null==n||null===(t=n.find(function(e){return"name"===e.key}))||void 0===t?void 0:t.value)||"",joined:o.some(function(e){return e.pid===r.serviceManager.rtcUserManager.currentSelfPid}),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.serviceManager.rtcSignaling.on("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.on("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"clear",value:function(){this.listVer=0,this.serviceManager.rtcSignaling.off("group",this.handleGroupEvents),this.serviceManager.rtcSignaling.off("group-list",this.handleGroupListEvents),this.serviceManager.rtcSignaling.off("sync",this.handleSyncEvent),this.groupIds.clear(),this.groups.clear()}},{key:"join",value:function(t){var r=t.publishAudioToGroup,i=void 0===r||r,n=t.groupId,o=t.userData;if(this.joinedIds.has(n))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you were in group already");return this.serviceManager.rtcSignaling.joinGroup({groupId:n,userData:o,autoJoinGroupAudio:!!i,autoLeaveChannelAudio:!0})}},{key:"leave",value:function(t){var r=t.groupId,i=t.publishAudioToChannel,n=void 0===i||i;if(!this.joinedIds.has(r))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"you are not in the group");return this.serviceManager.rtcSignaling.leaveGroup({groupId:r,reasonCode:dr.LEAVE_GROUP_REASON_CODE.NORMAL_LEAVE,autoJoinChannelAudio:n})}},{key:"dismiss",value:function(t){if(!this.groupIds.has(t))throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"group not existed");return this.serviceManager.rtcSignaling.dismissGroup({groupId:t})}},{key:"addUser",value:function(e,t){var r,i=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;i&&!i.find(function(t){return t.pid===e.pid})&&i.push(e)}},{key:"removeUser",value:function(e,t){var r,i=null===(r=this.groups.get(t))||void 0===r?void 0:r.participants;if(i){var n=i.findIndex(function(t){return t.pid===e.pid});n>-1&&i.splice(n,1)}}},{key:"observerAllGroup",value:function(){return this.serviceManager.rtcSignaling.observeAllGroups()}},{key:"unobserverAllGroup",value:function(){return this.serviceManager.rtcSignaling.unobserveAllGroups()}},{key:"setProperties",value:function(e,t){return this.serviceManager.rtcSignaling.setGroupProperties({groupId:e,properties:[t]})}},{key:"handleGroupListEvents",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.ver,i=e.type,n=e.updateOpt;if(this.logger.info("on groupList event:",e),r!==this.listVer+1&&!t||i!==dr.OptType.OPT_TYPE_UPDATE)r>this.listVer+1&&this.syncGroupList();else{var o=n.updateAction,a=n.id;o===dr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID?this.groupIds.add(a):o===dr.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.logger.info("on group event:",e);var i,n=e.id,o=e.ver,a=e.groupInfo,s=e.type,c=e.updateOpt,u=this.groups.get(n);if(s!==dr.OptType.OPT_TYPE_ADD||u){if(s===dr.OptType.OPT_TYPE_REMOVE&&u)this.groups.delete(n),this.emit("group","remove",this.parseGroup(u),u.audioInfo);else if(s===dr.OptType.OPT_TYPE_UPDATE){var d=c.updateAction,l=c.participants;if(u&&(u.ver+1===o||r)){if(d===dr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS){var p,f=u.participants.map(function(e){return e.pid}),v=In(l);try{for(v.s();!(p=v.n()).done;){var m=p.value;f.includes(m.pid)||(u.participants.push(m),this.emit("group","user-join",n,{userId:m.uid,userData:m.userData}))}}catch(e){v.e(e)}finally{v.f()}}else if(d===dr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS){var h=l.map(function(e){return e.pid}),g=te(u.participants);u.participants=u.participants.filter(function(e){return!h.includes(e.pid)}),g.forEach(function(e){h.includes(e.pid)&&t.emit("group","user-leave",n,{userId:e.uid,userData:e.userData})})}else if(d===dr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_LOST)this.logger.info("group ".concat(n," audioStream lost"));else if(d===dr.GroupUpdate.GROUP_UPDATE_AUDIO_STREAM_RECOVER)this.logger.debug("group ".concat(n," audioStream recover"));else if(d===dr.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",n,{key:"set-".concat(Rn[e.key]),value:e.value})});else if(d===dr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES){var b,y=c.properties.map(function(e){return e.key});u.properties=null===(b=u.properties)||void 0===b?void 0:b.filter(function(e){var t=e.key;return!y.includes(t)}),c.properties.forEach(function(e){t.emit("group","info-updated",n,{key:"remove-".concat(Rn[e.key])})})}u.ver=o}else u&&o>u.ver+1&&this.syncGroup(u.id)}}else null==a||null===(i=a.audioInfo)||void 0===i||null===(i=i.audio)||void 0===i||null===(i=i.media)||void 0===i||delete i.video,null==a.ver&&(a.ver=o),this.groups.set(n,a),this.emit("group","add",this.parseGroup(a))}},{key:"syncGroup",value:function(e){var t=this,r=this.groups.get(e);return this.serviceManager.rtcSignaling.syncData({type:dr.DataType.DATA_TYPE_GROUP,id:e,ver:null==r?void 0:r.ver}).then(function(i){var n=i.fullSync.groupData.groupInfos,o=(void 0===n?[]:n)[0];if(o){var a=o.participants,s=o.properties,c=void 0===s?[]:s,u=(null==r?void 0:r.participants)||[],d=new Map(((null==r?void 0:r.properties)||[]).map(function(e){return[e.key,e.value]})),l=u.map(function(e){return e.pid}),p=a.map(function(e){return e.pid}),f=c.filter(function(e){return e.value!==d[e.key]}),v=c.filter(function(e){return!d.has(e.key)}),m=a.filter(function(e){return!l.includes(e.pid)}),h=u.filter(function(e){return!p.includes(e.pid)});m.length&&t.handleGroupEvents({id:e,type:dr.OptType.OPT_TYPE_REMOVE,ver:o.ver,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_ADD_PARTICIPANTS,participants:m}},!0),h.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_REMOVE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_REMOVE_PARTICIPANTS,participants:h}},!0),f.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_SET_PROPERTIES,properties:f}},!0),v.length&&t.handleGroupEvents({id:e,ver:o.ver,type:dr.OptType.OPT_TYPE_UPDATE,updateOpt:{updateAction:dr.GroupUpdate.GROUP_UPDATE_REMOVE_PROPERTIES,properties:v}},!0)}else t.handleGroupEvents({id:e,type:dr.OptType.OPT_TYPE_REMOVE})})}},{key:"batchSyncGroup",value:function(e){var t=this;if(e.length)return this.serviceManager.rtcSignaling.syncDataByIds({type:dr.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.serviceManager.rtcSignaling.syncData({type:dr.DataType.DATA_TYPE_GROUP_LIST,forceFullSync:!0,ver:this.listVer}).then(function(t){var r=t.fullSync,i=r.ver,n=r.groupListData.groupIds,o=void 0===n?[]:n,a=o.filter(function(t){return!e.groupIds.has(t)}),s=te(e.groupIds).filter(function(e){return!o.includes(e)});a.length&&a.forEach(function(t){e.handleGroupListEvents({ver:i,updateOpt:{updateAction:dr.GroupListUpdate.GROUP_LIST_UPDATE_ADD_ID,id:t}},!0)}),s.length&&s.forEach(function(t){e.handleGroupListEvents({ver:i,updateOpt:{updateAction:dr.GroupListUpdate.GROUP_LIST_UPDATE_REMOVE_ID,id:t}},!0)})})}},{key:"handleSyncEvent",value:function(e){var t=this,r=e.groupListVer,i=e.groupVer,n=void 0===i?[]:i;this.listVer<r&&(this.syncGroupList(),this.listVer=r),n.forEach(function(e){var r=e.id,i=e.ver,n=t.groups.get(r);(null==n?void 0:n.ver)<i&&(t.syncGroup(r),n.ver=i)})}}])}();function xn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(xn=function(){return!!e})()}var Cn=function(){function t(e,r){var i,n,a,s;o(this,t),n=this,a=l(a=t),i=d(n,xn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(i,"userId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamMap",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"videoTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"auxiliaryTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"audioTrack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"joinedTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"properties",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"toJSON",{enumerable:!0,configurable:!0,writable:!0,value:function(){return{userId:i.userId,userName:i.userName,hasAuxiliary:i.hasAuxiliary,hasVideo:i.hasVideo,hasAudio:i.hasAudio,joinedTime:i.joinedTime,properties:i.properties,audioMuted:i.audioMuted,auxiliaryMuted:i.auxiliaryMuted,videoMuted:i.videoMuted}}});var c=e.user;return i.userId=c,i.videoTrack=null,i.audioTrack=null,i.auxiliaryTrack=null,i.serviceManager=r,i.joinedTime=Date.now(),i.update(e),i}return f(t,e.EventEmitter),u(t,[{key:"relatedStreams",get:function(){var e=this;return te(this.serviceManager.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,i=e.media;return"active"!==(null==i||null===(t=i.audio)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.audio)||void 0===r?void 0:r.source)===exports.AudioSourceInfo.MIC})}},{key:"auxiliaryMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,i=e.media;return"active"!==(null==i||null===(t=i.video)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.video)||void 0===r?void 0:r.source)===exports.VideoSourceInfo.SCREENCAST})}},{key:"videoMuted",get:function(){return this.relatedStreams.some(function(e){var t,r,i=e.media;return"active"!==(null==i||null===(t=i.video)||void 0===t?void 0:t.status)&&(null==i||null===(r=i.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 i=t.split("");i[K.UPLINK]=Fe(i[K.UPLINK]),i[K.DOWNLINK]=Fe(i[K.DOWNLINK]),t=i.join("")}t!==(null===(r=this.properties)||void 0===r?void 0:r[ue])&&(this.properties[ue]=t)}},{key:"update",value:function(e){var t=e.id,r=e.propertiesJsonStr,i=e.ver,n=JSON.parse(r||"{}");this.id=t,this.userName=n.__nick,this.version=i;var o=this.properties||{};this.properties=n,this.updateNetworkOfUser(n[ue]),!n.hasOwnProperty("mute_audio_record")||void 0!==o.mute_audio_record&&n.mute_audio_record===o.mute_audio_record||this.serviceManager.client.emit("user-mic-audio-muted",this.userId,!!n.mute_audio_record),!n.hasOwnProperty("enable_sys_audio")||void 0!==o.enable_sys_audio&&n.enable_sys_audio===o.enable_sys_audio||this.serviceManager.client.emit("user-screencast-audio-mixed",this.userId,!!n.enable_sys_audio)}},{key:"updateSubbedVideoTrack",value:function(e,t){var r=t?this.auxiliaryTrack:this.videoTrack,i=JSON.parse(e.stream.info.attributesJsonStr),n=Te(e.mediaStream,"video",this.userId,r);return t?this.auxiliaryTrack=n:this.videoTrack=n,i.mirror&&n.setSourceMirror(i.mirror),n}}])}();function _n(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 Dn(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)?Dn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Dn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(jn=function(){return!!e})()}var Ln=function(){function t(e,r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,jn()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(i,"users",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"currentUid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"currentSelfPid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"streamManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.users=new Map,i.serviceManager=e,i.reporter=e.reporter,i.logger=i.reporter.getLoggerWithPrefix("[rtc-userMgr]"),i.handleEvent=i.handleEvent.bind(i),i.streamManager=r,i}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){var t=this;return e.uniqBy(te(this.users.values()).sort(function(e,t){return e.joinedTime-t.joinedTime}),"userId").filter(function(e){return e.userId&&e.id!==t.currentSelfPid})}},{key:"init",value:function(e,t){var r,i=_n(e);try{for(i.s();!(r=i.n()).done;){var n=r.value,o=new Cn(n,this.serviceManager);this.users.set(n.user,o),t===n.user&&(this.currentUid=n.user)}}catch(e){i.e(e)}finally{i.f()}this.currentSelfPid=t,this.serviceManager.internalChannel.on("user",this.handleEvent)}},{key:"clear",value:function(){this.currentSelfPid="",this.currentUid="",this.users.clear(),this.serviceManager.internalChannel.off("user",this.handleEvent)}},{key:"handleEvent",value:function(e,t,r){var i=this;if(this.logger.info("userEvent ".concat(e," ").concat(JSON.stringify(t))),"join"===e){var n=new Cn(t,this.serviceManager);this.users.set(t.user,n),this.emit("user","join",n)}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}));te(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 i.streamManager.remove(e,!0)});var c=this.users.get(t.user);this.users.delete(t.user),this.emit("user","leave",c);var u=new Cn(t,this.serviceManager);this.users.set(t.user,u),this.emit("user","join",u)}}},{key:"setParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:JSON.stringify(X({},ue,e))})}},{key:"notifyParticipantProperties",value:function(e){return this.serviceManager.rtcSignaling.setParticipantProperties({participantId:this.currentSelfPid,roomId:this.serviceManager.roomId,propertiesJsonStr:e})}}])}();function Nn(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return Vn(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)?Vn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 Vn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Fn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Un(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Fn(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Fn(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function Gn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Gn=function(){return!!e})()}var Bn=function(){function t(e){var r,i,n,a;o(this,t),i=this,n=l(n=t),r=d(i,Gn()?Reflect.construct(n,[],l(i).constructor):n.apply(i,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,"rtcSignaling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(r,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.streams=new Map;var s=e.rtcSignaling,c=e.reporter;return r.rtcSignaling=s,r.reporter=c,r.logger=r.reporter.getLoggerWithPrefix("[rtc-streamMgr]"),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.rtcSignaling.off("stream",this.handleEvent),this.rtcSignaling.off("sync",this.handleSyncEvent)}},{key:"init",value:function(e,t){var r,i=e.find(function(e){return"admin"===e.info.owner&&"mixed"===e.type});null==i||null===(r=i.media)||void 0===r||delete r.video,this.streams=new Map(e.map(function(e){return[e.id,e]})),this.totalVer=t,this.rtcSignaling.on("stream",this.handleEvent),this.rtcSignaling.on("sync",this.handleSyncEvent)}},{key:"add",value:function(t){var r,i=t.id,n=t.info.owner,o=t.media,a=o.video,s=o.audio;if(!this.streams.get(i)){var c=null===(r=t.media)||void 0===r||null===(r=r.video)||void 0===r?void 0:r.source,u=te(this.streams.values()).find(function(e){var t;return e.info.owner===n&&(null===(t=e.media)||void 0===t||null===(t=t.video)||void 0===t?void 0:t.source)===c});u&&c&&this.remove(u.id),this.reporter.trace.streamsEvent(i,"add"),this.streams.set(t.id,t);var d=(null==a?void 0:a.source)===e.VideoSourceInfo.SCREENCAST;if((null==a?void 0:a.source)===e.VideoSourceInfo.CAMERA||d){this.emit("stream","add",{id:i,owner:n,mediaType:"video",auxiliary:d});var l="active"===a.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:i,auxiliary:d,updateStatus:"".concat(l,"-video")})}if((null==s?void 0:s.source)===exports.AudioSourceInfo.MIC||(null==s?void 0:s.source)===exports.AudioSourceInfo.MIXED){this.emit("stream","add",{id:i,owner:n,mediaType:"audio"});var p="active"===s.status?"unmute":"mute";this.emit("stream","update",{owner:n,id:i,auxiliary:!1,updateStatus:"".concat(p,"-audio")})}}}},{key:"remove",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=this.streams.get(t);if(i&&(this.streams.delete(t),r)){this.reporter.trace.streamsEvent(t,"remove");var n=i.media,o=n.video,a=n.audio,s=i.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 te(this.streams.values()).find(function(t){var r,i;return(null===(r=t.media.audio)||void 0===r?void 0:r.trackId)===e||(null===(i=t.media.video)||void 0===i?void 0:i.trackId)===e})}},{key:"handleEvent",value:function(t,r){var i=this,n=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.logger.info("streamEvent",t);var d=this.totalVer;if(c===d+1||c==se||r)if("add"===o){if(!a||!a.media||!a.info)return;this.add(a)}else if("remove"===o)this.remove(n,!0);else if("update"===o){var l=s.field,p=s.streamStatus,f=s.activeStream,v=s.extraValue,m=s.streamVer,h=s.propertiesJsonStr,g=s.highestResolutionLevel,b=this.streams.get(n);if(b){m!==se&&(b.version=m);var y=b.media,k=y.audio,S=y.video,P=b.info.owner;if("audio.status"===l||"video.status"===l){var T,w;"audio.status"===l?(w="audio",k.status=p):"video.status"===l&&(w="video",S.status=p),this.reporter.trace.streamsEvent(n,"".concat(w," ").concat(p));var E="active"===p?"unmute":"mute",I=(null===(T=b.media)||void 0===T||null===(T=T.video)||void 0===T?void 0:T.source)===e.VideoSourceInfo.SCREENCAST;this.emit("stream","update",{owner:P,id:n,updateStatus:"".concat(E,"-").concat(w),auxiliary:I})}else if("activeInput"===l){var M=[f].concat(v||[]).map(function(e){var t;return null===(t=i.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(M),l),this.emit("stream","volumeActive",{owners:M})}else if("properties"==l){var O,R=JSON.parse(h);b.info.attributesJsonStr=JSON.stringify(Un(Un({},JSON.parse(b.info.attributesJsonStr)),R));var A=(null===(O=b.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:n,properties:R,auxiliary:A})}else"highestResolutionLevel"===l&&(b.media.video.highestResolutionLevel=g,this.emit("stream","update",{owner:P,id:n,highestResolutionLevel:g}))}}r||c<=this.totalVer&&c!==se||(c===d+1&&(this.totalVer=c),c>d+1&&!r&&this.sync())}},{key:"sync",value:(r=n($.mark(function e(){var t,r,i,n,o,a,s,c,u,d,l,p,f,v,m=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],r=[],e.next=1,this.rtcSignaling.getStreamsVer({});case 1:i=e.sent,n=i.streamVersions,o=i.totalVer,a=te(this.streams.keys()).filter(function(e){return!e.includes("vad")}),s=Nn(n),e.prev=2,s.s();case 3:if((c=s.n()).done){e.next=6;break}if(u=c.value,d=u.streamId,l=u.streamVer,!d.includes("vad")){e.next=4;break}return e.abrupt("continue",5);case 4:(p=this.streams.get(d))?p&&p.version!==l&&t.push(d):(r.push(d),t.push(d));case 5:e.next=3;break;case 6:e.next=8;break;case 7:e.prev=7,v=e.catch(2),s.e(v);case 8:return e.prev=8,s.f(),e.finish(8);case 9:if(f=n.map(function(e){return e.streamId}),a.filter(function(e){return!f.includes(e)}).forEach(function(e){m.handleEvent({status:"remove",streamId:e,stream:m.streams.get(e),totalVer:o},!0)}),this.reporter.trace.syncEvent("stream",a,f),this.totalVer=o,0!==t.length){e.next=10;break}return e.abrupt("return");case 10:this.rtcSignaling.getStreams({streamIds:t}).then(function(e){var i,n=e.totalVer,o=e.streams,a=new Map,s=Nn(m.streams.values());try{for(s.s();!(i=s.n()).done;){var c=i.value;a.set(c.id,c)}}catch(e){s.e(e)}finally{s.f()}var u,d=Nn(o);try{for(d.s();!(u=d.n()).done;){var l=u.value;m.streams.has(l.id)?m.streams.set(l.id,l.stream):a.set(l.id,l.stream)}}catch(e){d.e(e)}finally{d.f()}for(var p=t.map(function(e){return a.get(e)}).filter(function(e){return!!e}).sort(function(e,t){return e.version-t.version}),f=0;f<p.length;f++){var v=p[f];r.includes(v.id)&&m.handleEvent({status:"add",streamId:v.id,stream:v,totalVer:n},!0)}a.clear(),m.totalVer=n});case 11:case"end":return e.stop()}},e,this,[[2,7,8,9]])})),function(){return r.apply(this,arguments)})},{key:"handleSyncEvent",value:function(e){var t=e.streamsVer;this.totalVer<t&&this.sync()}}]);var r}();function Hn(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 qn(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)?qn(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 qn(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function Wn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Yn(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){X(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 Jn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Jn=function(){return!!e})()}var Qn=function(){function t(i,n){var a,s,c,u;return o(this,t),s=this,c=l(c=t),a=d(s,Jn()?Reflect.construct(c,[],l(s).constructor):c.apply(s,u)),Object.defineProperty(a,"rtcSignaling",{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,"rtcUserManager",{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,"logger",{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,"processingSubParamsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(a,"joinInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(a,"getSubTraceId",{enumerable:!0,configurable:!0,writable:!0,value:function(){return++t.subAcc}}),Object.defineProperty(a,"handleSubscribeParam",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r,i=t.mediaType,n=t.uid,o=t.auxiliary,s=a.getStream(t),c=a.rtcUserManager.users.get(n),u=a.groups.some(function(e){return e.joined}),d="mcu"===n?a.remoteAudioTrack:o?null==c?void 0:c.auxiliaryTrack:null==c?void 0:c.videoTrack,l=[],p=te(a.processingSubParamsMap.values());a.logger.info("queueingSubParams",p,t),p.forEach(function(e){return l.push.apply(l,te(e))});var f=l.find(function(e){return e.uid===n&&e.mediaType===i&&!!e.auxiliary==!!o});return"mcu"===n&&"video"===i||n&&"mcu"!==n&&"audio"===i?r=new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support subscribe mcu audio"):"mcu"===n&&u?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"cannot subscribe mcu while in group"):d||f?r=new e.DingRTCError(e.ErrorCode.SubscribeInvaild,"duplicated subscription"):s||(a.logger.warn("".concat(n," videoTrack not existed")),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted)),{uid:n,user:c,error:r,stream:s,targetMediaType:i,resolutionInfo:"video"!==i||r?null:Ot(a.defaultVideoStreamType,ke(s))}}}),Object.defineProperty(a,"checkUnsubParam",{enumerable:!0,configurable:!0,writable:!0,value:function(t){var r,i=t.mediaType,n=t.uid,o=t.auxiliary,s=a.getStream(t),c=a.rtcUserManager.users.get(n),u="mcu"===n?a.remoteAudioTrack:o?null==c?void 0:c.auxiliaryTrack:null==c?void 0:c.videoTrack;"mcu"===n&&"video"===i||n&&"mcu"!==n&&"audio"===i?(a.logger.warn("only support unsubscribe mcu audio"),r=new e.DingRTCError(e.ErrorCode.InvaildArgument,"only support unsubscribe mcu audio")):s&&u||(a.logger.warn("".concat(n," videoTrack not existing")),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted));var d=a.sessionManager.getSessionByStreamId(null==s?void 0:s.id);return d||(a.logger.warn("no sub session"),r=new e.DingRTCError(e.ErrorCode.SubscribeStreamNotExisted)),{uid:n,user:c,error:r,stream:s,session:d,subMediaType:i,resolutionInfo:"video"!==i||r?null:Ot(a.defaultVideoStreamType,ke(s))}}}),Object.defineProperty(a,"handleJoinResponse",{enumerable:!0,configurable:!0,writable:!0,value:function(e){var t=e.room,r=e.id,i=t.participants,n=t.streams,o=t.streamsVer,s=t.groupList,c=t.groupListVer;a.streamManager.init(n,o),a.groupManager.init(s,c),a.rtcUserManager.init(i,r),a.streamManager.on("stream",a.handleStreamEvent),a.rtcUserManager.on("user",a.handleUserEvent),a.groupManager.on("group",a.handleGroupEvent)}}),a.reporter=n,a.logger=a.reporter.getLoggerWithPrefix("[rtc-svcMgr]"),a.internalChannel=new r.DingRTCChannel({reporter:n,sdkVersion:ae}),a.rtcSignaling=new Kr(a.internalChannel),a.client=i,a.micMixedGroups=new Set,a.groupManager=new An(a),a.streamManager=new Bn(a),a.rtcUserManager=new Ln(a,a.streamManager),a.sessionManager=new En(i,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:"publishedLocalTracks",get:function(){var e=te(this.sessionManager.sessions.values()).filter(function(e){return e.state===Y.Processing&&e instanceof an}),t=new Set;return e.map(function(e){if(e.tracks){var r,i;if((null===(r=e.tracks)||void 0===r?void 0:r[0])instanceof bn){var n=e.tracks[0].getMicAudioTrack();n&&t.add(n);var o=e.tracks[0].getScreenAudioTrack();return void(o&&t.add(o))}(null===(i=e.tracks)||void 0===i?void 0:i[0])&&t.add(e.tracks[0])}}),te(t.values())}},{key:"groups",get:function(){var e=this;return this.groupManager.groupList.map(function(t){return Yn(Yn({},t),{},{audioPublished:e.micMixedGroups.has(t.id)})})}},{key:"handleStreamEvent",value:function(e,t){var r=t.id,i=t.owner,n=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(i),p=this.rtcUserManager.users.get(null==l?void 0:l.user),f=i===this.rtcUserManager.currentSelfPid;if("add"===e&&!f&&p)this.client.emit("user-published",p,n,o);else if("remove"===e&&p&&!f)this.sessionManager.removeSession(void 0,r),"video"===n&&(o&&p.auxiliaryTrack&&(p.auxiliaryTrack.stopPlay(),p.auxiliaryTrack=null),!o&&p.videoTrack&&(p.videoTrack.stopPlay(),p.videoTrack=null)),this.client.emit("user-unpublished",p,n,o);else if("update"===e){if(s)this.client.emit("user-info-updated",(null==p?void 0:p.userId)||this.rtcUserManager.currentUid,s,o);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 m=this.sessionManager.getSessionByStreamId(r);if(!m)return;m.stream.media.video.highestResolutionLevel=u;var h=m.userConfigResolution,g=m.resolutionInfo;if(u>=h.resolutionLevel&&h.resolutionLevel>g.resolutionLevel)m.applyOptions(h,!0);else if(u<h.resolutionLevel){var b=Ot(Rt(u),ke(m.stream));m.applyOptions(b,!0)}}}else if("volumeActive"===e){var y=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",y)}}},{key:"handleGroupEvent",value:function(e,t,r){var i=this;if("add"===e)this.client.emit("group-add",t);else if("remove"===e){var n;if(this.micMixedGroups.delete(t.id),this.logger.info("unsub group for group removed",t),r&&(null===(n=r.audio)||void 0===n?void 0:n.id)===this.subscribedAudioStream){var o=r.audio;this.sessionManager.batchUnscribe([{stream:o,session:this.sessionManager.getSessionByStreamId(o.id),targetMediaType:"audio"}]).then(function(){o.id===i.subscribedAudioStream&&(i.updateSubscribedAudioStream(!1,""),i.remoteAudioTrack.stopPlay(),i.remoteAudioTrack=null)})}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 a=r.key,s=r.value;this.client.emit("group-info-updated",t,a,s)}}},{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):this.logger.warn("unhandled inner rtc user emitted event",e,t)}},{key:"getStream",value:function(t){var r,i=t.groupId,n=t.uid,o=t.auxiliary;if(i){var a,s=this.groupManager.groups.get(i);return null==s||null===(a=s.audioInfo)||void 0===a?void 0:a.audio}var c="mcu"===n?te(this.streamManager.streams.values()):null===(r=this.rtcUserManager.users.get(n))||void 0===r?void 0:r.relatedStreams;return"mcu"===n?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:(m=n($.mark(function e(t){var r,i,n,o,a,s;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return this.logger.info("join",be.gslb[0]),this.sessionManager.mixedLocalAudioTrack.setSelfMicMutedProperty(t.initMicMuted),e.next=1,this.rtcSignaling.join(t,be.gslb[0]);case 1:return i=e.sent,n=i.joinResponse,o=i.iceConfig,null!=(null==(a=this.internalChannel.staticConfig)||null===(r=a.websdkConfig)||void 0===r?void 0:r.simulcast)&&(be.simulcast=null==a||null===(s=a.websdkConfig)||void 0===s?void 0:s.simulcast),this.roomId=n.room.id,Di(n.room.ssrcMask,n.room.ssrcClientSequence),this.reporter.updateCommonInfo({roomId:this.roomId,participantId:n.id}),o&&o.uis&&this.setIceConfig(o.uis),this.sessionManager.start(),this.handleJoinResponse(n),e.abrupt("return",n);case 2:case"end":return e.stop()}},e,this)})),function(e){return m.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.rtcUserManager.clear(),this.streamManager.clear(),this.sessionManager.clear(),this.micMixedGroups.clear(),this.groupManager.clear(),this.subscribedAudioStream="",null===(e=this.remoteAudioTrack)||void 0===e||e.stopPlay(),this.remoteAudioTrack=null,this.iceConfig=null,this.roomId="",this.streamManager.off("stream",this.handleStreamEvent),this.rtcUserManager.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.rtcSignaling.leave()}},{key:"publish",value:(v=n($.mark(function e(t){var r,i,n,o;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=this.micMixedGroups,i=this.groupManager,n=this.groups,o=[],n.some(function(e){return e.joined})?o.push.apply(o,te(te(r).map(function(e){var t;return null===(t=i.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 1:case"end":return e.stop()}},e,this)})),function(e){return v.apply(this,arguments)})},{key:"unpublish",value:(p=n($.mark(function e(t){var r,i,n,o,a,s,c,u=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.republishPromise){e.next=5;break}return this.logger.info("wait for repub before unpublish"),e.prev=1,e.next=2,this.sessionManager.republishPromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unpublish after repub");case 5:return r=t.filter(function(e){return"audio"===e.trackMediaType}),i=t.filter(function(e){return"audio"!==e.trackMediaType}),n=!1,r.length>0&&(o=(this.sessionManager.mixedLocalAudioTrack.getMicAudioTrack()?1:0)+(this.sessionManager.mixedLocalAudioTrack.getScreenAudioTrack()?1:0),r.length>=o?(this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),i.push(this.sessionManager.mixedLocalAudioTrack),n=!0):(r[0].source===exports.AudioSourceInfo.MIC?this.sessionManager.mixedLocalAudioTrack.setMicAudioTrack(null):this.sessionManager.mixedLocalAudioTrack.setScreenAudioTrack(null),this.sessionManager.mixedLocalAudioTrack.updateMixedAudioTrackToPub())),a=new Set(i.map(function(e){return e.getTrackId()})),(s=te(this.sessionManager.sessions.values()).filter(function(e){var t,r;return e instanceof an&&a.has(null===(t=e.tracks)||void 0===t||null===(t=t[0])||void 0===t?void 0:t.getTrackId())&&"video"===(null===(r=e.tracks)||void 0===r||null===(r=r[0])||void 0===r?void 0:r.trackMediaType)})).forEach(function(e){u.reporter.trace.unpublish(e.id)}),c=te(s),n&&(c.push(this.sessionManager.mixedLocalAudioTrack.getPublication()),this.sessionManager.mixedLocalAudioTrack.setPublication(null)),e.abrupt("return",this.sessionManager.batchUnPublish(c));case 6:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return p.apply(this,arguments)})},{key:"updateSubbedRemoteTrack",value:function(e,t){var r=this;if(null==t||!t.mediaStream)return null;var i=this.rtcUserManager.users.get(e.uid);if("audio"===e.mediaType){var n=this.remoteAudioTrack;return this.remoteAudioTrack=Te(t.mediaStream,"audio","mcu",this.remoteAudioTrack),this.updateSubscribedAudioStream(!0,""),n||t.once("audio-first-frame",function(){r.remoteAudioTrack.emit("first-frame-decoded")}),this.remoteAudioTrack}return i.updateSubbedVideoTrack(t,e.auxiliary)}},{key:"batchSubscribe",value:(c=n($.mark(function e(t){var r,i,n,o,a,s=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.map(this.handleSubscribeParam),i=this.getSubTraceId(),this.processingSubParamsMap.set(i,t),e.prev=1,e.next=2,this.sessionManager.batchSubscribe(r);case 2:return n=e.sent,o=[],t.forEach(function(e,t){var r=e.auxiliary,i=e.uid,a=n[t],c=a.error,u=a.subscription;o.push({uid:i,auxiliary:r,error:c,track:s.updateSubbedRemoteTrack(e,u)})}),e.abrupt("return",o);case 3:throw e.prev=3,a=e.catch(1),this.logger.error("batch sub error",a),a;case 4:return e.prev=4,this.processingSubParamsMap.delete(i),e.finish(4);case 5:case"end":return e.stop()}},e,this,[[1,3,4,5]])})),function(e){return c.apply(this,arguments)})},{key:"batchUnsubscribe",value:(s=n($.mark(function e(t){var r,i,n,o,a,s,c,u,d,l,p=this;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.sessionManager.resubscribePromise){e.next=5;break}return this.logger.info("wait for resuball before unsubscribe"),e.prev=1,e.next=2,this.sessionManager.resubscribePromise;case 2:e.next=4;break;case 3:e.prev=3,e.catch(1);case 4:this.logger.info("go unsubscribe after resuball");case 5:r=[],i=Hn(t);try{for(i.s();!(n=i.n()).done;)o=n.value,a=this.checkUnsubParam(o),s=a.session,c=a.stream,u=a.user,d=a.uid,l=a.error,s&&c&&!l&&(this.reporter.trace.unsubscribe({sessionId:s.id,remoteStreamId:c.id,remoteUserId:d}),r.push(Yn({stream:c,user:u,session:s},o)))}catch(e){i.e(e)}finally{i.f()}if(r.length){e.next=6;break}return e.abrupt("return",Promise.resolve());case 6:return e.abrupt("return",this.sessionManager.batchUnscribe(r).then(function(e){for(var t=0,i=r;t<i.length;t++){var n,o=i[t],a=o.mediaType,s=o.user,c=o.auxiliary;if("audio"===a)p.updateSubscribedAudioStream(!1,""),null===(n=p.remoteAudioTrack)||void 0===n||n.stopPlay(),p.remoteAudioTrack=null;else if(c){var u;null===(u=s.auxiliaryTrack)||void 0===u||u.stop(),s.auxiliaryTrack=null}else{var d;null===(d=s.videoTrack)||void 0===d||d.stop(),s.videoTrack=null}}return e}));case 7:case"end":return e.stop()}},e,this,[[1,3]])})),function(e){return s.apply(this,arguments)})},{key:"updateSubscribedAudioStream",value:function(e,t){this.subscribedAudioStream=t,this.emit("suscribedAudio",e,t)}},{key:"subscribeGroup",value:function(t){var r=this,i=this.getStream({groupId:t});if(!i)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:i,uid:t,targetMediaType:"audio"}]).then(function(e){return r.updateSubscribedAudioStream(!0,i.id),r.remoteAudioTrack=Te(e[0].subscription.mediaStream,"audio",t,r.remoteAudioTrack),r.remoteAudioTrack})}},{key:"unsubscribeGroup",value:function(t){var r=this,i=this.getStream({groupId:t});return i?this.subscribedAudioStream!==i.id?Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildState,"you were not subscribed the group")):this.sessionManager.batchUnscribe([{stream:i,session:this.sessionManager.getSessionByStreamId(i.id),targetMediaType:"audio"}]).then(function(){i.id===r.subscribedAudioStream&&(r.updateSubscribedAudioStream(!1,""),r.remoteAudioTrack.stopPlay(),r.remoteAudioTrack=null)}):Promise.reject(new e.DingRTCError(e.ErrorCode.InvaildArgument,"cannot find audio info of the group"))}},{key:"setRemoteStreamType",value:function(e,t,r){this.logger.info("setRemoteStreamType",e,t,r);var i=this.getStream({uid:e,mediaType:"video",auxiliary:r}),n=this.sessionManager.getSessionByStreamId(i.id),o=Ot(t,ke(i));return n.applyOptions(o,!1)}},{key:"joinGroup",value:function(e){var t=this,r=e.groupId,i=e.publishAudioToGroup;return this.groupManager.join(e).then(function(e){t.logger.info("joinGroup response",e);var n=e.joinGroupAudioSuccess;i&&n&&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.rtcSignaling.streamControl({operation:r,streamId:e,data:t})}},{key:"setGroupProperties",value:function(e,t){return this.groupManager.setProperties(e,t)}},{key:"publishToGroup",value:(a=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=!(a.length>1&&void 0!==a[1])||a[1],n=[],null!=r&&n.push(this.groupManager.groups.get(r).audioInfo.label),this.sessionManager.mixedLocalAudioTrack.isPublished()){t.next=1;break}throw this.logger.error("publishToGroup: no published audio track found"),new e.DingRTCError(e.ErrorCode.InvaildState,"no published audio track found");case 1:if(o=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),null==r){t.next=4;break}return t.next=2,this.mixGroupAudio(o.id,n[0],"mix");case 2:if(this.micMixedGroups.add(r),!i){t.next=3;break}return t.next=3,this.mixGroupAudio(o.id,"common","unmix");case 3:t.next=5;break;case 4:return t.next=5,this.mixGroupAudio(o.id,"common","mix");case 5:case"end":return t.stop()}},t,this)})),function(e){return a.apply(this,arguments)})},{key:"unpublishFromGroup",value:(i=n($.mark(function t(r){var i,n,o,a=arguments;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(i=a.length>1&&void 0!==a[1]&&a[1],n=this.groupManager.groups.get(r).audioInfo.label,this.sessionManager.mixedLocalAudioTrack.isPublished()){t.next=1;break}throw this.logger.error("unpublishFromGroup: no published audio track found"),new e.DingRTCError(e.ErrorCode.InvaildState,"no published audio track found");case 1:return o=this.streamManager.getStreamByTrackId(this.sessionManager.mixedLocalAudioTrack.getTrackId()),t.next=2,this.mixGroupAudio(o.id,n,"unmix");case 2:if(this.micMixedGroups.delete(r),!i){t.next=3;break}return t.next=3,this.mixGroupAudio(o.id,"common","mix");case 3:case"end":return t.stop()}},t,this)})),function(e){return i.apply(this,arguments)})}]);var i,a,s,c,p,v,m}();function Kn(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Kn=function(){return!!e})()}Object.defineProperty(Qn,"subAcc",{enumerable:!0,configurable:!0,writable:!0,value:0});var zn={timestamp:-1,maxPlayLevel:-1,maxRecLevel:-1},$n=function(){function e(t){var r,i,a,s,c;return o(this,e),i=this,a=l(a=e),r=d(i,Kn()?Reflect.construct(a,[],l(i).constructor):a.apply(i,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=n($.mark(function e(){var t,i,n,o,a;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=1,r.client.getLocalAudioStats();case 1:return t=e.sent,i=t.audioLevel,e.next=2,r.client.getRemoteAudioStats();case 2:n=e.sent,o=n.audioLevel,a={timestamp:Date.now(),maxRecLevel:Math.min(1,i||0),maxPlayLevel:Math.min(1,Math.max(0,o||0))},r.audioDeviceBufferInfo.timestamp>0&&(r.audioDeviceBufferReport={attr_duration_ms:Ue(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 3: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({},zn),r.client=t,r}return f(e,$r),u(e)}();function Xn(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,i)}return r}function Zn(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Xn(Object(r),!0).forEach(function(t){X(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xn(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function eo(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 to(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)?to(e,t):void 0}}(e))||t){r&&(e=r);var i=0,n=function(){};return{s:n,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:n}}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 to(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function ro(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(ro=function(){return!!e})()}var io=function(){function t(r){var i,n,a,s;return o(this,t),n=this,a=l(a=t),i=d(n,ro()?Reflect.construct(a,[],l(n).constructor):a.apply(n,s)),Object.defineProperty(i,"channelName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"id",{enumerable:!0,configurable:!0,writable:!0,value:e.createUuid(6)}),Object.defineProperty(i,"reporter",{enumerable:!0,configurable:!0,writable:!0,value:e.registerReporter(i.id)}),Object.defineProperty(i,"logger",{enumerable:!0,configurable:!0,writable:!0,value:i.reporter.getLoggerWithPrefix("[rtc-client]")}),Object.defineProperty(i,"serviceManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"monitor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"syncStatTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(i,"clientStatSync",{enumerable:!0,configurable:!0,writable:!0,value:[0,0,0,0,0,0]}),Object.defineProperty(i,"currentClientState",{enumerable:!0,configurable:!0,writable:!0,value:""}),Object.defineProperty(i,"deviceChecker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),i.serviceManager=new Qn(i,i.reporter),i.handleVisibilitychange=i.handleVisibilitychange.bind(i),i.handleNetworkQuality=i.handleNetworkQuality.bind(i),i.handleConnectionChangeEvent=i.handleConnectionChangeEvent.bind(i),i.handlePageUnload=i.handlePageUnload.bind(i),i.init(),i.deviceChecker=null==r?void 0:r.deviceChecker,i}return f(t,e.EventEmitter),u(t,[{key:"remoteUsers",get:function(){return this.serviceManager.rtcUserManager.remoteUsers}},{key:"groups",get:function(){return this.serviceManager.groups}},{key:"userId",get:function(){var e;return(null===(e=this.serviceManager.internalChannel)||void 0===e||null===(e=e.joinInfo)||void 0===e?void 0:e.uid)||""}},{key:"localTracks",get:function(){return this.serviceManager.publishedLocalTracks}},{key:"connectionState",get:function(){var e;return(null===(e=this.serviceManager.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.serviceManager.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,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];var o,a,s,c,u;"network-quality"!==e&&"volume-indicator"!==e&&(o=this.logger).info.apply(o,["client emit event",e].concat(i));return(a="emit",s=this,c=3,u=re(l(t.prototype),a,s),2&c&&"function"==typeof u?function(e){return u.apply(s,e)}:u)([e].concat(i))}},{key:"startPlugin",value:(h=n($.mark(function e(t,r){var i;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.logger.info("startPlugin",t,r),"DeviceChecker"===t){e.next=1;break}return this.logger.error("not supported plugin",t),e.abrupt("return",Promise.reject("not supported plugin"));case 1:if(this.deviceChecker){e.next=2;break}return this.logger.error("deviceChecker should be created in DingRTC.createClient before start"),e.abrupt("return",Promise.reject("plugin not created"));case 2:return e.prev=2,e.abrupt("return",this.deviceChecker.start(r));case 3:return e.prev=3,i=e.catch(2),this.logger.error("startPlugin error",t,r,i),e.abrupt("return",Promise.reject(i));case 4:case"end":return e.stop()}},e,this,[[2,3]])})),function(e,t){return h.apply(this,arguments)})},{key:"join",value:(m=n($.mark(function t(r){var i,n,o=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.logger.info("join",r),t.prev=1,this.addEventListeners(),void 0===r.initMicMuted&&(r.initMicMuted=!0),t.next=2,this.serviceManager.join(r).then(function(t){var i;return o.channelName=r.channel,o.monitor=new $n(o),o.monitor.on("audio-device-buffer",function(e){o.reporter.metric.audioDeviceBuffer(e)}),o.syncStatTimer=e.addTimer(function(){o.sendClientStatToRemote()},2e3,"interval"),{remoteUsers:o.remoteUsers,timeLeft:null===(i=t.room)||void 0===i?void 0:i.timeLeft}}).catch(function(e){throw o.init(),e});case 2:return i=t.sent,t.abrupt("return",i);case 3:return t.prev=3,n=t.catch(1),this.logger.error("join error",r,n),t.abrupt("return",Promise.reject(n));case 4:case"end":return t.stop()}},t,this,[[1,3]])})),function(e){return m.apply(this,arguments)})},{key:"setRemoteDefaultVideoStreamType",value:function(e){this.logger.info("setRemoteDefaultVideoStreamType",e),this.serviceManager.defaultVideoStreamType=e}},{key:"leave",value:function(){this.logger.info("leave"),this.serviceManager.leave(),this.init()}},{key:"publish",value:(v=n($.mark(function t(r){var i,n,o,a,s,c,u,d,l,p,f,v=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if((i=this.logger).info.apply(i,["publish"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),t.prev=1,"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.PublishNotJoinChannel)));case 2:n=(Array.isArray(r)?r:[r]).filter(function(e){return e instanceof Qt&&!v.localTracks.includes(e)}),o=n.concat(this.localTracks),a=X(X(X(X({},"video"+exports.VideoSourceInfo.CAMERA,0),"video"+exports.VideoSourceInfo.SCREENCAST,0),"audio"+exports.AudioSourceInfo.MIC,0),"audio"+exports.AudioSourceInfo.SCREENCAST,0),s=eo(o),t.prev=3,s.s();case 4:if((c=s.n()).done){t.next=6;break}if(u=c.value,a[u.trackMediaType+u.source]++,!(a[u.trackMediaType+u.source]>=2)){t.next=5;break}throw new e.DingRTCError(e.ErrorCode.QuotaLimitExceed,"".concat(u.trackMediaType,"-").concat(u.source," published already"));case 5:t.next=4;break;case 6:t.next=8;break;case 7:t.prev=7,p=t.catch(3),s.e(p);case 8:return t.prev=8,s.f(),t.finish(8);case 9:if(n.length){t.next=10;break}throw new e.DingRTCError(e.ErrorCode.PublishNoStream);case 10:return t.next=11,this.serviceManager.publish(n);case 11:return d=t.sent,t.abrupt("return",d);case 12:return t.prev=12,f=t.catch(1),(l=this.logger).error.apply(l,["publish error"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[f])),t.abrupt("return",Promise.reject(f));case 13:case"end":return t.stop()}},t,this,[[1,12],[3,7,8,9]])})),function(e){return v.apply(this,arguments)})},{key:"unpublish",value:(p=n($.mark(function t(r){var i,n,o,a,s;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if((i=this.logger).info.apply(i,["unpublish param"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})))),t.prev=1,n=Array.isArray(r)?r:[r],r||(n=this.localTracks),this.logger.info("unpublish tracks",n.map(function(e){return e.trackMediaType})),"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 2:return t.next=3,this.serviceManager.unpublish(n);case 3:return o=t.sent,t.abrupt("return",o);case 4:return t.prev=4,s=t.catch(1),(a=this.logger).error.apply(a,["unpub error"].concat(te((Array.isArray(r)?r:[r]).map(function(e){return{mediaType:null==e?void 0:e.trackMediaType,trackId:null==e?void 0:e.getTrackId(),source:null==e?void 0:e.source}})),[s])),t.abrupt("return",Promise.reject(s));case 5:case"end":return t.stop()}},t,this,[[1,4]])})),function(e){return p.apply(this,arguments)})},{key:"subscribe",value:(c=n($.mark(function t(r,i,n){var o,a;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("subscribe",r,i,n),"connected"===this.connectionState){t.next=1;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 1:return t.next=2,this.serviceManager.batchSubscribe([{uid:r,mediaType:i,auxiliary:n}]).then(function(e){var t=e[0],r=t.error,i=t.track;if(r)throw r;return i});case 2:return o=t.sent,t.abrupt("return",o);case 3:return t.prev=3,a=t.catch(0),this.logger.error("subscribe error",r,i,n,a),t.abrupt("return",Promise.reject(a));case 4:case"end":return t.stop()}},t,this,[[0,3]])})),function(e,t,r){return c.apply(this,arguments)})},{key:"batchSubscribe",value:(s=n($.mark(function t(r){var i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("batchSubscribe",r),Array.isArray(r)&&r.length){t.next=1;break}return t.abrupt("return");case 1:if("connected"===this.connectionState){t.next=2;break}throw new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel);case 2:return t.next=3,this.serviceManager.batchSubscribe(r.map(function(e){return Zn(Zn({},e),{},{action:"subscribe"})}));case 3:return i=t.sent,t.abrupt("return",i);case 4:return t.prev=4,n=t.catch(0),this.logger.error("batchSubscribe error",n),t.abrupt("return",Promise.reject(n));case 5:case"end":return t.stop()}},t,this,[[0,4]])})),function(e){return s.apply(this,arguments)})},{key:"unsubscribe",value:(a=n($.mark(function t(r,i,n){var o,a;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.logger.info("unsubscribe",r,i,n),t.prev=1,"connected"===this.connectionState){t.next=2;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 2:return t.next=3,this.serviceManager.batchUnsubscribe([{uid:r,auxiliary:n,mediaType:i}]).then(function(e){var t,r=null==e||null===(t=e[0])||void 0===t?void 0:t.error;if(r)throw r});case 3:return o=t.sent,t.abrupt("return",o);case 4:return t.prev=4,a=t.catch(1),this.logger.error("unsubscribe error",r,i,a),t.abrupt("return",Promise.reject(a));case 5:case"end":return t.stop()}},t,this,[[1,4]])})),function(e,t,r){return a.apply(this,arguments)})},{key:"batchUnsubscribe",value:(i=n($.mark(function t(r){var i,n;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(this.logger.info("batchUnsubscribe",r),t.prev=1,Array.isArray(r)&&r.length){t.next=2;break}return t.abrupt("return");case 2:if("connected"===this.connectionState){t.next=3;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.SubscribeNotJoinChannel)));case 3:return t.next=4,this.serviceManager.batchUnsubscribe(r.map(function(e){return Zn(Zn({},e),{},{action:"unsubscribe"})}));case 4:return i=t.sent,t.abrupt("return",i);case 5:return t.prev=5,n=t.catch(1),this.logger.error("batchUnsubscribe error",r,n),t.abrupt("return",Promise.reject(n));case 6:case"end":return t.stop()}},t,this,[[1,5]])})),function(e){return i.apply(this,arguments)})},{key:"getLocalAudioStats",value:function(){return this.serviceManager.sessionManager.getLocalAudioStats("user")}},{key:"getLocalVideoStats",value:function(){return this.serviceManager.sessionManager.getLocalVideoStats("user")}},{key:"setRemoteVideoStreamType",value:(r=n($.mark(function t(r,i,n){var o,a,s,c=this;return $.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,this.logger.info("setRemoteVideoStreamType",r,i,n),"connected"===this.connectionState){t.next=1;break}return t.abrupt("return",Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)));case 1:if(null!=(o=this.remoteUsers.find(function(e){return e.userId===r}))&&o.relatedStreams){t.next=2;break}return this.logger.info("".concat(r," videoTrack not existed")),t.abrupt("return",Promise.reject("viedoTrack doesnt exiested"));case 2:return t.next=3,this.serviceManager.setRemoteStreamType(r,i,n).then(function(){c.emit("stream-type-changed",r,i,n)});case 3:return a=t.sent,t.abrupt("return",a);case 4:return t.prev=4,s=t.catch(0),this.logger.error("setRemoteVideoStreamType error",r,i,n,s),t.abrupt("return",Promise.reject(s));case 5:case"end":return t.stop()}},t,this,[[0,4]])})),function(e,t,i){return r.apply(this,arguments)})},{key:"getRemoteVideoStats",value:function(){return this.serviceManager.sessionManager.getRemoteVideoStats("user")}},{key:"getRemoteAudioStats",value:function(){return this.serviceManager.sessionManager.getRemoteAudioStats("user")}},{key:"getRemoteNetworkQuality",value:function(){var e={};return this.remoteUsers.forEach(function(t){var r,i,n=t.properties,o=t.userId;e[o]={downlinkNetworkQuality:Number((null==n||null===(r=n[ue])||void 0===r?void 0:r[K.DOWNLINK])||0),uplinkNetworkQuality:Number((null==n||null===(i=n[ue])||void 0===i?void 0:i[K.UPLINK])||0)}}),e}},{key:"handleConnectionChangeEvent",value:function(e,t,r){this.logger.info("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 i=Fe(null,r[K.UPLINK]),n=Fe(null,this.currentClientState[K.UPLINK]),o=Fe(null,r[K.DOWNLINK]),a=Fe(null,this.currentClientState[K.DOWNLINK]);i===n&&o===a||this.serviceManager.rtcUserManager.setParticipantProperties(r).catch(function(r){t.logger.info("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[K.BACKGROUND_MODE]=Number(t))}},{key:"handleNetworkQuality",value:function(e,t){this.clientStatSync[K.UPLINK]=e,this.clientStatSync[K.DOWNLINK]=t,this.emit("network-quality",e,t)}},{key:"handlePageUnload",value:function(e){"connected"===this.connectionState&&(this.logger.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.serviceManager.sessionManager.on("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.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.serviceManager.sessionManager.off("network-quality",this.handleNetworkQuality),this.serviceManager.rtcSignaling.off("connection-state-change",this.handleConnectionChangeEvent)}},{key:"joinGroup",value:function(t){this.logger.info("joinGroup",t);try{if("connected"!==this.connectionState)return Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail));var r=t.userData,i=t.groupId,n=new TextEncoder;if(!i||n.encode(i).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.serviceManager.joinGroup(t)}catch(e){return this.logger.error("joinGroup error",t,e),Promise.reject(e)}}},{key:"leaveGroup",value:function(t){this.logger.info("leaveGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.leaveGroup({groupId:t,publishAudioToChannel:!1})}catch(e){return this.logger.error("leaveGroup error",t,e),Promise.reject(e)}}},{key:"setGroupName",value:function(t,r){this.logger.info("setGroupName",t,r);try{if("connected"!==this.connectionState)return Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail));var i=new TextEncoder;if(!r||i.encode(r).length>64)throw new e.DingRTCError(e.ErrorCode.InvaildArgument,"update group with invalid name");return this.serviceManager.setGroupProperties(t,{key:"name",value:r})}catch(e){return this.logger.error("setGroupName error",t,r,e),Promise.reject(e)}}},{key:"subscribeGroup",value:function(t){this.logger.info("subscribeGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.subscribeGroup(t)}catch(e){return this.logger.error("subscribeGroup error",t,e),Promise.reject(e)}}},{key:"unsubscribeGroup",value:function(t){this.logger.info("unsubscribeGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.unsubscribeGroup(t)}catch(e){return this.logger.error("unsubscribeGroup error",t,e),Promise.reject(e)}}},{key:"mixAudioToGroup",value:function(t,r,i){this.logger.info("mixAudioToGroup",{mediaType:null==t?void 0:t.trackMediaType,trackId:null==t?void 0:t.getTrackId(),source:null==t?void 0:t.source},r,i);try{if("connected"!==this.connectionState)throw new e.DingRTCError(e.ErrorCode.ConnectionConnectFail);if(r){if(this.logger.info("mix audio to group ".concat(i)),null==i&&this.serviceManager.micMixedGroups.size)throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot mix audio to channel while mixing to others group");return this.serviceManager.publishToGroup(i,!0)}if(this.logger.info("unmix audio from group ".concat(i)),!this.serviceManager.micMixedGroups.has(i))throw new e.DingRTCError(e.ErrorCode.InvaildState,"cannot unmix audio from the unmixed group");return this.serviceManager.unpublishFromGroup(i)}catch(e){return this.logger.error("mixAudioToGroup error",{mediaType:null==t?void 0:t.trackMediaType,trackId:null==t?void 0:t.getTrackId(),source:null==t?void 0:t.source},r,i,e),Promise.reject(e)}}},{key:"dismissGroup",value:function(t){this.logger.info("dismissGroup",t);try{return"connected"!==this.connectionState?Promise.reject(new e.DingRTCError(e.ErrorCode.ConnectionConnectFail)):this.serviceManager.dismissGroup(t)}catch(e){return this.logger.error("dismissGroup error",t,e),Promise.reject(e)}}},{key:"register",value:function(e){this.logger.info("register",e),e.attach(this.serviceManager.internalChannel,this.serviceManager)}},{key:"ungister",value:function(e){this.logger.info("ungister",e),e.detach(this.serviceManager.internalChannel)}}]);var r,i,a,s,c,p,v,m,h}(),no=function(){var e=n($.mark(function e(t){var r;return $.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 1:case"end":return e.stop()}},e)}));return function(t){return e.apply(this,arguments)}}();function oo(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(oo=function(){return!!e})()}et();var ao=e.getReporter().getLoggerWithPrefix("[rtc-index]");ao.info("sdk version",ae),ao.info("userAgent",navigator.userAgent),ao.info("href: ".concat(location.href,", in_iframe=").concat(window!==window.parent)),no(ao);var so=new(function(){function t(){var r,i,n,a;if(o(this,t),i=this,n=l(n=t),r=d(i,oo()?Reflect.construct(n,[],l(i).constructor):n.apply(i,a)),Object.defineProperty(r,"VERSION",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),r.VERSION=ae,!ve.checkSupported())return d(r);var s=xe.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(t){ao.info("createClient",null==t?void 0:t.map(function(e){return null==e?void 0:e.pluginName}));var r=null==t?void 0:t.find(function(e){return"DeviceChecker"===(null==e?void 0:e.pluginName)}),i=null==r?void 0:r.createPlugin();return null==i||i.injectLogger(e.getReporter().getLoggerWithPrefix("[rtc-devcheck]")),new io({deviceChecker:i})}},{key:"checkSystemRequirements",value:function(){return ao.info("checkSystemRequirements"),ve.checkSupported()}},{key:"getSupportedCodec",value:function(){return ao.info("getSupportedCodec"),ve.getSupportedCodec()}},{key:"createCameraVideoTrack",value:function(e){return ao.info("createCameraVideoTrack",e),er(e)}},{key:"createMicrophoneAudioTrack",value:function(e){return ao.info("createMicrophoneAudioTrack",e),Zt(e)}},{key:"createCustomVideoTrack",value:function(e){return ao.info("createCustomVideoTrack",e),or(e)}},{key:"createCustomAudioTrack",value:function(e){return ao.info("createCustomAudioTrack",e),ar(e)}},{key:"createScreenVideoTrack",value:function(e){return ao.info("createScreenVideoTrack",e),tr(e)}},{key:"createScreenVideoAndAudioTrack",value:function(e){return ao.info("createScreenVideoAndAudioTrack",e),ir(e)}},{key:"createMicrophoneAndCameraTracks",value:(i=n($.mark(function e(t,r){return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ao.info("createMicrophoneAndCameraTracks",{videoConfig:t,audioConfig:r}),e.abrupt("return",nr(t,r));case 1:case"end":return e.stop()}},e)})),function(e,t){return i.apply(this,arguments)})},{key:"getCameras",value:function(){return ao.info("getCameras"),xe.getCameras()}},{key:"getDevices",value:(r=n($.mark(function e(){var t,r;return $.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return ao.info("start getDevices"),e.prev=1,e.next=2,xe.getDevices();case 2:return t=e.sent,ao.info("getDevices suc",t),e.abrupt("return",t);case 3:return e.prev=3,r=e.catch(1),ao.info("error getDevices ",r),e.abrupt("return",r);case 4:case"end":return e.stop()}},e,null,[[1,3]])})),function(){return r.apply(this,arguments)})},{key:"getPlaybackDevices",value:function(){return ao.info("getPlaybackDevices"),xe.getPlaybackDevices()}},{key:"getMicrophones",value:function(){return ao.info("getMicrophones"),xe.getMicrophones()}},{key:"setLogLevel",value:function(t){console.warn("[dingrtc]: setLogLevel is deprecated"),e.setLogLevel(be._consoleLogLevel),ao.info(" setLogLevel - ignored and hint deprecated",t)}},{key:"setClientConfig",value:function(e){ao.info("setClientConfig",e),be.setClientConfig(e)}}]);var r,i}());Object.defineProperty(exports,"ErrorCodeAndMsgMap",{enumerable:!0,get:function(){return e.ErrorCodeAndMsgMap}}),exports.FALLBACK_SUB_VIDEO_PROFILE={height:360,width:640},exports.default=so;
|