/*! AgoraRTC|BUILD v2.7.0-0-g1b0bbe8 */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("AgoraRTC",[],t):"object"==typeof exports?exports.AgoraRTC=t():e.AgoraRTC=t()}(window,function(){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var o=t[i]={i:i,l:!1,exports:{}};return e[i].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(i,o,function(t){return e[t]}.bind(null,o));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=18)}([function(e,t,n){"use strict";n.r(t);var i=n(6),o=n.n(i),a=n(5),r=n(3),s=n(1),d=0,c="free",u=[],l=[],p=0;setInterval(function(){Object(r.getParameter)("UPLOAD_LOG")&&f.info("console log upload")},9e5);var f=function(){var e,t,n,i,f,m,g="https://".concat(Object(r.getParameter)("LOG_UPLOAD_SERVER"),"/upload/v1"),v=["DEBUG","INFO","WARNING","ERROR","NONE"],S=0,I=function e(t){c="uploading",setTimeout(function(){!function(e,t,n){var i;Array.isArray(e)||(e=[e]),e=e.map(function(e){return{log_item_id:d++,log_level:e.log_level,payload_str:e.payload}}),i={sdk_version:r.VERSION,process_id:Object(s.a)(),payload:JSON.stringify(e)};try{Object(a.c)(g,i,function(e){"OK"===e?t&&t(e):n&&n(e)},function(e){n&&n(e)},{withCredentials:!0})}catch(e){n&&n(e)}}(t,function(){p=0,0!==u.length?(l=u.length<10?u.splice(0,u.length):u.splice(0,10),e(l)):c="free"},function(){setTimeout(function(){e(l)},p++<2?200:1e4)})},3e3)};t=function(){for(var t=[0],n=0;n4?e=4:e<0&&(e=0),S=e},log:e=function(){var e,t=arguments[0],n=arguments;if(n[0]=(e=new Date).toTimeString().split(" ")[0]+":"+e.getMilliseconds()+" Agora-SDK ["+(v[t]||"DEFAULT")+"]:",function(e,t){if(Object(r.getParameter)("UPLOAD_LOG"))try{t=Array.prototype.slice.call(t);var n="";t.forEach(function(e){"object"===o()(e)&&(e=JSON.stringify(e)),n=n+e+" "}),u.push({payload:n,log_level:e}),"free"===c&&(l=u.length<10?u.splice(0,u.length):u.splice(0,10),I(l))}catch(e){}}(t,n),!(t1&&(e="EXECUTOR_INVOKE_".concat(m)),e)return g._sendApiInvoke(o()({},S(),{success:!1,error:e},r&&{states:r()})),u&&u(e);g._sendApiInvoke(o()({},S(),{success:!0},p&&{result:t},r&&{states:r()})),u&&u(null,t)}},e._cachedItems=[],e._cacheInvokeReport=function(t){t.lts||(t.lts=Date.now()),e._cachedItems.push(t),e._cachedItems.length>50&&e._cachedItems.shift()},e._flushInvokeReport=function(t){if(e._cachedItems.length){var n=e._cachedItems;e._cachedItems=[],d.default.debug("Flush cached event reporting:",n.length),n.forEach(function(n,i){n.sid=t,setTimeout(function(){e._sendApiInvoke(n)},5e3+500*i)})}},e._sendApiInvoke=function(t){var n=t.tag,i=t.invokeId,a=t.sid,r=t.name,d=t.result,c=t.states,u=t.options,l=t.error,p=t.success,f=t.apiInvokeTime,m=t.lts,g=Object(s.getParameter)("NOT_REPORT_EVENT");if(!(n&&g instanceof Array&&-1!==g.indexOf(n)))if(e.list[a]){var v=e.list[a],S=v.startTime,I=v.cname,h=v.uid,y=v.cid,_=(m=m||Date.now())-S,b=m-f,E=o()({invokeId:i,sid:a,cname:I,cid:y,lts:m,uid:h,success:p,elapse:_,apiName:r,execElapse:b},void 0!==u&&{options:JSON.stringify(u)},void 0!==c&&{execStates:JSON.stringify(c)},void 0!==l&&{errorCode:JSON.stringify(l)},void 0!==d&&{execResult:JSON.stringify(d)});e.send({type:"io.agora.pb.Wrtc.ApiInvoke",data:E})}else e._cacheInvokeReport(arguments[0])},e._send=function(t){try{var n=[];t&&t.data&&t.data.apiName?n.push(["apiName",""+t.data.apiName]):t&&t.data&&t.data.eventType&&n.push(["eventType",t.data.eventType]);var i=n.map(function(e){return"".concat(e[0],"=").concat(encodeURIComponent(e[1]))}).join("&"),o=-1===e.url.indexOf("?")?"".concat(e.url,"?").concat(i):e.url;Object(c.c)(o,t,null,function(n){var o=-1===e.urlBackup.indexOf("?")?"".concat(e.urlBackup,"?").concat(i):e.urlBackup;Object(c.c)(o,t,null,function(e){},{timeout:1e4})},{timeout:1e4})}catch(e){}},e.sendCache=[],e.sendTimer=null,e.send=function(t){if(e.sendCache.push(t),null===e.sendTimer){return function t(){e.sendTimer=setTimeout(function(){if(0!==e.sendCache.length)return e._send(e.sendCache.shift()),t();e.sendTimer=null},Object(s.getParameter)("EVENT_REPORT_SEND_INTERVAL"))}()}},e}()},function(e,t,n){"use strict";n.r(t),n.d(t,"getBrowserInfo",function(){return I}),n.d(t,"getBrowserVersion",function(){return p}),n.d(t,"getBrowserOS",function(){return f}),n.d(t,"isChrome",function(){return i}),n.d(t,"isSafari",function(){return o}),n.d(t,"isFireFox",function(){return r}),n.d(t,"isOpera",function(){return s}),n.d(t,"isEdge",function(){return a}),n.d(t,"isQQBrowser",function(){return d}),n.d(t,"isWeChatBrowser",function(){return c}),n.d(t,"isLegacyChrome",function(){return g}),n.d(t,"isSupportedPC",function(){return u}),n.d(t,"isSupportedMobile",function(){return l}),n.d(t,"getChromeKernelVersion",function(){return S}),n.d(t,"isChromeKernel",function(){return m});var i=function(){var e=I();return e.name&&"Chrome"===e.name},o=function(){var e=I();return e.name&&"Safari"===e.name},a=function(){var e=I();return e.name&&"Edge"===e.name},r=function(){var e=I();return e.name&&"Firefox"===e.name},s=function(){var e=I();return e.name&&"OPR"===e.name},d=function(){var e=I();return e.name&&"QQBrowser"===e.name},c=function(){var e=I();return e.name&&"MicroMessenger"===e.name},u=function(){var e=f();return"Linux"===e||"Mac OS X"===e||"Mac OS"===e||-1!==e.indexOf("Windows")},l=function(){var e=f();return"Android"===e||"iOS"===e},p=function(){return I().version},f=function(){return I().os},m=function(){return!!navigator.userAgent.match(/chrome\/[\d]./i)};function g(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}var v,S=function(){var e=navigator.userAgent.match(/chrome\/[\d]./i);return e&&e[0]&&e[0].split("/")[1]},I=(v=function(){var e,t=navigator.userAgent,n=t.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];"Chrome"===n[1]&&null!=(e=t.match(/(OPR(?=\/))\/?(\d+)/i))&&(n=e),"Safari"===n[1]&&null!=(e=t.match(/version\/(\d+)/i))&&(n[2]=e[1]),~t.toLowerCase().indexOf("qqbrowser")&&null!=(e=t.match(/(qqbrowser(?=\/))\/?(\d+)/i))&&(n=e),~t.toLowerCase().indexOf("micromessenger")&&null!=(e=t.match(/(micromessenger(?=\/))\/?(\d+)/i))&&(n=e),~t.toLowerCase().indexOf("edge")&&null!=(e=t.match(/(edge(?=\/))\/?(\d+)/i))&&(n=e),~t.toLowerCase().indexOf("trident")&&null!=(e=/\brv[ :]+(\d+)/g.exec(t)||[])&&(n=[null,"IE",e[1]]);var i=void 0,o=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Linux",r:/(Linux|X11)/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(var a in o){var r=o[a];if(r.r.test(navigator.userAgent)){i=r.s;break}}return{name:n[1],version:n[2],os:i}}(),function(){return v})},function(e,t,n){"use strict";t.__esModule=!0;t.BUILD="v2.7.0-0-g1b0bbe8";t.VERSION="2.7.0";t.SUPPORT_RESOLUTION_LIST={"90p_1":[160,90,null,null,null,null],"120p_1":[160,120,15,15,30,65],"120p_3":[120,120,15,15,30,50],"120p_4":[212,120,null,null,null,null],"180p_1":[320,180,15,15,30,140],"180p_3":[180,180,15,15,30,100],"180p_4":[240,180,15,15,30,120],"240p_1":[320,240,15,15,40,200],"240p_3":[240,240,15,15,40,140],"240p_4":[424,240,15,15,40,220],"360p_1":[640,360,15,15,80,400],"360p_3":[360,360,15,15,80,260],"360p_4":[640,360,30,30,80,600],"360p_6":[360,360,30,30,80,400],"360p_7":[480,360,15,15,80,320],"360p_8":[480,360,30,30,80,490],"360p_9":[640,360,15,15,80,800],"360p_10":[640,360,24,24,80,800],"360p_11":[640,360,24,24,80,1e3],"480p_1":[640,480,15,15,20,500,1,5],"480p_2":[640,480,30,30,100,1e3,25,30],"480p_3":[480,480,15,15,100,400],"480p_4":[640,480,30,30,100,750],"480p_6":[480,480,30,30,100,600],"480p_8":[848,480,15,15,100,610],"480p_9":[848,480,30,30,100,930],"480p_10":[640,480,10,10,100,400],"720p_1":[1280,720,15,15,120,1130,1,5],"720p_2":[1280,720,30,30,120,2e3,25,30],"720p_3":[1280,720,30,30,120,1710],"720p_5":[960,720,15,15,120,910],"720p_6":[960,720,30,30,120,1380],"1080p_1":[1920,1080,15,15,120,2080,1,5],"1080p_2":[1920,1080,30,30,120,3e3,25,30],"1080p_3":[1920,1080,30,30,120,3150],"1080p_5":[1920,1080,60,60,120,4780],"1440p_1":[2560,1440,30,30,120,4850],"1440p_2":[2560,1440,60,60,120,7350],"4k_1":[3840,2160,30,30,120,8910],"4k_3":[3840,2160,60,60,120,13500]};t.AUDIO_PROFILE_SETTINGS={speech_low_quality:[!1,!1,!0,!0],speech_standard:[!1,!1,!0,!1],music_standard:[!1,!1,!1,!1],standard_stereo:[!1,!0,!1,!1],high_quality:[!0,!1,!1,!1],high_quality_stereo:[!0,!0,!1,!1],default:[!1,!1,!1,!1]};var i={WEBCS_DOMAIN:["ap-web-1.agora.io","ap-web-2.agoraio.cn"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-3.agora.io","ap-web-4.agoraio.cn"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],AUDIO_CONTEXT:null,LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"webcollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"webcollector-2.agoraio.cn",WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,HTTP_CONNECT_TIMEOUT:5e3,PLAYER_STATE_DEFER:2e3,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],FILEPATH_LENMAX:255,SUBSCRIBE_TCC:!1,PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:1e3,MEDIA_ELEMENT_EXISTS_DEPTH:3,CANDIDATE_TIMEOUT:2e3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3};t.setParameter=function(e,t){return void 0!==i[e]&&(i[e]=t,!0)};t.getParameter=function(e){return void 0!==i[e]?i[e]:null}},function(e,t){function n(){return e.exports=n=Object.assign||function(e){for(var t=1;t=n&&parseInt(i[n])}};if("object"==("undefined"==typeof window?"undefined":o()(window))?(!window.HTMLMediaElement||"srcObject"in window.HTMLMediaElement.prototype?(p=function(e,t){e.srcObject=t},f=function(e){return e.srcObject}):(p=function(e,t){"mozSrcObject"in e?e.mozSrcObject=t:(e._srcObject=t,e.src=t?URL.createObjectURL(t):null)},f=function(e){return"mozSrcObject"in e?e.mozSrcObject:e._srcObject}),a=window.navigator&&window.navigator.getUserMedia):(p=function(e,t){e.srcObject=t},f=function(e){return e.srcObject}),r=function(e,t){p(e,t)},s=function(e,t){p(e,f(t))},"undefined"!=typeof window&&window.navigator)if(navigator.mozGetUserMedia&&window.mozRTCPeerConnection){for(var S in v.log("This appears to be Firefox"),d="firefox",c=v.extractVersion(navigator.userAgent,/Firefox\/([0-9]+)\./,1),u=31,m=mozRTCPeerConnection,g)g[S]=m.prototype[S];if(l=function(e,t){if(c<38&&e&&e.iceServers){for(var n=[],i=0;i0&&"function"==typeof e&&(t?(n=t,t=e,a=[e=null,t,n]):(t=e,a=[e=null,t]));var r=function(e){var t={};return e.result().forEach(function(e){var n={id:e.id,timestamp:e.timestamp,type:e.type};e.names().forEach(function(t){n[t]=e.stat(t)}),t[n.id]=n}),t};if(a.length>=2){return o.apply(this,[function(e){a[1](r(e))},a[0]])}return new Promise(function(t,n){1===a.length&&null===e?o.apply(i,[function(e){t.apply(null,[r(e)])},n]):o.apply(i,[t,n])})},n},["createOffer","createAnswer"].forEach(function(e){var t=webkitRTCPeerConnection.prototype[e];webkitRTCPeerConnection.prototype[e]=function(){var e=this;if(arguments.length<1||1===arguments.length&&"object"===o()(arguments[0])){var n=1===arguments.length?arguments[0]:void 0;return new Promise(function(i,o){t.apply(e,[i,o,n])})}return t.apply(this,arguments)}}),["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(e){var t=webkitRTCPeerConnection.prototype[e];webkitRTCPeerConnection.prototype[e]=function(){var e=arguments,n=this;return new Promise(function(i,o){t.apply(n,[e[0],function(){i(),e.length>=2&&e[1].apply(null,[])},function(t){o(t),e.length>=3&&e[2].apply(null,[t])}])})}});var h=function(e){if("object"!==o()(e)||e.mandatory||e.optional)return e;var t={};return Object.keys(e).forEach(function(n){if("require"!==n&&"advanced"!==n&&"mediaSource"!==n){var i="object"===o()(e[n])?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);var a=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];var r={};"number"==typeof i.ideal?(r[a("min",n)]=i.ideal,t.optional.push(r),(r={})[a("max",n)]=i.ideal,t.optional.push(r)):(r[a("",n)]=i.ideal,t.optional.push(r))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[a("",n)]=i.exact):["min","max"].forEach(function(e){void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[a(e,n)]=i[e])})}}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t};if(a=function(e,t,n){return e.audio&&(e.audio=h(e.audio)),e.video&&(e.video=h(e.video)),v.log("chrome: "+JSON.stringify(e)),navigator.webkitGetUserMedia(e,t,n)},navigator.getUserMedia=a,navigator.mediaDevices||(navigator.mediaDevices={getUserMedia:_,enumerateDevices:function(){return new Promise(function(e){var t={audio:"audioinput",video:"videoinput"};return MediaStreamTrack.getSources(function(n){e(n.map(function(e){return{label:e.label,kind:t[e.kind],deviceId:e.id,groupId:""}}))})})}}),navigator.mediaDevices.getUserMedia){var y=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);navigator.mediaDevices.getUserMedia=function(e){return v.log("spec: "+JSON.stringify(e)),e.audio=h(e.audio),e.video=h(e.video),v.log("chrome: "+JSON.stringify(e)),y(e)}}else navigator.mediaDevices.getUserMedia=function(e){return _(e)};void 0===navigator.mediaDevices.addEventListener&&(navigator.mediaDevices.addEventListener=function(){v.log("Dummy mediaDevices.addEventListener called.")}),void 0===navigator.mediaDevices.removeEventListener&&(navigator.mediaDevices.removeEventListener=function(){v.log("Dummy mediaDevices.removeEventListener called.")}),r=function(e,t){c>=43?p(e,t):void 0!==e.src?e.src=t?URL.createObjectURL(t):null:v.log("Error attaching stream to element.")},s=function(e,t){c>=43?p(e,f(t)):e.src=t.src}}else navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)?(v.log("This appears to be Edge"),d="edge",c=v.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2),u=12):v.log("Browser does not appear to be WebRTC-capable");else v.log("This does not appear to be a browser"),d="not a browser";function _(e){return new Promise(function(t,n){a(e,t,n)})}var b,E={};try{Object.defineProperty(E,"version",{set:function(e){c=e}})}catch(e){}l?b=l:"undefined"!=typeof window&&(b=window.RTCPeerConnection)},function(e,t,n){var i=n(16);e.exports=function(e){for(var t=1;t500?500:t,Date.now()-this.lastTimeGetStats10&&(n=n+"a=fmtp:"+e.slice(u+9,l-1)+" x-google-min-bitrate="+r+"\r\n"),e=e.replace(t[0],n),o.default.debug("["+c+"]Set Video Bitrate - min:"+r+" max:"+s)}return(t=e.match(/m=audio.*\r\n/))&&d&&(n=t[0]+"b=AS:"+d+"\r\n",e=e.replace(t[0],n)),e},e.prototype.reviseOpus=function(e){return e=(e=e.replace(/a=rtpmap:102 opus\/48000\/2/g,"a=rtpmap:111 opus/48000/2")).replace(/m=audio 9 UDP\/TLS\/RTP\/SAVPF 102 0 8 97 13 118 101/g,"m=audio 9 UDP/TLS/RTP/SAVPF 111 0 8 97 13 118 101")},e.prototype.addCandidate=function(e){return e+="a=candidate:2243255435 1 udp 2122194687 192.168.0.1 30000 typ host generation 0 network-id 1\r\n"},e.prototype.sendOffer=function(e){this.config.callback(JSON.stringify({sdp:e.sdp,messageType:"OFFER",tiebreaker:Math.floor(429496723*Math.random()+1)})),this.state=i.OFFER_SENT},e}();t.default=r},function(e,t,n){"use strict";var i=this&&this.__awaiter||function(e,t,n,i){return new(n||(n=Promise))(function(o,a){function r(e){try{d(i.next(e))}catch(e){a(e)}}function s(e){try{d(i.throw(e))}catch(e){a(e)}}function d(e){e.done?o(e.value):new n(function(t){t(e.value)}).then(r,s)}d((i=i.apply(e,t||[])).next())})},o=this&&this.__generator||function(e,t){var n,i,o,a,r={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(o=2&a[0]?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return r.label++,{value:a[1],done:!1};case 5:r.label++,i=a[1],a=[0];continue;case 7:a=r.ops.pop(),r.trys.pop();continue;default:if(!(o=(o=r.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){r=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]>>((3&t)<<3)&255;return o}}},function(e,t){for(var n=[],i=0;i<256;++i)n[i]=(i+256).toString(16).substr(1);e.exports=function(e,t){var i=t||0,o=n;return[o[e[i++]],o[e[i++]],o[e[i++]],o[e[i++]],"-",o[e[i++]],o[e[i++]],"-",o[e[i++]],o[e[i++]],"-",o[e[i++]],o[e[i++]],"-",o[e[i++]],o[e[i++]],o[e[i++]],o[e[i++]],o[e[i++]],o[e[i++]]].join("")}},function(e,t){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){"use strict";t.__esModule=!0;var i="object"==typeof window&&window.RTCPeerConnection,o="object"==typeof window&&window.webkitRTCPeerConnection,a="object"==typeof window&&window.mozRTCPeerConnection;t.createRTCPeerConnection=function(e){var t=i||o||a;return t?new t(e):null}},function(e,t,n){"use strict";n.r(t);var i=n(3),o=n(0),a=n(1),r=function(){var e={dispatcher:{}};return e.dispatcher.eventListeners={},e.addEventListener=function(t,n){void 0===e.dispatcher.eventListeners[t]&&(e.dispatcher.eventListeners[t]=[]),e.dispatcher.eventListeners[t].push(n)},e.hasListeners=function(t){return!(!e.dispatcher.eventListeners[t]||!e.dispatcher.eventListeners[t].length)},e.on=e.addEventListener,e.removeEventListener=function(t,n){var i;-1!==(i=e.dispatcher.eventListeners[t].indexOf(n))&&e.dispatcher.eventListeners[t].splice(i,1)},e.dispatchEvent=function(t){var n;for(n in e.dispatcher.eventListeners[t.type])e.dispatcher.eventListeners[t.type]&&e.dispatcher.eventListeners[t.type].hasOwnProperty(n)&&"function"==typeof e.dispatcher.eventListeners[t.type][n]&&e.dispatcher.eventListeners[t.type][n](t)},e.dispatchSocketEvent=function(t){var n;for(n in e.dispatcher.eventListeners[t.type])e.dispatcher.eventListeners[t.type]&&e.dispatcher.eventListeners[t.type].hasOwnProperty(n)&&"function"==typeof e.dispatcher.eventListeners[t.type][n]&&e.dispatcher.eventListeners[t.type][n](t.msg)},e},s=function(e){var t={};return t.type=e.type,t},d=function(e){var t=s(e);return t.stream=e.stream,t.reason=e.reason,t.msg=e.msg,t},c=function(e){var t=s(e);return t.uid=e.uid,t.attr=e.attr,t.stream=e.stream,t},u=function(e){var t=s(e);return t.msg=e.msg,t},l=function(e){var t=s(e);return t.url=e.url,t.uid=e.uid,t.status=e.status,t.reason=e.reason,t},p=n(2),f=function(){};f.prototype.set=function(e,t){["BatteryLevel"].indexOf(e)>-1&&(this[e]=t)};var m=new function(){var e=r();return e.states={UNINIT:"UNINIT",INITING:"INITING",INITED:"INITED"},e.state=e.states.UNINIT,e.batteryManager=null,e._init=function(t,n){e.state=e.states.INITING,navigator.getBattery?navigator.getBattery().then(function(n){e.batteryManager=n,t&&setTimeout(function(){t()},0)}).catch(function(e){o.default.debug("navigator.getBattery is disabled",e),t&&t()}):(e.state=e.states.INITED,t&&t())},e._getBatteryStats=function(){var t={};return e.batteryManager&&e.batteryManager.level?t.BatteryLevel=Math.floor(100*e.batteryManager.level):t.BatteryLevel="UNSUPPORTED",t},e.getStats=function(t,n){var i=new f,o=e._getBatteryStats();o&&o.BatteryLevel&&i.set("BatteryLevel",o.BatteryLevel),t&&t(i)},e._init(),e},g=n(4),v=n.n(g),S=function(e){var t=r();return t.url=".",t},I=n(8),h={101100:"NO_FLAG_SET",101101:"FLAG_SET_BUT_EMPTY",101102:"INVALID_FALG_SET",101203:"NO_SERVICE_AVIABLE",0:"OK_CODE",5:"INVALID_VENDOR_KEY",7:"INVALID_CHANNEL_NAME",8:"INTERNAL_ERROR",9:"NO_AUTHORIZED",10:"DYNAMIC_KEY_TIMEOUT",11:"NO_ACTIVE_STATUS",13:"DYNAMIC_KEY_EXPIRED",14:"STATIC_USE_DYANMIC_KEY",15:"DYNAMIC_USE_STATIC_KEY"},y={2000:"ERR_NO_VOCS_AVAILABLE",2001:"ERR_NO_VOS_AVAILABLE",2002:"ERR_JOIN_CHANNEL_TIMEOUT",2003:"WARN_REPEAT_JOIN",2004:"ERR_JOIN_BY_MULTI_IP",101:"ERR_INVALID_VENDOR_KEY",102:"ERR_INVALID_CHANNEL_NAME",103:"WARN_NO_AVAILABLE_CHANNEL",104:"WARN_LOOKUP_CHANNEL_TIMEOUT",105:"WARN_LOOKUP_CHANNEL_REJECTED",106:"WARN_OPEN_CHANNEL_TIMEOUT",107:"WARN_OPEN_CHANNEL_REJECTED",108:"WARN_REQUEST_DEFERRED",109:"ERR_DYNAMIC_KEY_TIMEOUT",110:"ERR_NO_AUTHORIZED",111:"ERR_VOM_SERVICE_UNAVAILABLE",112:"ERR_NO_CHANNEL_AVAILABLE_CODE",113:"ERR_TOO_MANY_USERS",114:"ERR_MASTER_VOCS_UNAVAILABLE",115:"ERR_INTERNAL_ERROR",116:"ERR_NO_ACTIVE_STATUS",117:"ERR_INVALID_UID",118:"ERR_DYNAMIC_KEY_EXPIRED",119:"ERR_STATIC_USE_DYANMIC_KE",120:"ERR_DYNAMIC_USE_STATIC_KE",2:"K_TIMESTAMP_EXPIRED",3:"K_CHANNEL_PERMISSION_INVALID",4:"K_CERTIFICATE_INVALID",5:"K_CHANNEL_NAME_EMPTY",6:"K_CHANNEL_NOT_FOUND",7:"K_TICKET_INVALID",8:"K_CHANNEL_CONFLICTED",9:"K_SERVICE_NOT_READY",10:"K_SERVICE_TOO_HEAVY",14:"K_UID_BANNED",15:"K_IP_BANNED",16:"K_CHANNEL_BANNED"},_=["NO_SERVICE_AVIABLE"],b={19:"ERR_ALREADY_IN_USE",10:"ERR_TIMEDOUT",3:"ERR_NOT_READY",9:"ERR_NO_PERMISSION",0:"UNKNOW_ERROR"},E={FAILED:"FAILED",INVALID_KEY:"INVALID_KEY",INVALID_CLIENT_MODE:"INVALID_CLIENT_MODE",INVALID_CLIENT_CODEC:"INVALID_CLIENT_CODEC",CLIENT_MODE_CODEC_MISMATCH:"CLIENT_MODE_CODEC_MISMATCH",WEB_API_NOT_SUPPORTED:"WEB_API_NOT_SUPPORTED",INVALID_PARAMETER:"INVALID_PARAMETER",INVALID_OPERATION:"INVALID_OPERATION",INVALID_LOCAL_STREAM:"INVALID_LOCAL_STREAM",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",INVALID_DYNAMIC_KEY:"INVALID_DYNAMIC_KEY",DYNAMIC_KEY_TIMEOUT:"DYNAMIC_KEY_TIMEOUT",NO_VOCS_AVAILABLE:"NO_VOCS_AVAILABLE",NO_VOS_AVAILABLE:"ERR_NO_VOS_AVAILABLE",JOIN_CHANNEL_TIMEOUT:"ERR_JOIN_CHANNEL_TIMEOUT",NO_AVAILABLE_CHANNEL:"NO_AVAILABLE_CHANNEL",LOOKUP_CHANNEL_TIMEOUT:"LOOKUP_CHANNEL_TIMEOUT",LOOKUP_CHANNEL_REJECTED:"LOOKUP_CHANNEL_REJECTED",OPEN_CHANNEL_TIMEOUT:"OPEN_CHANNEL_TIMEOUT",OPEN_CHANNEL_REJECTED:"OPEN_CHANNEL_REJECTED",REQUEST_DEFERRED:"REQUEST_DEFERRED",STREAM_ALREADY_PUBLISHED:"STREAM_ALREADY_PUBLISHED",STREAM_NOT_YET_PUBLISHED:"STREAM_NOT_YET_PUBLISHED",JOIN_TOO_FREQUENT:"JOIN_TOO_FREQUENT",SOCKET_ERROR:"SOCKET_ERROR",SOCKET_DISCONNECTED:"SOCKET_DISCONNECTED",PEERCONNECTION_FAILED:"PEERCONNECTION_FAILED",CONNECT_GATEWAY_ERROR:"CONNECT_GATEWAY_ERROR",SERVICE_NOT_AVAILABLE:"SERVICE_NOT_AVAILABLE",JOIN_CHANNEL_FAILED:"JOIN_CHANNEL_FAILED",PUBLISH_STREAM_FAILED:"PUBLISH_STREAM_FAILED",UNPUBLISH_STREAM_FAILED:"UNPUBLISH_STREAM_FAILED",SUBSCRIBE_STREAM_FAILED:"SUBSCRIBE_STREAM_FAILED",UNSUBSCRIBE_STREAM_FAILED:"UNSUBSCRIBE_STREAM_FAILED",NO_SUCH_REMOTE_STREAM:"NO_SUCH_REMOTE_STREAM",ERR_FAILED:"1",ERR_INVALID_VENDOR_KEY:"101",ERR_INVALID_CHANNEL_NAME:"102",WARN_NO_AVAILABLE_CHANNEL:"103",WARN_LOOKUP_CHANNEL_TIMEOUT:"104",WARN_LOOKUP_CHANNEL_REJECTED:"105",WARN_OPEN_CHANNEL_TIMEOUT:"106",WARN_OPEN_CHANNEL_REJECTED:"107",WARN_REQUEST_DEFERRED:"108",ERR_DYNAMIC_KEY_TIMEOUT:"109",ERR_INVALID_DYNAMIC_KEY:"110",ERR_NO_VOCS_AVAILABLE:"2000",ERR_NO_VOS_AVAILABLE:"2001",ERR_JOIN_CHANNEL_TIMEOUT:"2002",IOS_NOT_SUPPORT:"IOS_NOT_SUPPORT",WECHAT_NOT_SUPPORT:"WECHAT_NOT_SUPPORT",SHARING_SCREEN_NOT_SUPPORT:"SHARING_SCREEN_NOT_SUPPORT",STILL_ON_PUBLISHING:"STILL_ON_PUBLISHING",LOW_STREAM_ALREADY_PUBLISHED:"LOW_STREAM_ALREADY_PUBLISHED",LOW_STREAM_NOT_YET_PUBLISHED:"LOW_STREAM_ALREADY_PUBLISHED",HIGH_STREAM_NOT_VIDEO_TRACE:"HIGH_STREAM_NOT_VIDEO_TRACE",NOT_FIND_DEVICE_BY_LABEL:"NOT_FIND_DEVICE_BY_LABEL",ENABLE_DUALSTREAM_FAILED:"ENABLE_DUALSTREAM_FAILED",DISABLE_DUALSTREAM_FAILED:"DISABLE_DUALSTREAM_FAILED",PLAYER_NOT_FOUND:"PLAYER_NOT_FOUND",ELECTRON_NOT_SUPPORT_SHARING_SCREEN:"ELECTRON_NOT_SUPPORT_SHARING_SCREEN",BAD_ENVIRONMENT:"BAD_ENVIRONMENT"},T=0,A=function(e){var t=S({});t.id=e.id,t.playerId=T++,t.fit=e.options&&e.options.fit,"contain"!==t.fit&&"cover"!==t.fit&&(t.fit=null),t.url=e.url,t.stream=e.stream.stream,t.elementID=e.elementID,t.setAudioOutput=function(e,n,i){var a=t.video||t.audio;return a?a.setSinkId?void a.setSinkId(e).then(function(){return o.default.debug("["+t.id+"] "+"video ".concat(t.id," setAudioOutput ").concat(e," SUCCESS")),a==t.video&&t.audio?t.audio.setSinkId(e):Promise.resolve()}).then(function(){return o.default.debug("["+t.id+"] "+"audio ".concat(t.id," setAudioOutput ").concat(e," SUCCESS")),n&&n()}).catch(function(e){return o.default.error("["+t.id+"] VideoPlayer.setAudioOutput",e),i&&i(e)}):(o.default.error("["+t.id+"] ",E.WEB_API_NOT_SUPPORTED),i&&i(E.WEB_API_NOT_SUPPORTED)):(o.default.error("["+t.id+"] ",E.PLAYER_NOT_FOUND),i&&i(E.PLAYER_NOT_FOUND))},t.destroy=function(){o.default.debug("destroy ".concat(e.stream.local?"local":"remote"," Player ").concat(t.id)),Object(I.setSrcObject)(t.video,null),Object(I.setSrcObject)(t.audio,null),t.video.pause(),delete t.resizer,clearInterval(t.mediaPlayerTimer),t.mediaPlayerTimer=null,document.getElementById(t.div.id)&&t.parentNode.contains(t.div)&&t.parentNode.removeChild(t.div),["video","audio"].forEach(function(n){t[n];var i=s[n];clearTimeout(i.playDeferTimeout),i.formerMediaState=null;var r={playerId:t.playerId,stateId:i.stateId+1,playDeferTimeout:null,error:!1,status:"aborted",reason:"stop",updatedAt:Date.now()};s[n]=r;var d={type:"player-status-change",playerId:t.playerId,mediaType:n,status:r.status,reason:r.reason,isErrorState:!1};o.default.debug("Media Player Status Change Triggered by destroy()",d),e.stream.dispatchEvent(d),a.b.reportApiInvoke(e.stream.sid,{name:"Stream.playerStatusChange",options:d,tag:"tracer"})()})},t.div=document.createElement("div"),t.div.setAttribute("id","player_"+t.id),e.stream.video?t.div.setAttribute("style","width: 100%; height: 100%; position: relative; background-color: black; overflow: hidden;"):t.div.setAttribute("style","width: 100%; height: 100%; position: relative; overflow: hidden;"),t.video=document.createElement("video"),t.video.setAttribute("id","video"+t.id),e.stream.local&&!e.stream.screen?e.stream.mirror?t.video.setAttribute("style","width: 100%; height: 100%; position: absolute; transform: rotateY(180deg); object-fit: ".concat(t.fit||"cover",";")):t.video.setAttribute("style","width: 100%; height: 100%; position: absolute; object-fit: ".concat(t.fit||"cover",";")):e.stream.video?t.video.setAttribute("style","width: 100%; height: 100%; position: absolute; object-fit: ".concat(t.fit||"cover",";")):e.stream.screen?t.video.setAttribute("style","width: 100%; height: 100%; position: absolute; object-fit: ".concat(t.fit||"contain")):t.video.setAttribute("style","width: 100%; height: 100%; position: absolute; display: none; object-fit: ".concat(t.fit||"cover"));var n={autoplay:!0,muted:!!e.stream.local||!(!p.isSafari()&&"iOS"!==p.getBrowserOS())&&"video_element_muted",playsinline:!0,controls:!(!p.isSafari()&&"iOS"!==p.getBrowserOS()||e.stream.local),volume:null},r=v()({},n,e.options);!0!==r.muted||r.volume||(r.volume=0),r.autoplay&&t.video.setAttribute("autoplay",""),!0!==r.muted&&"video_element_muted"!==r.muted||(t.video.setAttribute("muted",""),t.video.muted=!0),r.playsinline&&t.video.setAttribute("playsinline",""),r.controls&&t.video.setAttribute("controls",""),Number.isFinite(r.volume)&&(t.video.volume=r.volume),t.audio=document.createElement("audio"),t.audio.setAttribute("id","audio"+t.id),r.autoplay&&t.audio.setAttribute("autoplay",""),!0===r.muted&&t.audio.setAttribute("muted",""),!0===r.muted&&(t.audio.muted=!0),r.playsinline&&t.audio.setAttribute("playsinline",""),Number.isFinite(r.volume)&&(t.audio.volume=r.volume),void 0!==t.elementID?(document.getElementById(t.elementID).appendChild(t.div),t.container=document.getElementById(t.elementID)):(document.body.appendChild(t.div),t.container=document.body),t.parentNode=t.div.parentNode;var s={video:{playerId:t.playerId,stateId:0,playDeferTimeout:null,error:!1,status:"init",reason:null,updatedAt:Date.now()},audio:{playerId:t.playerId,stateId:0,playDeferTimeout:null,error:!1,status:"init",reason:null,updatedAt:Date.now()}};t.mediaElemExists=function(e){for(var t=e,n=0;n").concat(f))},Object(i.getParameter)("PLAYER_STATE_DEFER"))}else o.default.error("Unknown media element",l)};if(t.mediaPlayerTimer=setInterval(function(){["video","audio"].forEach(function(n){var i=t[n],u=s[n];if(!u.playDeferTimeout){var l={playerId:t.playerId,stateId:u.stateId+1,playDeferTimeout:null,error:c(i,n,r),status:d(i),reason:"timer",updatedAt:Date.now()};if(u.status!==l.status){o.default.debug("Player ".concat(t.playerId," ").concat(n," Status Changed Detected by Timer: ").concat(u.status,"=>").concat(l.status)),s[n]=l;var p={type:"player-status-change",playerId:t.playerId,mediaType:n,status:l.status,reason:l.reason,isErrorState:l.error};o.default.debug("Media Player Status Change",p),e.stream.dispatchEvent(p),a.b.reportApiInvoke(e.stream.sid,{name:"Stream.playerStatusChange",options:p,tag:"tracer"})()}}})},Object(i.getParameter)("PLAYER_STATE_DEFER")),t.video.addEventListener("playing",function(e){!function e(){t.video.videoWidth*t.video.videoHeight>4?o.default.debug("["+t.id+"] video dimensions:",t.video.videoWidth,t.video.videoHeight):setTimeout(e,50)}()}),t.video.addEventListener("playing",u),t.video.addEventListener("canplay",u),t.video.addEventListener("abort",u),t.video.addEventListener("onerror",u),t.video.addEventListener("suspend",u),t.video.addEventListener("stalled",u),t.video.addEventListener("pause",u),t.audio.addEventListener("playing",u),t.audio.addEventListener("canplay",u),t.audio.addEventListener("abort",u),t.audio.addEventListener("onerror",u),t.audio.addEventListener("suspend",u),t.audio.addEventListener("stalled",u),t.audio.addEventListener("pause",u),e.stream.hasVideo()||e.stream.hasScreen())t.div.appendChild(t.video),t.div.appendChild(t.audio),p.isEdge()?t.video.srcObject=e.stream.stream:(Object(I.attachMediaStream)(t.video,e.stream.stream),Object(I.attachMediaStream)(t.audio,e.stream.stream));else if(!1!==r.muted&&"video_element_muted"!==r.muted||(t.video.removeAttribute("muted"),t.video.muted=!1),t.div.appendChild(t.video),window.MediaStream&&p.isSafari()){var l=new MediaStream(e.stream.stream.getAudioTracks());Object(I.setSrcObject)(t.video,l)}else Object(I.setSrcObject)(t.video,e.stream.stream);return t.setAudioVolume=function(e){var n=parseInt(e)/100;isFinite(n)&&(n<0?n=0:n>1&&(n=1),t.video&&(t.video.volume=n),t.audio&&(t.audio.volume=n))},t},C=function(e){var t={},n=I.RTCPeerConnection;t.uid=e.uid,t.isVideoMute=e.isVideoMute,t.isAudioMute=e.isAudioMute,t.isSubscriber=e.isSubscriber,t.clientId=e.clientId,t.filterStatsCache=[],t.originStatsCache=[],t.lastTimeGetStats=null,t.pc_config={iceServers:[{url:"stun:webcs.agora.io:3478"}]},t.con={optional:[{DtlsSrtpKeyAgreement:!0}]},e.iceServers instanceof Array?t.pc_config.iceServers=e.iceServers:(e.stunServerUrl&&(e.stunServerUrl instanceof Array?e.stunServerUrl.map(function(e){"string"==typeof e&&""!==e&&t.pc_config.iceServers.push({url:e})}):"string"==typeof e.stunServerUrl&&""!==e.stunServerUrl&&t.pc_config.iceServers.push({url:e.stunServerUrl})),e.turnServer&&(e.turnServer instanceof Array?e.turnServer.map(function(e){"string"==typeof e.url&&""!==e.url&&t.pc_config.iceServers.push({username:e.username,credential:e.credential,url:e.url})}):"string"==typeof e.turnServer.url&&""!==e.turnServer.url&&(t.pc_config.iceServers.push({username:e.turnServer.username,credential:e.turnServer.credential,credentialType:"password",urls:"turn:"+e.turnServer.url+":"+e.turnServer.udpport+"?transport=udp"}),"string"==typeof e.turnServer.tcpport&&""!==e.turnServer.tcpport&&t.pc_config.iceServers.push({username:e.turnServer.username,credential:e.turnServer.credential,credentialType:"password",urls:"turn:"+e.turnServer.url+":"+e.turnServer.tcpport+"?transport=tcp"}),!0===e.turnServer.forceturn&&(t.pc_config.iceTransportPolicy="relay")))),void 0===e.audio&&(e.audio=!0),void 0===e.video&&(e.video=!0),t.mediaConstraints={mandatory:{OfferToReceiveVideo:e.video,OfferToReceiveAudio:e.audio}},t.roapSessionId=103;try{t.pc_config.sdpSemantics="plan-b",t.peerConnection=new n(t.pc_config,t.con)}catch(e){delete t.pc_config.sdpSemantics,t.peerConnection=new n(t.pc_config,t.con)}t.iceCandidateTimer=setTimeout(function(){t.iceCandidateTimer=null,o.default.debug("[".concat(t.clientId,"]Candidates collected: ").concat(t.iceCandidateCount)),t.moreIceComing&&(t.moreIceComing=!1,t.markActionNeeded())},Object(i.getParameter)("CANDIDATE_TIMEOUT")),t.peerConnection.onicecandidate=function(e){var n,i,a,r;i=(n=t.peerConnection.localDescription.sdp).match(/a=candidate:.+typ\ssrflx.+\r\n/),a=n.match(/a=candidate:.+typ\shost.+\r\n/),r=n.match(/a=candidate:.+typ\srelay.+\r\n/),null===i&&null===a&&null===r||void 0!==t.ice||!t.iceCandidateTimer||(o.default.debug("["+t.clientId+"]srflx candidate : "+i+" relay candidate: "+r+" host candidate : "+a),clearTimeout(t.iceCandidateTimer),t.iceCandidateTimer=null,t.ice=0,t.moreIceComing=!1,t.markActionNeeded()),t.iceCandidateCount=t.iceCandidateCount+1},o.default.debug("["+t.clientId+']Created webkitRTCPeerConnnection with config "'+JSON.stringify(t.pc_config)+'".');var a=function(t){return e.screen&&(t=t.replace("a=x-google-flag:conference\r\n","")),t},r=function(n){var i,a;if((i=n.match(/m=video.*\r\n/))&&e.minVideoBW&&e.maxVideoBW){a=i[0]+"b=AS:"+e.maxVideoBW+"\r\n";var r=0,s=0;"h264"===e.codec?(r=n.search(/a=rtpmap:(\d+) H264\/90000\r\n/),s=n.search(/H264\/90000\r\n/)):"vp8"===e.codec&&(r=n.search(/a=rtpmap:(\d+) VP8\/90000\r\n/),s=n.search(/VP8\/90000\r\n/)),-1!==r&&-1!==s&&s-r>10&&(a=a+"a=fmtp:"+n.slice(r+9,s-1)+" x-google-min-bitrate="+e.minVideoBW+"\r\n"),n=n.replace(i[0],a),o.default.debug("["+t.clientId+"]Set Video Bitrate - min:"+e.minVideoBW+" max:"+e.maxVideoBW)}return(i=n.match(/m=audio.*\r\n/))&&e.maxAudioBW&&(a=i[0]+"b=AS:"+e.maxAudioBW+"\r\n",n=n.replace(i[0],a)),n};return t.processSignalingMessage=function(e){var n,i=JSON.parse(e);t.incomingMessage=i,"new"===t.state?"OFFER"===i.messageType?(n={sdp:i.sdp,type:"offer"},t.peerConnection.setRemoteDescription(new RTCSessionDescription(n)),t.state="offer-received",t.markActionNeeded()):t.error("Illegal message for this state: "+i.messageType+" in state "+t.state):"offer-sent"===t.state?"ANSWER"===i.messageType?((n={sdp:i.sdp,type:"answer"}).sdp=a(n.sdp),n.sdp=r(n.sdp),t.peerConnection.setRemoteDescription(new RTCSessionDescription(n)),t.sendOK(),t.state="established"):"pr-answer"===i.messageType?(n={sdp:i.sdp,type:"pr-answer"},t.peerConnection.setRemoteDescription(new RTCSessionDescription(n))):"offer"===i.messageType?t.error("Not written yet"):t.error("Illegal message for this state: "+i.messageType+" in state "+t.state):"established"===t.state&&("OFFER"===i.messageType?(n={sdp:i.sdp,type:"offer"},t.peerConnection.setRemoteDescription(new RTCSessionDescription(n)),t.state="offer-received",t.markActionNeeded()):"ANSWER"===i.messageType?((n={sdp:i.sdp,type:"answer"}).sdp=a(n.sdp),n.sdp=r(n.sdp),t.peerConnection.setRemoteDescription(new RTCSessionDescription(n))):t.error("Illegal message for this state: "+i.messageType+" in state "+t.state))},t.getVideoRelatedStats=function(e){t.peerConnection.getStats(function(n){Object.keys(n).forEach(function(i){var o=n[i];t.isSubscriber?"video"===o.mediaType&&o.id&&~o.id.indexOf("recv")&&e&&e({mediaType:"video",peerId:t.uid,isVideoMute:t.isVideoMute,frameRateReceived:o.googFrameRateReceived,frameRateDecoded:o.googFrameRateDecoded,bytesReceived:o.bytesReceived,packetsReceived:o.packetsReceived,packetsLost:o.packetsLost}):"video"===o.mediaType&&o.id&&~o.id.indexOf("send")&&e&&e({mediaType:"video",isVideoMute:t.isVideoMute,frameRateInput:o.googFrameRateInput,frameRateSent:o.googFrameRateSent,googRtt:o.googRtt})})})},t.getAudioRelatedStats=function(e){t.peerConnection.getStats(function(n){Object.keys(n).forEach(function(i){var o=n[i];t.isSubscriber&&"audio"===o.mediaType&&o.id&&~o.id.indexOf("recv")&&e&&e({mediaType:"audio",peerId:t.uid,isAudioMute:t.isAudioMute,frameDropped:parseInt(o.googDecodingPLC)+parseInt(o.googDecodingPLCCNG)+"",frameReceived:o.googDecodingCTN,googJitterReceived:o.googJitterReceived,bytesReceived:o.bytesReceived,packetsReceived:o.packetsReceived,packetsLost:o.packetsLost})})})},t.getStatsRate=function(e){t.getStats(function(t){e(t)})},t.getStats=function(e,n){n=(n=n||500)>500?500:n,t.lastTimeGetStats&&Date.now()-t.lastTimeGetStats500?500:n,t.lastTimeGetStats&&Date.now()-t.lastTimeGetStats-1&&-1===navigator.userAgent.indexOf("Chrome")?e.getTracks().forEach(function(n){return t.peerConnection.addTrack(n,e)}):t.peerConnection.addStream(e),t.markActionNeeded()},t.removeStream=function(){t.markActionNeeded()},t.close=function(){t.state="closed",t.peerConnection.close()},t.markActionNeeded=function(){t.actionNeeded=!0,t.doLater(function(){t.onstablestate()})},t.doLater=function(e){window.setTimeout(e,1)},t.onstablestate=function(){var n;if(t.actionNeeded){if("new"===t.state||"established"===t.state)e.isSubscriber&&(t.peerConnection.addTransceiver("audio",{direction:"recvonly"}),t.peerConnection.addTransceiver("video",{direction:"recvonly"})),t.peerConnection.createOffer(t.mediaConstraints).then(function(n){if(n.sdp=r(n.sdp),e.isSubscriber||(n.sdp=n.sdp.replace(/a=extmap:4 urn:3gpp:video-orientation\r\n/g,"")),n.sdp!==t.prevOffer)return t.peerConnection.setLocalDescription(n),t.state="preparing-offer",void t.markActionNeeded();o.default.debug("["+t.clientId+"]Not sending a new offer")}).catch(function(e){o.default.debug("["+t.clientId+"]peer connection create offer failed ",e)});else if("preparing-offer"===t.state){if(t.moreIceComing)return;t.prevOffer=t.peerConnection.localDescription.sdp,t.offerCandidates=t.prevOffer.match(/a=candidate.+\r\n/g)||[],t.offerCandidates.length||(o.default.warning("[".concat(t.clientId,"]No Ice Candidate generated")),Object(i.getParameter)("SHIM_CANDIDATE")?(o.default.debug("Shimming fake candidate"),t.prevOffer+="a=candidate:2243255435 1 udp 2122194687 192.168.0.1 30000 typ host generation 0 network-id 1\r\n"):o.default.error("[".concat(t.clientId,"]None Ice Candidate not allowed"))),t.prevOffer=t.prevOffer.replace(/a=candidate:.+typ\shost.+\r\n/g,"a=candidate:2243255435 1 udp 2122194687 192.168.0.1 30000 typ host generation 0 network-id 1\r\n"),t.sendMessage("OFFER",t.prevOffer),t.state="offer-sent"}else if("offer-received"===t.state)t.peerConnection.createAnswer(function(e){if(t.peerConnection.setLocalDescription(e),t.state="offer-received-preparing-answer",t.iceStarted)t.markActionNeeded();else{var n=new Date;o.default.debug("["+t.clientId+"]"+n.getTime()+": Starting ICE in responder"),t.iceStarted=!0}},function(e){o.default.debug("["+t.clientId+"]peer connection create answer failed ",e)},t.mediaConstraints);else if("offer-received-preparing-answer"===t.state){if(t.moreIceComing)return;n=t.peerConnection.localDescription.sdp,t.sendMessage("ANSWER",n),t.state="established"}else t.error("Dazed and confused in state "+t.state+", stopping here");t.actionNeeded=!1}},t.sendOK=function(){t.sendMessage("OK")},t.sendMessage=function(e,n){var i={};i.messageType=e,i.sdp=n,"OFFER"===e?(i.offererSessionId=t.sessionId,i.answererSessionId=t.otherSessionId,i.seq=t.sequenceNumber+=1,i.tiebreaker=Math.floor(429496723*Math.random()+1)):(i.offererSessionId=t.incomingMessage.offererSessionId,i.answererSessionId=t.sessionId,i.seq=t.incomingMessage.seq),t.onsignalingmessage(JSON.stringify(i))},t._getSender=function(e){if(t.peerConnection&&t.peerConnection.getSenders){var n=t.peerConnection.getSenders().find(function(t){return t.track.kind==e});if(n)return n}return null},t.hasSender=function(e){return!!t._getSender(e)},t.replaceTrack=function(e,n,i){var o=t._getSender(e.kind);if(!o)return i("NO_SENDER_FOUND");try{o.replaceTrack(e)}catch(e){return i&&i(e)}setTimeout(function(){return n&&n()},50)},t.error=function(e){throw"Error in RoapOnJsep: "+e},t.sessionId=t.roapSessionId+=1,t.sequenceNumber=0,t.actionNeeded=!1,t.iceStarted=!1,t.moreIceComing=!0,t.iceCandidateCount=0,t.onsignalingmessage=e.callback,t.peerConnection.ontrack=function(e){t.onaddstream&&t.onaddstream(e,"ontrack")},t.peerConnection.onremovestream=function(e){t.onremovestream&&t.onremovestream(e)},t.peerConnection.oniceconnectionstatechange=function(e){"connected"===e.currentTarget.iceConnectionState&&(t.connectedTime=new Date),t.oniceconnectionstatechange&&t.oniceconnectionstatechange(e.currentTarget.iceConnectionState)},t.renegotiate=function(){void 0!==t.prevOffer&&t.peerConnection.createOffer().then(function(e){return e.sdp=e.sdp.replace(/a=recvonly\r\n/g,"a=inactive\r\n"),e.sdp=a(e.sdp),e.sdp=r(e.sdp),t.peerConnection.setLocalDescription(e)}).then(function(){t.onnegotiationneeded&&t.onnegotiationneeded(t.peerConnection.localDescription.sdp)}).catch(function(e){console.log("createOffer error: ",e)})},t.peerConnection.onnegotiationneeded=t.renegotiate,t.onaddstream=null,t.onremovestream=null,t.state="new",t.markActionNeeded(),t},O=function(e){var t={},n=(mozRTCPeerConnection,mozRTCSessionDescription),a=!1;t.uid=e.uid,t.isVideoMute=e.isVideoMute,t.isAudioMute=e.isAudioMute,t.isSubscriber=e.isSubscriber,t.clientId=e.clientId,t.filterStatsCache=[],t.originStatsCache=[],t.lastTimeGetStats=null,t.pc_config={iceServers:[]},e.iceServers instanceof Array?e.iceServers.map(function(e){0===e.url.indexOf("stun:")&&t.pc_config.iceServers.push({url:e.url})}):(e.stunServerUrl&&(e.stunServerUrl instanceof Array?e.stunServerUrl.map(function(e){"string"==typeof e&&""!==e&&t.pc_config.iceServers.push({url:e})}):"string"==typeof e.stunServerUrl&&""!==e.stunServerUrl&&t.pc_config.iceServers.push({url:e.stunServerUrl})),e.turnServer&&"string"==typeof e.turnServer.url&&""!==e.turnServer.url&&(t.pc_config.iceServers.push({username:e.turnServer.username,credential:e.turnServer.credential,credentialType:"password",urls:"turn:"+e.turnServer.url+":"+e.turnServer.udpport+"?transport=udp"}),"string"==typeof e.turnServer.tcpport&&""!==e.turnServer.tcpport&&t.pc_config.iceServers.push({username:e.turnServer.username,credential:e.turnServer.credential,credentialType:"password",urls:"turn:"+e.turnServer.url+":"+e.turnServer.tcpport+"?transport=tcp"}),!0===e.turnServer.forceturn&&(t.pc_config.iceTransportPolicy="relay"))),void 0===e.audio&&(e.audio=!0),void 0===e.video&&(e.video=!0),t.mediaConstraints={offerToReceiveAudio:e.audio,offerToReceiveVideo:e.video,mozDontOfferDataChannel:!0},t.roapSessionId=103,t.peerConnection=new I.RTCPeerConnection(t.pc_config),o.default.debug("["+t.clientId+']safari Created RTCPeerConnnection with config "'+JSON.stringify(t.pc_config)+'".'),t.iceCandidateTimer=setTimeout(function(){t.iceCandidateTimer=null,o.default.debug("[".concat(t.clientId,"]Candidates collected: ").concat(t.iceCandidateCount)),t.moreIceComing&&(t.moreIceComing=!1,t.markActionNeeded())},Object(i.getParameter)("CANDIDATE_TIMEOUT")),t.peerConnection.onicecandidate=function(e){var n,i,a,r;i=(n=t.peerConnection.localDescription.sdp).match(/a=candidate:.+typ\ssrflx.+\r\n/),a=n.match(/a=candidate:.+typ\shost.+\r\n/),r=n.match(/a=candidate:.+typ\srelay.+\r\n/),null===i&&null===a&&null===r||void 0!==t.ice||!t.iceCandidateTimer||(o.default.debug("["+t.clientId+"]srflx candidate : "+i+" relay candidate: "+r+" host candidate : "+a),clearTimeout(t.iceCandidateTimer),t.iceCandidateTimer=null,t.ice=0,t.moreIceComing=!1,t.markActionNeeded()),t.iceCandidateCount=t.iceCandidateCount+1},t.checkMLineReverseInSDP=function(e){return!(!~e.indexOf("m=audio")||!~e.indexOf("m=video"))&&e.indexOf("m=audio")>e.indexOf("m=video")},t.reverseMLineInSDP=function(e){var t=e.split("m=audio"),n=t[1].split("m=video"),i="m=video"+n[1],o="m=audio"+n[0];return e=t[0]+i+o},t.processSignalingMessage=function(e){var i,a=JSON.parse(e);t.incomingMessage=a,"new"===t.state?"OFFER"===a.messageType?(a.sdp=l(a.sdp),i={sdp:a.sdp,type:"offer"},t.peerConnection.setRemoteDescription(new n(i),function(){o.default.debug("["+t.clientId+"]setRemoteDescription succeeded")},function(e){o.default.info("["+t.clientId+"]setRemoteDescription failed: "+e.name)}),t.state="offer-received",t.markActionNeeded()):t.error("Illegal message for this state: "+a.messageType+" in state "+t.state):"offer-sent"===t.state?"ANSWER"===a.messageType?(a.sdp=l(a.sdp),a.sdp=a.sdp.replace(/ generation 0/g,""),a.sdp=a.sdp.replace(/ udp /g," UDP "),-1!==a.sdp.indexOf("a=group:BUNDLE")?(a.sdp=a.sdp.replace(/a=group:BUNDLE audio video/,"a=group:BUNDLE sdparta_0 sdparta_1"),a.sdp=a.sdp.replace(/a=mid:audio/,"a=mid:sdparta_0"),a.sdp=a.sdp.replace(/a=mid:video/,"a=mid:sdparta_1")):(a.sdp=a.sdp.replace(/a=mid:audio/,"a=mid:sdparta_0"),a.sdp=a.sdp.replace(/a=mid:video/,"a=mid:sdparta_0")),i={sdp:a.sdp,type:"answer"},t.peerConnection.setRemoteDescription(new n(i),function(){o.default.debug("["+t.clientId+"]setRemoteDescription succeeded")},function(e){o.default.info("["+t.clientId+"]setRemoteDescription failed: "+e)}),t.sendOK(),t.state="established"):"pr-answer"===a.messageType?(i={sdp:a.sdp,type:"pr-answer"},t.peerConnection.setRemoteDescription(new n(i),function(){o.default.debug("["+t.clientId+"]setRemoteDescription succeeded")},function(e){o.default.info("["+t.clientId+"]setRemoteDescription failed: "+e.name)})):"offer"===a.messageType?t.error("Not written yet"):t.error("Illegal message for this state: "+a.messageType+" in state "+t.state):"established"===t.state&&("OFFER"===a.messageType?(i={sdp:a.sdp,type:"offer"},t.peerConnection.setRemoteDescription(new n(i),function(){o.default.debug("["+t.clientId+"]setRemoteDescription succeeded")},function(e){o.default.info("["+t.clientId+"]setRemoteDescription failed: "+e.name)}),t.state="offer-received",t.markActionNeeded()):t.error("Illegal message for this state: "+a.messageType+" in state "+t.state))};var r={id:"",type:"",mediaType:"opus",googCodecName:"opus",aecDivergentFilterFraction:"0",audioInputLevel:"0",bytesSent:"0",packetsSent:"0",googEchoCancellationReturnLoss:"0",googEchoCancellationReturnLossEnhancement:"0"},s={id:"",type:"",mediaType:"",googCodecName:"h264"===e.codec?"H264":"VP8",bytesSent:"0",packetsLost:"0",packetsSent:"0",googAdaptationChanges:"0",googAvgEncodeMs:"0",googEncodeUsagePercent:"0",googFirsReceived:"0",googFrameHeightSent:"0",googFrameHeightInput:"0",googFrameRateInput:"0",googFrameRateSent:"0",googFrameWidthSent:"0",googFrameWidthInput:"0",googNacksReceived:"0",googPlisReceived:"0",googRtt:"0"},d={id:"",type:"",mediaType:"",audioOutputLevel:"0",bytesReceived:"0",packetsLost:"0",packetsReceived:"0",googAccelerateRate:"0",googCurrentDelayMs:"0",googDecodingCNG:"0",googDecodingCTN:"0",googDecodingCTSG:"0",googDecodingNormal:"0",googDecodingPLC:"0",googDecodingPLCCNG:"0",googExpandRate:"0",googJitterBufferMs:"0",googJitterReceived:"0",googPreemptiveExpandRate:"0",googPreferredJitterBufferMs:"0",googSecondaryDecodedRate:"0",googSpeechExpandRate:"0"},c={id:"",type:"",mediaType:"",googTargetDelayMs:"0",packetsLost:"0",googDecodeMs:"0",googMaxDecodeMs:"0",googRenderDelayMs:"0",googFrameWidthReceived:"0",googFrameHeightReceived:"0",googFrameRateReceived:"0",googFrameRateDecoded:"0",googFrameRateOutput:"0",googJitterBufferMs:"0",googCurrentDelayMs:"0",googMinPlayoutDelayMs:"0",googNacksSent:"0",googPlisSent:"0",googFirsSent:"0",bytesReceived:"0",packetsReceived:"0",googFramesDecoded:"0"},u=0;t.getVideoRelatedStats=function(e){t.peerConnection.getStats().then(function(n){var i=!0,o=!1,a=void 0;try{for(var r,s=n.values()[Symbol.iterator]();!(i=(r=s.next()).done);i=!0){var d=r.value;if(t.isSubscriber){if(("inbound-rtp"===d.type||"inboundrtp"===d.type)&&"video"===d.mediaType){if(!t.lastReport)return void(t.lastReport=d);e&&e({browser:"firefox",mediaType:"video",peerId:t.uid,isVideoMute:t.isVideoMute,frameRateReceived:d.framerateMean+"",frameRateDecoded:d.framesDecoded-t.lastReport.framesDecoded+"",bytesReceived:d.bytesReceived+"",packetsReceived:d.packetsReceived+"",packetsLost:d.packetsLost+""}),t.lastReport=d}}else if(("outbound-rtp"===d.type||"outboundrtp"===d.type)&&"video"===d.mediaType){if(!t.lastReport)return void(t.lastReport=d);e&&e({mediaType:"video",isVideoMute:t.isVideoMute,frameRateInput:d.framerateMean+"",frameRateSent:d.framesEncoded-t.lastReport.framesEncoded+""}),t.lastReport=d}}}catch(e){o=!0,a=e}finally{try{i||null==s.return||s.return()}finally{if(o)throw a}}})},t.getAudioRelatedStats=function(e){t.peerConnection.getStats().then(function(n){var i=!0,o=!1,a=void 0;try{for(var r,s=n.values()[Symbol.iterator]();!(i=(r=s.next()).done);i=!0){var d=r.value;t.isSubscriber&&("inbound-rtp"!==d.type&&"inboundrtp"!==d.type||"audio"!==d.mediaType||e&&e({browser:"firefox",mediaType:"audio",peerId:t.uid,isAudioMute:t.isAudioMute,frameDropped:d.packetsLost+"",frameReceived:d.packetsReceived+"",googJitterReceived:d.jitter+"",bytesReceived:d.bytesReceived+"",packetsReceived:d.packetsReceived+"",packetsLost:d.packetsLost+""}))}}catch(e){o=!0,a=e}finally{try{i||null==s.return||s.return()}finally{if(o)throw a}}})},t.getStatsRate=function(e){t.getStats(function(t){t.forEach(function(e){"inbound-rtp"!==e.type&&"inboundrtp"!==e.type||"video"!==e.mediaType||e.googFrameRateDecoded&&(e.googFrameRateDecoded=((e.googFramesDecoded-u)/3).toString(),u=e.googFramesDecoded)}),e(t)})},t.getStats=function(e,n){n=(n=n||500)>500?500:n,t.lastTimeGetStats&&Date.now()-t.lastTimeGetStats0)){var i=n[0]+"b=TIAS:"+1e3*e.maxVideoBW+"\r\n";t=t.replace(n[0],i)}return e.audio&&e.maxAudioBW&&(null==(n=t.match(/m=audio.*\r\n/))&&(n=t.match(/m=audio.*\n/)),n&&n.length>0)&&(i=n[0]+"b=TIAS:"+1e3*e.maxAudioBW+"\r\n",t=t.replace(n[0],i)),t};return t.onaddstream=null,t.onremovestream=null,t.state="new",t.markActionNeeded(),t},N=n(12),w=n.n(N),D=null,k=function(){try{D=window.require("electron")}catch(e){}return D},M=function(e){var t=a.b.reportApiInvoke(null,{callback:e,name:"getScreenSources",options:arguments,tag:"tracer"}),n=k();if(!n)return t&&t("electron is null");n.desktopCapturer.getSources({types:["window","screen"]},function(e,n){if(e)return t&&t(e);t&&t(null,n)})},L=function(e,t,n){var i=t.attributes.width;t={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:t.attributes.height,maxWidth:i,maxFrameRate:t.attributes.maxFr,minFrameRate:t.attributes.minFr}}};navigator.webkitGetUserMedia(t,function(e){n&&n(null,e)},function(e){n&&n(e)})},P=function(){return!!k()},x=M,V=L,U=function(e,t){M(function(n,i){if(n)return t&&t(n);!function(e,t){var n=document.createElement("div");n.innerText="share screen",n.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");var i=document.createElement("div");i.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");var o=document.createElement("div");o.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",o.setAttribute("style","height: 12%;");var a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");var r=document.createElement("div");r.setAttribute("style","text-align: right; padding: 16px 0;");var s=document.createElement("button");s.innerHTML="cancel",s.setAttribute("style","width: 85px;"),s.onclick=function(){document.body.removeChild(d),t&&t("NotAllowedError")},r.appendChild(s),i.appendChild(o),i.appendChild(a),i.appendChild(r);var d=document.createElement("div");d.setAttribute("style","position: absolute; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),d.appendChild(n),d.appendChild(i),document.body.appendChild(d),e.map(function(e){if(e.id){var n=document.createElement("div");n.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;"),n.innerHTML='
'+e.name+"",n.onclick=function(){document.body.removeChild(d),t&&t(null,e.id)},a.appendChild(n)}})}(i,function(n,i){if(n)return t&&t(n);L(i,e,t)})})},F=103,B=function(e){var t={};if(t.clientId=e.clientId,e.session_id=F+=1,"undefined"==typeof window||!window.navigator)throw o.default.error("["+t.streamId+"]["+t.clientId+"]Publish/subscribe video/audio streams not supported yet"),new Error("NON_BROWSER_ENV_DETECTED");return null!==window.navigator.userAgent.match("Firefox")?(t.browser="mozilla",t=O(e)):"iOS"===p.getBrowserOS()||p.isSafari()?(o.default.debug("["+t.streamId+"]["+t.clientId+"]Safari"),(t=R(e)).browser="safari"):~window.navigator.userAgent.indexOf("Edge")?t=new w.a(e):(t=C(e)).browser="chrome-stable",t},j=function(e,t,n){var i={};i.config=e,i.streamId=e.streamId,delete e.streamId,navigator.getMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia;var a=0,r=1,s=!1,d=null,c=function(e){if(a++,d)if(d===e)o.default.debug("Using Video Source/ Audio Source");else{var n=d.getVideoTracks()[0],i=d.getAudioTracks()[0],c=e.getVideoTracks()[0],u=e.getAudioTracks()[0];c&&(n&&d.removeTrack(n),d.addTrack(c)),u&&(i&&d.removeTrack(i),d.addTrack(u))}else d=e;a!==r||s||(s=!0,setTimeout(function(){t(d)},0))},u=function(e){o.default.error("Failed to GetUserMedia",e.name,e.code,e.message,e),a++,s||(s=!0,setTimeout(function(){n&&n(e)},0))},l=function(){var t={video:e.video,audio:e.audio};if(o.default.debug("GetUserMedia",JSON.stringify(t)),navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)navigator.mediaDevices.getUserMedia(t).then(c).catch(u);else if("undefined"!=typeof navigator&&navigator.getMedia)navigator.getMedia(e,c,u);else{var a={name:"MEDIA_NOT_SUPPORT",message:"Video/audio streams not supported yet"};o.default.error("["+i.streamId+"]"+a.message),n&&n(a)}};if((e.videoSource||e.audioSource)&&(d=new MediaStream,e.videoSource&&d.addTrack(e.videoSource),e.audioSource&&d.addTrack(e.audioSource)),e.video||e.audio||e.screen)if(e.screen){if(P())return e.screen.sourceId?V(e.screen.sourceId,e.screen,function(e,t){e?u(e):c(t)}):U(e.screen,function(e,t){e?u(e):c(t)});if(p.isFireFox()){o.default.debug("["+i.streamId+"]Screen access requested");if(!~["screen","window","application"].indexOf(e.screen.mediaSource))return n&&n("Invalid mediaSource, mediaSource should be one of [screen, window, application]");navigator.getMedia({video:e.screen},function(t){e.audio&&(r++,l()),c(t)},u)}else if(p.isChrome()&&e.screen.extensionId){if(window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<34)return void n({code:"This browser does not support screen sharing"});o.default.debug("["+i.streamId+"]Screen access on chrome stable, looking for extension");try{chrome.runtime.sendMessage(e.screen.extensionId,{getStream:!0},function(t){if(void 0===t){o.default.error("["+i.streamId+"]No response from Chrome Plugin. Plugin not installed properly");u({name:"PluginNotInstalledProperly",message:"No response from Chrome Plugin. Plugin not installed properly."})}else e.screen.mandatory.chromeMediaSourceId=t.streamId,navigator.getMedia({video:e.screen},function(t){e.audio&&(r++,l()),c(t)},u)})}catch(e){o.default.debug("["+i.streamId+"]AgoraRTC screensharing plugin is not accessible");return void n({code:"no_plugin_present"})}}else{if(window.navigator.mediaDevices.getDisplayMedia)return o.default.debug("use getDisplayMedia, constraints:",e.screen),window.navigator.mediaDevices.getDisplayMedia(e.screen).then(function(t){e.audio&&(r++,l()),c(t)}).catch(u);o.default.error("["+i.streamId+"]This browser does not support screenSharing")}}else l();else c(d)},W=n(7),H=function(e,t,n){if(["End2EndDelay","TransportDelay","PacketLossRate","RecvLevel","RecvBitrate","CodecType","MuteState","TotalFreezeTime","TotalPlayDuration","RecordingLevel","SendLevel","SamplingRate","SendBitrate","CodecType","MuteState","End2EndDelay","TransportDelay","PacketLossRate","RecvBitrate","RecvResolutionWidth","RecvResolutionHeight","RenderResolutionHeight","RenderResolutionWidth","RenderFrameRate","TotalFreezeTime","TotalPlayDuration","TargetSendBitrate","SendFrameRate","SendFrameRate","SendBitrate","SendResolutionWidth","SendResolutionHeight","CaptureResolutionHeight","CaptureResolutionWidth","EncodeDelay","MuteState","TotalFreezeTime","TotalDuration","CaptureFrameRate","RTT","OutgoingAvailableBandwidth","Duration","UserCount","SendBytes","RecvBytes","SendBitrate","RecvBitrate","accessDelay","audioSendBytes","audioSendPackets","videoSendBytes","videoSendPackets","videoSendPacketsLost","videoSendFrameRate","audioSendPacketsLost","videoSendResolutionWidth","videoSendResolutionHeight","accessDelay","audioReceiveBytes","audioReceivePackets","audioReceivePacketsLost","videoReceiveBytes","videoReceivePackets","videoReceivePacketsLost","videoReceiveFrameRate","videoReceiveDecodeFrameRate","videoReceiveResolutionWidth","videoReceiveResolutionHeight","endToEndDelay","videoReceiveDelay","audioReceiveDelay","FirstFrameTime","VideoFreezeRate","AudioFreezeRate","RenderResolutionWidth","RenderResolutionHeight"].indexOf(t)>-1&&("string"==typeof n||isFinite(n)))return e[t]=""+n},G=new function(){var e=r();return e.devicesHistory={},e.states={UNINIT:"UNINIT",INITING:"INITING",INITED:"INITED"},e.state=e.states.UNINIT,e.deviceStates={ACTIVE:"ACTIVE",INACTIVE:"INACTIVE"},e.deviceReloadTimer=null,e._init=function(t,n){e.state=e.states.INITING,e.devicesHistory={},e._reloadDevicesInfo(function(){e.state=e.states.INITED,e.dispatchEvent({type:"inited"}),t&&t()},function(t){o.default.warning("Device Detection functionality cannot start properly."),e.state=e.states.UNINIT,n&&n(t)})},e._enumerateDevices=function(e,t){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return o.default.warning("enumerateDevices() not supported."),t&&t("enumerateDevices() not supported");navigator.mediaDevices.enumerateDevices().then(function(t){e&&setTimeout(function(){e(t)},0)}).catch(function(e){t&&t(e)})},e._reloadDevicesInfo=function(t,n){var i=[];e._enumerateDevices(function(n){var a=Date.now();for(var r in n.forEach(function(t){var n=e.devicesHistory[t.deviceId];if((n?n.state:e.deviceStates.INACTIVE)!=e.deviceStates.ACTIVE){var o=n||{initAt:a};o.device=t,o.state=e.deviceStates.ACTIVE,i.push(o),e.devicesHistory[t.deviceId]=o}e.devicesHistory[t.deviceId].lastReloadAt=a}),e.devicesHistory){var s=e.devicesHistory[r];s&&s.state==e.deviceStates.ACTIVE&&s.lastReloadAt!==a&&(s.state=e.deviceStates.INACTIVE,i.push(s)),s.lastReloadAt=a}e.state==e.states.INITED&&i.forEach(function(t){var n=v()({},t);switch(t.device.kind){case"audioinput":n.type="recordingDeviceChanged";break;case"audiooutput":n.type="playoutDeviceChanged";break;case"videoinput":n.type="cameraChanged";break;default:o.default.warning("Unknown device change",n),n.type="unknownDeviceChanged"}e.dispatchEvent(n)}),t&&t()},n)},e.getDeviceById=function(t,n,i){e.getDevices(function(e){for(var o=0;o=t&&e.length<=n},Z=function(e,t,n){return ie(e)&&e>=t&&e<=n},ee=function(e){return"boolean"==typeof e},te=function(e){return $(e,1,2047)},ne=function(e){if("string"==typeof e){for(var t=0;t255)return!1}return!0}},ie=function(e){return"number"==typeof e&&e%1==0},oe=function(e){return"string"==typeof e},ae=function(e){return null==e},re=n(11);var se=function(e){q(e,"profileName"),-1===(e=e.toLowerCase()).indexOf("_")&&(e+="_1"),K(e,"profileName",Object.keys(i.SUPPORT_RESOLUTION_LIST));var t=i.SUPPORT_RESOLUTION_LIST[e];t||(e=Object(i.getParameter)("DEFAULT_PROFILE"),t=i.SUPPORT_RESOLUTION_LIST[e]);var n={profileName:e,video:{width:t[0],height:t[1]},attributes:{resolution:"".concat(t[0],"x").concat(t[1]),minFrameRate:t[2],maxFrameRate:t[3],minVideoBW:t[4],maxVideoBW:t[5]}};return t[2]&&t[3]&&(n.video.frameRate={min:t[2],max:t[3]}),t[6]&&t[7]&&(n.screen={width:t[0],height:t[1],frameRate:{min:t[6],max:t[7]}}),n},de=function(e){return Object.keys(i.SUPPORT_RESOLUTION_LIST).filter(function(t){var n=i.SUPPORT_RESOLUTION_LIST[t],o=["width","height","frameRate"];for(var a in o){var r=o[a];if(e[r]&&n[a]){if("number"==typeof e[r].max&&e[r].maxn[a])return!1}}return!0}).reverse()},ce=function(e){var t=i.AUDIO_PROFILE_SETTINGS[e]||i.AUDIO_PROFILE_SETTINGS.default;return{highQuality:t[0],stereo:t[1],speech:t[2],lowQuality:t[3]}};var ue=function(e){var t=r();if(t.params=v()({},e),t.stream=e.stream,t.url=e.url,t.onClose=void 0,t.local=!1,t.videoSource=e.videoSource,t.audioSource=e.audioSource,e.video=!(!e.videoSource&&!e.video),t.video=e.video,e.audio=!(!e.audioSource&&!e.audio),t.audio=e.audio,t.screen=!!e.screen,t.screenAttributes={width:1920,height:1080,maxFr:5,minFr:1},t.videoSize=e.videoSize,t.player=void 0,t.audioLevelHelper=null,e.attributes=e.attributes||{},t.attributes=e.attributes,t.microphoneId=e.microphoneId,t.cameraId=e.cameraId,t.inSwitchDevice=!1,t.userMuteVideo=!1,t.userMuteAudio=!1,t.peerMuteVideo=!1,t.peerMuteAudio=!1,t.lowStream=null,t.videoWidth=0,t.videoHeight=0,t.streamId=e.streamID,t.userId=null,t.mirror=!1!==e.mirror,t.DTX=e.audioProcessing&&e.audioProcessing.DTX,t.audioProcessing=e.audioProcessing,t.highQuality=!1,t.stereo=!1,t.speech=!1,t.screen||delete t.screen,!(void 0===t.videoSize||t.videoSize instanceof Array&&4===t.videoSize.length))throw Error("Invalid Video Size");function n(){var e={};t.getVideoTrack()===this?(o.default.debug("Video Track Ended"),e.type="videoTrackEnded",e.track=this):t.getAudioTrack()===this?(o.default.debug("Audio Track Ended"),e.type="audioTrackEnded",e.track=this):o.default.debug("Detached Track ended",this.kind,this.label,this),e.type&&t.dispatchEvent(e)}return t.videoSize=[640,480,640,480],void 0!==e.local&&!0!==e.local||(t.local=!0),t.initialized=!t.local,function(e){e.audioMixing={audioContextInited:!1,defaultVolume:100,inEarMonitoring:"FILE",sounds:{},states:{IDLE:"IDLE",STARTING:"STARTING",BUSY:"BUSY",PAUSED:"PAUSED"},inEarMonitoringModes:{NONE:"NONE",FILE:"FILE",MICROPHONE:"MOCROPHONE",ALL:"ALL"},ctx:null,mediaStreamSource:null,mediaStreamDest:null,buffer:{}},e._initSoundIfNotExists=function(t,n){e.audioMixing.sounds[t]||(e.audioMixing.sounds[t]={soundId:t,state:"IDLE",muted:e.userMuteAudio,filePath:n,volume:e.audioMixing.defaultVolume,startAt:null,startOffset:null,pauseAt:null,pauseOffset:null,resumeAt:null,resumeOffset:null,stopAt:null,options:null,source:null})},e._initSoundIfNotExists(-1),e.loadAudioBuffer=function(t,n,i){var r=a.b.reportApiInvoke(e.sid,{callback:i,name:"Stream.loadAudioBuffer",options:arguments,tag:"tracer"});q(n,"url",1,1024,!1),q(t,"id",1,1024,!1);var s=new XMLHttpRequest;s.open("GET",n,!0),s.responseType="arraybuffer",s.onload=function(){if(s.status>400){var n=s.statusText;return o.default.error("[".concat(e.streamId,"] loadAudioBuffer Failed: ")+n),r(n)}var i=s.response;e.audioMixing.audioContextInited||e._initAudioContext(),e.audioMixing.ctx.decodeAudioData(i,function(n){e.audioMixing.buffer[t]=n,r(null)},function(t){o.default.error("[".concat(e.streamId,"] decodeAudioData Failed: "),t),r(t)})},s.send()},e.createAudioBufferSource=function(t){var n=a.b.reportApiInvoke(e.sid,{name:"Stream.createAudioBufferSource",options:arguments,tag:"tracer"});if(e.audioMixing.buffer[t.id]){var i=e.audioMixing.buffer[t.id],r=e.audioMixing.ctx.createBufferSource();r.buffer=i;var s=e.audioMixing.ctx.createGain();if(r.connect(s),s.connect(e.audioMixing.mediaStreamDest),r.gainNode=s,t.loop)r.loop=!0,r.start(0,t.playTime/1e3);else if(t.cycle>1)if(Object(p.isChrome)()){r.loop=!0;var d=t.cycle*i.duration*1e3-(t.playTime||0);r.start(0,t.playTime/1e3,d/1e3)}else o.default.warning("[".concat(e.streamId,"] Cycle Param is ignored by current browser")),r.start(0,t.playTime/1e3);else r.start(0,t.playTime/1e3);var c=e.audioMixing.sounds[t.soundId];return c.source=r,e._flushAudioMixingMuteStatus(),r.addEventListener("ended",function(){r===c.source&&e.dispatchEvent({type:"audioSourceEnded",soundId:t.soundId,source:r,sound:c})}),n(),r}return o.default.error("[".concat(e.streamId,"] "),"AUDIOBUFFER_NOT_FOUND",t.id),n(!1),!1},e.on("audioSourceEnded",function(t){t.source;var n=t.sound;n&&n.state===e.audioMixing.states.BUSY&&!n.pauseAt&&(n.state=e.audioMixing.states.IDLE,n.startAt=null,n.startOffset=null,n.resumeAt=null,n.resumeOffset=null,e.audioMixing.mediaStreamSource.connect(e.audioMixing.mediaStreamDest))}),e.clearAudioBufferSource=function(){e.audioBufferSource.forEach(function(e){e.stop()})},e._isSoundExists=function(t){return!!e.audioMixing.sounds[t.soundId]||(o.default.error("SoundId not exists. #".concat(t.soundId)),!1)},e._initAudioContext=function(){if(e.audioMixing.audioContextInited)throw new Error("Failed to init audio context. Already inited");if(!e.stream)throw new Error("Failed to init audio context. Local Stream not initialized");e.audioMixing.ctx=Object(re.a)(),e.audioMixing.mediaStreamSource=e.audioMixing.ctx.createMediaStreamSource(e.stream),e.audioMixing.mediaStreamDest=e.audioMixing.ctx.createMediaStreamDestination(),e.audioMixing.mediaStreamSource.connect(e.audioMixing.mediaStreamDest);var t=e.stream.getVideoTracks()[0];if(t&&e.audioMixing.mediaStreamDest.stream.addTrack(t),e._isAudioMuted()?(e._unmuteAudio(),e.stream=e.audioMixing.mediaStreamDest.stream,e._muteAudio()):e.stream=e.audioMixing.mediaStreamDest.stream,e.audioLevelHelper=null,e.pc&&e.pc.peerConnection&&e.pc.peerConnection){var n=(e.pc.peerConnection&&e.pc.peerConnection.getSenders()).find(function(e){return e&&e.track&&"audio"==e.track.kind}),i=e.audioMixing.mediaStreamDest.stream.getAudioTracks()[0];n&&n.replaceTrack&&i&&n.replaceTrack(i)}e.audioMixing.audioContextInited=!0},e._cleanupAudioMixing=function(){if(e.audioMixing.audioContextInited){for(var t in e.audioMixing.sounds){var n=e.audioMixing.sounds[t];n.state!==e.audioMixing.states.BUSY&&n.state!==e.audioMixing.states.PAUSED||e._stopOneEffect({soundId:t})}e.audioLevelHelper=null,e.audioMixing.audioContextInited=!1}},e._reloadInEarMonitoringMode=function(t){if(t){if(!e.audioMixing.inEarMonitoringModes[t])return o.default.error("[".concat(e.streamId,"] Invalid InEarMonitoringMode ").concat(t));e.audioMixing.inEarMonitoring=t}switch(e.audioMixing.audioContextInited||e._initAudioContext(),e.audioMixing.inEarMonitoring){case e.audioMixing.inEarMonitoringModes.FILE:e.audioMixing.mediaStreamSource.connectedToDestination&&(e.audioMixing.mediaStreamSource.disconnect(e.audioMixing.ctx.destination),e.audioMixing.mediaStreamSource.connectedToDestination=!1);case e.audioMixing.inEarMonitoringModes.ALL:for(var n in e.audioMixing.sounds){var i=e.audioMixing.sounds[n];i&&i.source&&!i.source.connectedToDestination&&(i.source.gainNode.connect(e.audioMixing.ctx.destination),i.source.connectedToDestination=!0)}}switch(e.audioMixing.inEarMonitoring){case e.audioMixing.inEarMonitoringModes.MICROPHONE:e.audioMixing.source.forEach(function(t){t.connectedToDestination&&(t.gainNode.disconnect(e.audioMixing.ctx.destination),t.connectedToDestination=!1)});case e.audioMixing.inEarMonitoringModes.ALL:e.audioMixing.mediaStreamSource.connectedToDestination||(e.audioMixing.mediaStreamSource.connect(e.audioMixing.ctx.destination),e.audioMixing.mediaStreamSource.connectedToDestination=!0)}},e._startAudioMixingBufferSource=function(t){e.audioMixing.audioContextInited||e._initAudioContext();var n={soundId:t.soundId,id:t.filePath,loop:t.loop,cycle:t.cycle,playTime:t.playTime||0},i=t.replace,o=e.createAudioBufferSource(n);return o.sound=e.audioMixing.sounds[t.soundId],o?(o.addEventListener("ended",e._audioMixingFinishedListener,{once:!0}),e._reloadInEarMonitoringMode(),i&&e.audioMixing.mediaStreamSource.disconnect(e.audioMixing.mediaStreamDest),o):null},e._stopAudioMixingBufferSource=function(t){var n=e.audioMixing.sounds[t.soundId].source;return n?(n.removeEventListener("ended",e._audioMixingFinishedListener),e.audioMixing.mediaStreamSource.connect(e.audioMixing.mediaStreamDest),n.stop(),n):null},e._flushAudioMixingMuteStatus=function(t){for(var n in e.audioMixing.sounds){var i=e.audioMixing.sounds[n];i&&(void 0!==t&&(i.muted=!!t),i.source&&(i.muted?i.source.gainNode.gain.value=0:i.source.gainNode.gain.value=i.volume/100))}},e._handleAudioMixingInvalidStateError=function(t,n,i){var a=e.audioMixing.sounds[n.soundId],r=-1===n.soundId?"INVALID_AUDIO_MIXING_STATE":"INVALID_PLAY_EFFECT_STATE";o.default.error("[".concat(e.streamId,"] Cannot ").concat(t,": ").concat(r,", state is ").concat(a.state)),i&&i(r)},e._handleAudioMixingNoSourceError=function(t,n,i){e.audioMixing.sounds[n.soundId].state=e.audioMixing.states.IDLE;var a=-1===n.soundId?"NO_AUDIO_MIXING_SOURCE":"NO_EFFECT_SOURCE";o.default.error("[".concat(e.streamId,"] Cannot ").concat(t,": ").concat(a)),i&&i(a)},e._getOneEffectStates=function(t){var n=e.audioMixing.sounds[t.soundId];return function(){return n?{state:n.state,startAt:n.startAt,resumeAt:n.resumeAt,pauseOffset:n.pauseOffset,pauseAt:n.pauseAt,resumeOffset:n.resumeOffset,stopAt:n.stopAt,duration:e._getOneEffectDuration(t),position:e._getOneEffectCurrentPosition(t)}:{}}},e._audioMixingFinishedListener=function(){var t=this.sound;t.state===e.audioMixing.states.IDLE&&e.audioMixing.buffer[t.options.filePath]&&!t.options.cacheResource&&(o.default.debug("Recycled buffer ".concat(t.options.filePath)),delete e.audioMixing.buffer[t.options.filePath]),-1===t.soundId&&e.dispatchEvent({type:"audioMixingFinished"})},e._playOneEffect=function(t,n){Y(t,"options");var i=t.soundId,a=(t.filePath,t.cacheResource);if(t.cycle,t.loop,t.playTime,t.replace,Object(p.isSafari)()&&Object(p.getBrowserVersion)()<12){var r="BROWSER_NOT_SUPPORT";return o.default.error("[".concat(e.streamId,"] Cannot _playOneEffect: "),r),n(r)}e.audioMixing.audioContextInited||e._initAudioContext(),e._initSoundIfNotExists(i);var s=e.audioMixing.sounds[i];if(s.state===e.audioMixing.states.IDLE){if(void 0!==t.cycle&&!t.cycle>0)return r="Invalid Parmeter cycle: "+t.cycle,o.default.error("[".concat(e.streamId,"] ").concat(i),r),n(r);if(ae(a)&&(t.cacheResource=!0),s.state=e.audioMixing.states.STARTING,s.options=t,e.audioMixing.buffer[t.filePath]){var d=e._startAudioMixingBufferSource(t);if(d)return s.source=d,s.startAt=Date.now(),s.resumeAt=null,s.pauseOffset=null,s.pauseAt=null,s.resumeOffset=null,s.stopAt=null,s.startOffset=t.playTime||0,s.state=e.audioMixing.states.BUSY,e._flushAudioMixingMuteStatus(),n(null);s.state=e.audioMixing.states.IDLE;var c="CREATE_BUFFERSOURCE_FAILED";if(n)return n(c);o.default.error("[".concat(e.streamId,"] "),c)}else e.loadAudioBuffer(t.filePath,t.filePath,function(i){if(i)s.state=e.audioMixing.states.IDLE,n?n(i):o.default.error("[".concat(e.streamId,"] "),i);else{var a=e._startAudioMixingBufferSource(t);if(a)return s.source=a,s.startAt=Date.now(),s.resumeAt=null,s.pauseOffset=null,s.pauseAt=null,s.resumeOffset=null,s.stopAt=null,s.startOffset=t.playTime||0,s.state=e.audioMixing.states.BUSY,e._flushAudioMixingMuteStatus(),n(null);if(s.state=e.audioMixing.states.IDLE,i="CREATE_BUFFERSOURCE_FAILED",n)return n(i);o.default.error("[".concat(e.streamId,"] "),i)}})}else e._handleAudioMixingInvalidStateError("_playEffect",t,n)},e._stopOneEffect=function(t,n){var i=e.audioMixing.sounds[t.soundId];return e._isSoundExists(t)?i.state===e.audioMixing.states.BUSY||i.state===e.audioMixing.states.PAUSED?(e._stopAudioMixingBufferSource(t),i.stopAt=Date.now(),i.state=e.audioMixing.states.IDLE,e.audioMixing.buffer[i.options.filePath]&&!i.options.cacheResource&&(o.default.debug("Recycled buffer ".concat(i.options.filePath)),delete e.audioMixing.buffer[i.options.filePath]),void(n&&n(null))):void e._handleAudioMixingInvalidStateError("_stopOneEffect",t,n):n("SOUND_NOT_EXISTS")},e._pauseOneEffect=function(t,n){var i=e.audioMixing.sounds[t.soundId];if(i.state===e.audioMixing.states.BUSY)return e._stopAudioMixingBufferSource(t)?(i.pauseAt=Date.now(),i.state=e.audioMixing.states.PAUSED,i.resumeAt?i.pauseOffset=i.pauseAt-i.resumeAt+i.resumeOffset:i.pauseOffset=i.pauseAt-i.startAt+i.startOffset,n&&n(null)):void e._handleAudioMixingNoSourceError("_pauseOneEffect",t,n);e._handleAudioMixingInvalidStateError("_pauseOneEffect",t,n)},e._resumeOneEffect=function(t,n){var i=e.audioMixing.sounds[t.soundId];if(i.state===e.audioMixing.states.PAUSED){var a={soundId:t.soundId,filePath:i.options.filePath,cycle:i.options.cycle,loop:i.options.loop,playTime:i.pauseOffset,replace:i.options.replace},r=e._startAudioMixingBufferSource(a);if(!r){var s="CREATE_BUFFERSOURCE_FAILED";return n(s),void o.default.error("[".concat(e.streamId,"] "),s)}i.source=r,i.resumeAt=Date.now(),i.resumeOffset=i.pauseOffset,i.state=e.audioMixing.states.BUSY,i.pauseAt=null,i.pauseOffset=null,n(null)}else e._handleAudioMixingInvalidStateError("_resumeOneEffect",t,n)},e._getOneEffectDuration=function(t){var n=e.audioMixing.sounds[t.soundId];return n.options&&n.options.filePath&&e.audioMixing.buffer[n.options.filePath]?1e3*e.audioMixing.buffer[n.options.filePath].duration:null},e._getOneEffectCurrentPosition=function(t,n){var i=e.audioMixing.sounds[t.soundId];return i.state===e.audioMixing.states.PAUSED?i.pauseOffset%e._getOneEffectDuration(t):i.state===e.audioMixing.states.BUSY?i.resumeAt?(Date.now()-i.resumeAt+i.resumeOffset+i.startOffset)%e._getOneEffectDuration(t):(Date.now()-i.startAt+i.startOffset)%e._getOneEffectDuration(t):void(n&&e._handleAudioMixingInvalidStateError("_getOneEffectCurrentPosition",t))},e._setOneEffectPosition=function(t,n,i){var a=e.audioMixing.sounds[t.soundId];if(a.state===e.audioMixing.states.BUSY){if(!e._stopAudioMixingBufferSource(t))return void e._handleAudioMixingNoSourceError("_setOneEffectPosition",t,i);var r={soundId:t.soundId,filePath:a.options.filePath,loop:a.options.loop,cycle:a.options.cycle,playTime:n},s=e._startAudioMixingBufferSource(r);if(!s){var d="CREATE_BUFFERSOURCE_FAILED";return i&&i(d),void o.default.error("[".concat(e.streamId,"] "),d)}a.source=s,a.startAt=Date.now(),a.startOffset=n,a.resumeAt=null,a.resumeOffset=null,a.pauseOffset=null,a.pauseAt=null}else{if(a.state!==e.audioMixing.states.PAUSED)return void e._handleAudioMixingInvalidStateError("_setOneEffectPosition",t,i);a.pauseOffset=n}i&&i(null)},e.startAudioMixing=function(t,n){var o=a.b.reportApiInvoke(e.sid,{callback:function(t){if(t)return n&&n(t);e.dispatchEvent({type:"audioMixingPlayed"}),n&&n(null)},getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.startAudioMixing",options:t});Y(t,"options");var r=t.filePath,s=t.cacheResource,d=t.cycle,c=t.loop,u=t.playTime,l=t.replace;q(r,"filePath",1,Object(i.getParameter)("FILEPATH_LENMAX"),!1),Q(u,"playTime",0,1e8),!ae(d)&&Q(d,"cycle"),!ae(c)&&X(c,"loop"),!ae(l)&&X(l,"replace"),!ae(s)&&X(s,"cacheResource");var p=v()({soundId:-1},t);e._playOneEffect(p,o)},e.stopAudioMixing=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:t,getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.stopAudioMixing"});e._stopOneEffect({soundId:-1},n)},e.pauseAudioMixing=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:t,getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.pauseAudioMixing"});return e._pauseOneEffect({soundId:-1},n)},e.resumeAudioMixing=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:function(n,i){if(n)return t&&t(n);e.dispatchEvent({type:"audioMixingPlayed"}),t&&t(null)},getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.resumeAudioMixing"});e._resumeOneEffect({soundId:-1},n)},e.adjustAudioMixingVolume=function(t){var n=a.b.reportApiInvoke(e.sid,{getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.adjustAudioMixingVolume",options:arguments,tag:"tracer"});Q(t,"volume",0,100),e.audioMixing.sounds[-1].volume=t,e._flushAudioMixingMuteStatus(),n()},e.getAudioMixingDuration=function(){var t=a.b.reportApiInvoke(e.sid,{getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.getAudioMixingDuration"}),n=e._getOneEffectDuration({soundId:-1});return t(null,n),n},e.getAudioMixingCurrentPosition=function(){var t=a.b.reportApiInvoke(e.sid,{getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.getAudioMixingCurrentPosition"}),n=e._getOneEffectCurrentPosition({soundId:-1},!0);return t(null,n),n},e.setAudioMixingPosition=function(t,n){var i=a.b.reportApiInvoke(e.sid,{callback:n,options:arguments,tag:"tracer",getStates:e._getOneEffectStates({soundId:-1}),name:"Stream.setAudioMixingPosition"});Q(t,"position",0,1e8),e._setOneEffectPosition({soundId:-1},t,i)},e.playEffect=function(t,n){var o=a.b.reportApiInvoke(e.sid,{callback:function(t){if(t)return n&&n(t);e.dispatchEvent({type:"effectPlayed"}),n&&n(null)},name:"Stream.playEffect",options:t});Y(t,"options");var r=t.soundId,s=t.filePath,d=t.cycle;Q(r,"soundId",1,1e4),q(s,"filePath",0,Object(i.getParameter)("FILEPATH_LENMAX"),!1),!ae(d)&&Q(d,"cycle"),e._playOneEffect(t,o)},e.stopEffect=function(t,n){var i=a.b.reportApiInvoke(e.sid,{callback:n,getStates:e._getOneEffectStates({soundId:t}),name:"Stream.stopEffect"});Q(t,"soundId",1,1e4),e._stopOneEffect({soundId:t},i)},e.stopAllEffects=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:t,name:"Stream.stopAllEffect"}),i=!1,o=0,r=0,s=function(e){i||(e?(n(e),i=!0):o+=1,o===r&&(n(null),i=!0))};for(var d in e.audioMixing.sounds){var c=e.audioMixing.sounds[d];-1!==c.soundId&&(c.state!==e.audioMixing.states.BUSY&&c.state!==e.audioMixing.states.PAUSED||(r++,e._stopOneEffect({soundId:d},s)))}r||n(null)},e.preloadEffect=function(t,n,o){var r=a.b.reportApiInvoke(e.sid,{callback:o,options:arguments,tag:"tracer",name:"Stream.preloadEffect"});Q(t,"soundId",1,1e4),q(n,"filePath",1,Object(i.getParameter)("FILEPATH_LENMAX"),!1),e._initSoundIfNotExists(t,n),e.audioMixing.buffer[n]?r(null):e.loadAudioBuffer(n,n,r)},e.unloadEffect=function(t,n){var i=a.b.reportApiInvoke(e.sid,{callback:n,options:arguments,tag:"tracer",name:"Stream.unloadEffect"});Q(t,"soundId",1,1e4);var r=e.audioMixing.sounds[t];if(!r){var s="SOUND_NOT_EXISTS";return o.default.error(s,t),void i(s)}var d=r.options?r.options.filePath:r.filePath;if(d)delete e.audioMixing.buffer[d],delete e.audioMixing.sounds[t],i(null);else{var c="SOUND_BUFFER_NOT_FOUND";o.default.error(c,t),i(c)}},e.pauseEffect=function(t,n){var i=a.b.reportApiInvoke(e.sid,{callback:n,options:arguments,tag:"tracer",name:"Stream.pauseEffect"});return e._pauseOneEffect({soundId:t},i)},e.pauseAllEffects=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:t,name:"Stream.pauseAllEffects"}),i=!1,o=0,r=0,s=function(e){i||(e?(n(e),i=!0):o+=1,o===r&&(n(null),i=!0))};for(var d in e.audioMixing.sounds)"-1"!==d&&e.audioMixing.sounds[d].state===e.audioMixing.states.BUSY&&(r++,e._pauseOneEffect({soundId:d},s));r||n(null)},e.resumeEffect=function(t,n){Q(t,"soundId",1,1e4);var i=a.b.reportApiInvoke(e.sid,{callback:n,options:arguments,tag:"tracer",name:"Stream.resumeEffect"});return e._resumeOneEffect({soundId:t},i)},e.resumeAllEffects=function(t){var n=a.b.reportApiInvoke(e.sid,{callback:t,name:"Stream.resumeAllEffects"}),i=!1,o=0,r=0,s=function(e){i||(e?(n(e),i=!0):o+=1,o===r&&(n(null),i=!0))};for(var d in e.audioMixing.sounds)"-1"!==d&&e.audioMixing.sounds[d].state===e.audioMixing.states.PAUSED&&(r++,e._resumeOneEffect({soundId:d},s));r||n(null)},e.getEffectsVolume=function(){var t=[];for(var n in e.audioMixing.sounds){var i=e.audioMixing.sounds[n];i&&"-1"!==n&&t.push({soundId:parseInt(n),volume:i.volume})}return t},e.setEffectsVolume=function(t,n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setEffectsVolume",options:arguments,tag:"tracer",callback:n});for(var o in Q(t,"volume",0,100),e.audioMixing.defaultVolume=t,e.audioMixing.sounds){var r=e.audioMixing.sounds[o];"-1"!==o&&(r.volume=t)}e._flushAudioMixingMuteStatus(),i(null)},e.setVolumeOfEffect=function(t,n,i){var o=a.b.reportApiInvoke(e.sid,{name:"Stream.setVolumeOfEffect",options:arguments,tag:"tracer",callback:i});Q(t,"soundId",0,1e4),Q(n,"volume",0,100),e._initSoundIfNotExists(t),e.audioMixing.sounds[t].volume=n,e._flushAudioMixingMuteStatus(),o(null)}}(t),function(e,t){e.videoConstraint={},t.cameraId&&(e.videoConstraint.deviceId={exact:t.cameraId}),e.videoSize&&(e.videoConstraint.width=e.videoSize[0],e.videoConstraint.height=e.videoSize[1]),Object(p.isLegacyChrome)()||(e.videoConstraint.frameRate={min:30,max:30}),e.audioConstraint={},t.microphoneId&&(e.audioConstraint.deviceId={exact:t.microphoneId}),Object(p.isLegacyChrome)()||e.audioProcessing&&(void 0!==e.audioProcessing.AGC&&(Object(p.isFireFox)()?e.audioConstraint.autoGainControl=e.audioProcessing.AGC:Object(p.isChrome)()&&(e.audioConstraint.googAutoGainControl=e.audioProcessing.AGC,e.audioConstraint.googAutoGainControl2=e.audioProcessing.AGC)),void 0!==e.audioProcessing.AEC&&(e.audioConstraint.echoCancellation=e.audioProcessing.AEC),void 0!==e.audioProcessing.ANS&&(Object(p.isFireFox)()?e.audioConstraint.noiseSuppression=e.audioProcessing.ANS:Object(p.isChrome)()&&(e.audioConstraint.googNoiseSuppression=e.audioProcessing.ANS))),e.screenConstraint={},t.sourceId&&(e.screenConstraint.sourceId=t.sourceId),t.extensionId&&Object(p.isChrome)()?(e.screenConstraint.extensionId=t.extensionId,e.screenConstraint.mandatory={chromeMediaSource:"desktop",maxWidth:e.screenAttributes.width,maxHeight:e.screenAttributes.height,maxFrameRate:e.screenAttributes.maxFr,minFrameRate:e.screenAttributes.minFr}):(e.screenConstraint.mediaSource="screen",e.screenConstraint.width=e.screenAttributes.width,e.screenConstraint.height=e.screenAttributes.height,e.screenConstraint.frameRate={ideal:e.screenAttributes.maxFr,max:e.screenAttributes.maxFr}),t.mediaSource&&(e.screenConstraint.mediaSource=t.mediaSource),e.setVideoResolution=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoResolution",options:arguments,tag:"tracer"});if(!(n instanceof Array)){var r=se(n+="");return r&&r.video?(e.videoConstraint=v()(e.videoConstraint,{width:{ideal:r.video.width},height:{ideal:r.video.height}}),t.attributes.resolution=r.attributes.resolution,(s=e.stream&&e.stream.getVideoTracks&&e.stream.getVideoTracks()[0])&&s.applyConstraints?(o.default.debug("setVideoResolution applyConstraints",e.videoConstraint),s.applyConstraints(e.videoConstraint).then(i).catch(i)):i(),!0):(i("NO_PROFILE_".concat(n)),!1)}var s,d=n[0],c=n[1];e.videoConstraint=v()(e.videoConstraint,{width:{ideal:d},height:{ideal:c}}),t.attributes.resolution="".concat(d,"x").concat(c),(s=e.stream&&e.stream.getVideoTracks&&e.stream.getVideoTracks()[0])&&s.applyConstraints?(o.default.debug("setVideoResolution applyConstraints",e.videoConstraint),s.applyConstraints(e.videoConstraint).then(i).catch(i)):i()},e.setVideoFrameRate=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoFrameRate",options:arguments,tag:"tracer"});if(Object(p.isFireFox)())return i("FIREFOX_NOT_SUPPORTED"),!1;if("object"===z()(n)&&n instanceof Array&&n.length>1){e.videoConstraint=v()(e.videoConstraint,{frameRate:{ideal:n[0],max:n[1]}}),t.attributes.minFrameRate=n[0],t.attributes.maxFrameRate=n[1];var r=e.stream&&e.stream.getVideoTracks&&e.stream.getVideoTracks()[0];return r&&r.applyConstraints?(o.default.debug("setVideoFrameRate applyConstraints",e.videoConstraint),r.applyConstraints(e.videoConstraint).then(i).catch(i)):i(),!0}return i("INVALID_PARAM_".concat(JSON.stringify(n))),!1},e.setVideoBitRate=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoBitRate",options:arguments,tag:"tracer"});return"object"===z()(n)&&n instanceof Array&&n.length>1?(t.attributes.minVideoBW=n[0],t.attributes.maxVideoBW=n[1],e.connectionSpec&&(e.connectionSpec.minVideoBW=n[0],e.connectionSpec.maxVideoBW=n[1]),e.pc&&e.pc.renegotiate&&e.pc.renegotiate(),i(),!0):(i("INVALID_PARAM_".concat(JSON.stringify(n))),!1)},e.setScreenBitRate=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setScreenBitRate",options:arguments,tag:"tracer"});return"object"===z()(n)&&n instanceof Array&&n.length>1?(t.screenAttributes.minVideoBW=n[0],t.screenAttributes.maxVideoBW=n[1],i(),!0):(i("INVALID_PARAM_".concat(JSON.stringify(n))),!1)},e.setScreenProfile=function(t){var n=a.b.reportApiInvoke(e.sid,{name:"Stream.setScreenProfile",options:arguments,tag:"tracer"});K(t,"profile",["480p_1","480p_2","720p_1","720p_2","1080p_1","1080p_2"]);var i=se(t);return i&&i.screen?(e.screenConstraint=v()(e.screenConstraint,i.screen),e.screenAttributes.width=i.screen.width,e.screenAttributes.height=i.screen.height,e.screenAttributes.minFr=i.screen.frameRate.min,e.screenAttributes.maxFr=i.screen.frameRate.max,n(),!0):(n("NO_SCREEN_PROFILE_".concat(JSON.stringify(t))),!1)},e.setVideoProfileCustom=function(t){var n=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoProfileCustom",options:arguments,tag:"tracer"});e.setVideoResolution(t[0]),e.setVideoFrameRate([t[1],t[1]]),e.setVideoBitRate([t[2],t[2]]),n()},e.setVideoProfileCustomPlus=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoProfileCustom",options:arguments,tag:"tracer"});e.videoConstraint.width=n.width,e.videoConstraint.height=n.height,t.attributes.resolution="".concat(n.width,"x").concat(n.height),e.setVideoFrameRate([n.framerate,n.framerate]),e.setVideoBitRate([n.bitrate,n.bitrate]),i()},e.setVideoProfile=function(n){var i=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoProfile",options:arguments,tag:"tracer"}),r=se(n);if(!r){var s="Invalid Profile ".concat(n);throw new Error(s)}if(e.profile=n,r&&r.video){e.profile=r.profileName,e.videoConstraint=v()(e.videoConstraint,r.video),e.connectionSpec&&r.attributes.maxVideoBW&&(e.connectionSpec.minVideoBW=r.attributes.minVideoBW,e.connectionSpec.maxVideoBW=r.attributes.maxVideoBW),Object(p.isEdge)()&&(e.videoConstraint.frameRate.max=60),Object(p.isFireFox)()&&(e.videoConstraint.frameRate={ideal:30,max:30}),t.attributes=v()(t.attributes,r.attributes),e.pc&&e.pc.renegotiate&&e.pc.renegotiate();var d=e.stream&&e.stream.getVideoTracks&&e.stream.getVideoTracks()[0];return d&&d.applyConstraints?(o.default.debug("setVideoProfile applyConstraints",e.videoConstraint),d.applyConstraints(e.videoConstraint).then(function(t){i(t),Object(W.h)(e.stream,function(t,n){e.videoWidth=t,e.videoHeight=n},function(t){o.default.warning("[".concat(e.streamId,"] vsResHack failed: "),t)})}).catch(i)):i(),!0}return i("INVALID_VIDEO_PROFILE_".concat(n)),!1},e.setAudioProfile=function(t){var n=a.b.reportApiInvoke(e.sid,{name:"Stream.setAudioProfile",options:arguments,tag:"tracer"});K(t,"profile",["speech_low_quality","speech_standard","music_standard","standard_stereo","high_quality","high_quality_stereo"]),e.audioProfile=t;var i=ce(t);return e.highQuality=i.highQuality,e.stereo=i.stereo,e.speech=i.speech,e.lowQuality=i.lowQuality,e.stereo&&Object(p.isChrome)()&&(e.audioConstraint.googAutoGainControl=!1,e.audioConstraint.googAutoGainControl2=!1,e.audioConstraint.echoCancellation=!1,e.audioConstraint.googNoiseSuppression=!1),n(),!0},e.setVideoEncoderConfiguration=function(t){Y(t,"config");var n=a.b.reportApiInvoke(e.sid,{name:"Stream.setVideoEncoderConfiguration",options:t,tag:"tracer"});t.resolution&&(Q(t.resolution.width,"config.resolution.width"),Q(t.resolution.height,"config.resolution.height"),e.setVideoResolution([t.resolution.width,t.resolution.height])),t.frameRate&&(Q(t.frameRate.min,"config.frameRate.min"),Q(t.frameRate.max,"config.frameRate.max"),e.setVideoFrameRate([t.frameRate.min,t.frameRate.max])),t.bitrate&&(Q(t.bitrate.min,"config.bitrate.min",1,1e7),Q(t.bitrate.max,"config.bitrate.max",1,1e7),e.setVideoBitRate([t.bitrate.min,t.bitrate.max])),n()},e.getSupportedProfile=function(t){var n=a.b.reportApiInvoke(e.sid,{name:"Stream.getSupportedProfile",options:arguments,tag:"tracer",callback:t});if(!e.local){var i="ONLY_LOCAL_STREAM_SUPPORTED";return o.default.error(i),n(i)}if(!e.stream)return i="STREAM_NOT_INIT",o.default.error(i),n(i);if(!e.stream.getVideoTracks)return i="TRACK_NOT_SUPPORT",o.default.error(i),n(i);var r=e.stream.getVideoTracks()[0];if(!r)return i="NO_VIDEO_TRACK_FOUND",o.default.error(i),n(i);if(!r.getCapabilities)return i="GETCAPABILITY_NOT_SUPPORT",o.default.error(i),n(i);var s=r.getCapabilities();return n(null,de(s))}}(t,e),t.on("collectStats",function(e){e.promises.push(t._getPCStats(e.interval)),e.promises.push(new Promise(function(e){var n={};t.pc&&t.pc.isSubscriber?null!==window.navigator.userAgent.match("Firefox")&&(H(n,"videoReceiveResolutionHeight",t.videoHeight),H(n,"videoReceiveResolutionWidth",t.videoWidth)):t.pc&&!t.pc.isSubscriber&&((Object(p.isSafari)()||Object(p.isFireFox)())&&(H(n,"videoSendResolutionHeight",t.videoHeight),H(n,"videoSendResolutionWidth",t.videoWidth)),(Object(p.isSafari)()||Object(p.isFireFox)())&&t.uplinkStats&&H(n,"videoSendPacketsLost",t.uplinkStats.uplink_cumulative_lost)),e(n)})),e.promises.push(new Promise(function(e){var n={};return t.traffic_stats&&t.pc&&t.pc.isSubscriber?(H(n,"accessDelay",t.traffic_stats.access_delay),H(n,"endToEndDelay",t.traffic_stats.e2e_delay),H(n,"videoReceiveDelay",t.traffic_stats.video_delay),H(n,"audioReceiveDelay",t.traffic_stats.audio_delay)):t.traffic_stats&&t.pc&&!t.pc.isSubscriber&&H(n,"accessDelay",t.traffic_stats.access_delay),e(n)}))}),t.getId=function(){return t.streamId},t.getUserId=function(){return t.userId},t.setUserId=function(e){var n=a.b.reportApiInvoke(t.sid,{name:"Stream.setUserId",options:arguments,tag:"tracer"});t.userId&&o.default.warning("[".concat(t.streamId,"] Stream.userId ").concat(t.userId," => ").concat(e)),t.userId=e,n()},t.getAttributes=function(){return e.screen?t.screenAttributes:e.attributes},t.hasAudio=function(){return t.audio},t.hasVideo=function(){return t.video},t.hasScreen=function(){return t.screen},t.isVideoOn=function(){return(t.hasVideo()||t.hasScreen())&&!t.userMuteVideo},t.isAudioOn=function(){return t.hasAudio()&&!t.userMuteAudio},t.init=function(i,r){var s=a.b.reportApiInvoke(t.sid,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Stream.init",options:arguments,tag:"tracer"}),d=((new Date).getTime(),arguments[2]);if(void 0===d&&(d=2),!0===t.initialized)return s({type:"warning",msg:"STREAM_ALREADY_INITIALIZED"});if(!0!==t.local)return s({type:"warning",msg:"STREAM_NOT_LOCAL"});t.videoSource?t.videoName="videoSource":t.video&&(t.videoName=G.searchDeviceNameById(e.cameraId)||"default"),t.audioSource?t.audioName="audioSource":t.audio&&(t.audioName=G.searchDeviceNameById(e.microphoneId)||"default"),t.screen&&(t.screenName=e.extensionId||"default");try{if(e.audio||e.video||e.screen||e.videoSource||e.audioSource){o.default.debug("[".concat(t.streamId,"] Requested access to local media"));var c={streamId:t.streamId};e.videoSource?c.videoSource=e.videoSource:e.screen?c.screen=t.screenConstraint:e.video&&(c.video=t.videoConstraint),e.audioSource?c.audioSource=e.audioSource:e.audio&&(c.audio=t.audioConstraint),j(c,function(i){c.screen&&o.default.debug("[".concat(t.streamId,"] User has granted access to screen sharing")),(c.video||c.audio)&&o.default.debug("[".concat(t.streamId,"] User has granted access to local media")),t.dispatchEvent({type:"accessAllowed"}),t.stream=i,t.initialized=!0,t.reloadDeviceName(),t.hasVideo()&&Object(W.h)(i,function(e,n){t.videoWidth=e,t.videoHeight=n},function(e){o.default.warning("[".concat(t.streamId,"] vsResHack failed: "),e)}),e.screen&&t.stream&&t.stream.getVideoTracks()[0]&&(t.stream.getVideoTracks()[0].onended=function(){t.dispatchEvent({type:"stopScreenSharing"})}),t.stream&&t.stream.getTracks&&t.stream.getTracks().forEach(function(e){e&&!e.onended&&(e.onended=n)}),s()},function(e){var n={type:"error",info:null};switch(e&&(n.msg=e.name||e.code||e,e.message&&(n.info=e.message),e.code&&(n.info?n.info+=". "+e.code:n.info=" "+e.code),e.constraint&&(n.info?n.info+=". Constraint: "+e.constraint:n.info="constraint: "+e.constraint)),n.msg){case"Starting video failed":case"TrackStartError":if(t.videoConstraint&&(delete t.videoConstraint.width,delete t.videoConstraint.height),d>0)return void setTimeout(function(){t.init(function(e){return s(e)},s,d-1)},1);n.msg="MEDIA_OPTION_INVALID";break;case"DevicesNotFoundError":n.msg="DEVICES_NOT_FOUND";break;case"NotSupportedError":n.msg="NOT_SUPPORTED";break;case"PermissionDeniedError":case"InvalidStateError":n.msg="PERMISSION_DENIED",t.dispatchEvent({type:"accessDenied"});break;case"PERMISSION_DENIED":case"NotAllowedError":t.dispatchEvent({type:"accessDenied"});break;case"ConstraintNotSatisfiedError":n.msg="CONSTRAINT_NOT_SATISFIED";break;default:n.msg||(n.msg="UNDEFINED")}var i="Media access ".concat(n.msg).concat(n.info?": "+n.info:"");o.default.error("[".concat(t.streamId,"] "),i),s(n)})}else s({type:"warning",msg:"STREAM_HAS_NO_MEDIA_ATTRIBUTES"})}catch(e){o.default.error("[".concat(t.streamId,"] Stream init: "),e),s({type:"error",msg:e.message||e})}},t.reloadDeviceName=function(){if(t.stream){if(t.stream.getVideoTracks){var e=t.stream.getVideoTracks()[0];e&&e.label&&(t.videoName=e.label)}if(t.stream.getAudioTracks){var n=t.stream.getAudioTracks()[0];n&&n.label&&(t.audioName=n.label)}}},t.close=function(){var e=a.b.reportApiInvoke(null,{name:"Stream.close",options:arguments,tag:"tracer"});if(o.default.debug("[".concat(t.streamId,"] Close stream with id"),t.streamId),void 0!==t.stream){var n=t.stream.getTracks();for(var i in n)n.hasOwnProperty(i)&&n[i].stop();t.stream=void 0}Object(p.isSafari)()&&t.pc&&t.pc.peerConnection&&t.pc.peerConnection.removeTrack&&t.pc.peerConnection.getSenders&&t.pc.peerConnection.getSenders().forEach(function(e){e&&(o.default.debug("[".concat(t.streamId,"] Remove Track"),e),t.pc.peerConnection.removeTrack(e))});t.initialized=!1,t._onAudioMute=void 0,t._onAudioUnmute=void 0,t._onVideoMute=void 0,t._onVideoUnmute=void 0,t.lowStream&&t.lowStream.close(),e()},t.enableAudio=function(){var e,n=a.b.reportApiInvoke(t.sid,{name:"Stream.enableAudio",options:arguments,tag:"tracer"});return o.default.deprecate("[".concat(t.streamId,"] Stream.enableAudio is deprecated and will be removed in the future. Use Stream.unmuteAudio instead")),t.userMuteAudio||o.default.warning("[".concat(t.streamId,"] User already enableAudio")),t.userMuteAudio=!1,n(null,e=!t.peerMuteAudio&&t._unmuteAudio()),e},t.disableAudio=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.disableAudio",options:arguments,tag:"tracer"});o.default.deprecate("[".concat(t.streamId,"] Stream.disableAudio is deprecated and will be removed in the future. Use Stream.muteAudio instead")),t.userMuteAudio&&o.default.warning("[".concat(t.streamId,"] User already disableAudio")),t.userMuteAudio=!0;var n=t._muteAudio();return e(null,n),n},t.enableVideo=function(){var e,n=a.b.reportApiInvoke(t.sid,{name:"Stream.enableVideo",options:arguments,tag:"tracer"});return o.default.deprecate("[".concat(t.streamId,"] Stream.enableVideo is deprecated and will be removed in the future. Use Stream.unmuteVideo instead")),t.userMuteVideo||o.default.warning("[".concat(t.streamId,"] User already enableVideo")),t.userMuteVideo=!1,t.lowStream&&(t.lowStream.userMuteVideo=!1),n(null,e=!t.peerMuteVideo&&t._unmuteVideo()),e},t.disableVideo=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.disableVideo",options:arguments,tag:"tracer"});o.default.deprecate("[".concat(t.streamId,"] Stream.disableVideo is deprecated and will be removed in the future. Use Stream.muteVideo instead")),t.userMuteVideo&&o.default.warning("[".concat(t.streamId,"] User already disableVideo")),t.userMuteVideo=!0,t.lowStream&&(t.lowStream.userMuteVideo=!0);var n=t._muteVideo();return e(null,n),n},t.unmuteAudio=function(){var e,n=a.b.reportApiInvoke(t.sid,{name:"Stream.unmuteAudio",options:arguments,tag:"tracer"});return t.userMuteAudio||o.default.warning("[".concat(t.streamId,"] User already unmuteAudio")),t.userMuteAudio=!1,n(null,e=!t.peerMuteAudio&&t._unmuteAudio()),e},t.muteAudio=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.muteAudio",options:arguments,tag:"tracer"});t.userMuteAudio&&o.default.warning("[".concat(t.streamId,"] User already muteAudio")),t.userMuteAudio=!0;var n=t._muteAudio();return e(null,n),n},t.unmuteVideo=function(){var e,n=a.b.reportApiInvoke(t.sid,{name:"Stream.unmuteVideo",options:arguments,tag:"tracer"});return t.userMuteVideo||o.default.warning("[".concat(t.streamId,"] User already unmuteVideo")),t.userMuteVideo=!1,t.lowStream&&(t.lowStream.userMuteVideo=!1),n(null,e=!t.peerMuteVideo&&t._unmuteVideo()),e},t.muteVideo=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.muteVideo",options:arguments,tag:"tracer"});t.userMuteVideo&&o.default.warning("[".concat(t.streamId,"] User already muteVideo")),t.userMuteVideo=!0,t.lowStream&&(t.lowStream.userMuteVideo=!0);var n=t._muteVideo();return e(null,n),n},t._unmuteAudio=function(){return o.default.debug("[".concat(t.streamId,"] Unmuted audio stream with id "),t.streamId),t._flushAudioMixingMuteStatus(!1),!(!t.hasAudio()||!t.initialized||void 0===t.stream||!0===t.stream.getAudioTracks()[0].enabled)&&(t._onAudioUnmute&&t._onAudioUnmute(),t.pc&&(t.pc.isAudioMute=!1),t.stream.getAudioTracks()[0].enabled=!0,!0)},t._isAudioMuted=function(){if(t.stream&&t.hasAudio()){var e=t.stream.getAudioTracks();return e.length>0&&!e[0].enabled}return!1},t._muteAudio=function(){return o.default.debug("[".concat(t.streamId,"] Muted audio stream with id "),t.streamId),t._flushAudioMixingMuteStatus(!0),!!(t.hasAudio()&&t.initialized&&void 0!==t.stream&&t.stream.getAudioTracks()[0].enabled)&&(t._onAudioMute&&t._onAudioMute(),t.pc&&(t.pc.isAudioMute=!0),t.stream.getAudioTracks()[0].enabled=!1,t.sid&&a.b.audioSendingStopped(t.sid,{succ:!0,reason:"muteAudio"}),!0)},t._unmuteVideo=function(){return o.default.debug("[".concat(t.streamId,"] Unmuted video stream with id"),t.streamId),!(!t.initialized||void 0===t.stream||!t.stream.getVideoTracks().length||!0===t.stream.getVideoTracks()[0].enabled)&&(t._onVideoUnmute&&t._onVideoUnmute(),t.pc&&(t.pc.isVideoMute=!1),t.stream.getVideoTracks()[0].enabled=!0,t.lowStream&&t.lowStream._unmuteVideo(),!0)},t._muteVideo=function(){return o.default.debug("[".concat(t.streamId,"] Muted video stream with id"),t.streamId),!!(t.initialized&&void 0!==t.stream&&t.stream.getVideoTracks().length&&t.stream.getVideoTracks()[0].enabled)&&(t._onVideoMute&&t._onVideoMute(),t.pc&&(t.pc.isVideoMute=!0),t.stream.getVideoTracks()[0].enabled=!1,t.lowStream&&t.lowStream._muteVideo(),t.sid&&a.b.videoSendingStopped(t.sid,{succ:!0,reason:"muteVideo"}),!0)},t.addTrack=function(i){var o=a.b.reportApiInvoke(t.sid,{name:"Stream.addTrack",options:arguments,tag:"tracer"});if(t.pc&&t.pc.addTrack(i,t.stream),"audio"==i.kind){t._cleanupAudioMixing();var r=new MediaStream;t.userMuteAudio&&(i.enabled=!1),r.addTrack(i);var s=t.stream.getVideoTracks()[0];s&&(r.addTrack(s),t.audio=!0,e.audio=!0),t.stream=r,t.audioLevelHelper=null,t.player&&t.player.video&&(t.player.video.srcObject=t.stream)}else t.userMuteVideo&&(i.enabled=!1),t.stream.addTrack(i),t.video=!0,e.video=!0;i.onended||(i.onended=n),o()},t.removeTrack=function(n){var i=a.b.reportApiInvoke(t.sid,{name:"Stream.removeTrack",options:arguments,tag:"tracer"});t.pc&&t.pc.removeTrack(n,t.stream),t.stream.removeTrack(n),t._cleanupAudioMixing(),"audio"===n.kind?(t.audio=!1,e.audio=!1):(t.video=!1,e.video=!1),t.audioLevelHelper=null,"live"==n.readyState&&(n.stop(),o.default.debug("[".concat(t.streamId,"] Track ").concat(n.kind," Stopped"))),i()},t.setAudioOutput=function(e,n,i){var r=a.b.reportApiInvoke(t.sid,{callback:function(e,t){if(e)return i&&i(e);n&&n(t)},name:"Stream.setAudioOutput",options:arguments,tag:"tracer"});return $(e,1,255)?(t.audioOutput=e,t.player?void t.player.setAudioOutput(e,function(){return r()},r):r()):(o.default.error("[".concat(t.streamId,"] setAudioOutput Invalid Parameter"),e),r(E.INVALID_PARAMETER))},t.play=function(e,n,i){"function"==typeof n&&(i=n,n=null),o.default.debug("[".concat(t.streamId,"] play()."),e,n);var r=a.b.reportApiInvoke(t.sid,{name:"Stream.play",options:arguments,tag:"tracer",callback:i});if(q(e,"elementID"),ae(n)||(ae(n.fit)||K(n.fit,"fit",["cover","contain"]),ae(n.muted)||X(n.muted,"muted")),t.player)o.default.warning("[".concat(t.streamId,"] Stream.play(): Stream is already playing. Fallback to resume stream")),t.resume().then(function(){r(null)}).catch(r);else{t.elementID=e,t.playOptions=n,!t.local||t.video||t.screen?t.player=new A({id:t.getId(),stream:t,elementID:e,options:n}):t.hasAudio()&&(t.player=new A({id:t.getId(),stream:t,elementID:e,options:n}));var s={audio:null,video:null};t.on("player-status-change",function e(n){if(s[n.mediaType]=n,s.audio&&s.video)if(t.removeEventListener("player-status-change",e),s.video.isErrorState||s.audio.isErrorState){var i=s.video.isErrorState?s.video:s.audio;r({isErrorState:!0,status:i.status,reason:i.reason,video:s.video,audio:s.audio})}else"aborted"===s.video.status&&"aborted"===s.audio.status?r({status:"aborted",reason:"stop",video:s.video,audio:s.audio}):r(null)}),t.audioOutput&&t.player.setAudioOutput(t.audioOutput),void 0!==t.audioLevel&&t.player.setAudioVolume(t.audioLevel),t._flushAudioMixingMuteStatus(!1)}},t.stop=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.stop",options:arguments,tag:"tracer"});o.default.debug("[".concat(t.streamId,"] Stop stream player with id "),t.streamId),t.player?(t.player.destroy(),delete t.player):o.default.error("[".concat(t.streamId,"] Stream.stop(): Stream is not playing")),t._flushAudioMixingMuteStatus(!0),e()},t.isPlaying=function(){return!!t.player},t.isPaused=function(){return!!t.player&&(!!(t.player.video&&t.player.video.paused&&t.player.mediaElemExists(t.player.video))||!!(t.player.audio&&t.player.audio.paused&&t.player.mediaElemExists(t.player.audio)))},t.resume=function(){var e,n;return t.player?(t.player.video&&t.player.video.play&&(e=t.player.video.play()),e=e||Promise.resolve(),t.player.audio&&t.player.audio.play&&(n=t.player.audio.play()),n=n||Promise.resolve(),Promise.all([e,n])):Promise.reject("NO_PLAYER_FOUND")},t.getVideoTrack=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.getVideoTrack",options:arguments,tag:"tracer"});if(t.stream&&t.stream.getVideoTracks){var n=t.stream.getVideoTracks()[0];if(n)return o.default.info("[".concat(t.streamId,"] getVideoTrack"),n),e(),n}o.default.info("[".concat(t.streamId,"] getVideoTrack None")),e(null,"getVideoTrack None")},t.getAudioTrack=function(){var e=a.b.reportApiInvoke(t.sid,{name:"Stream.getAudioTrack",options:arguments,tag:"tracer"});if(t.stream&&t.stream.getAudioTracks){var n=t.stream.getAudioTracks()[0];if(n)return o.default.info("[".concat(t.streamId,"] getAudioTracks"),n),e(),n}o.default.info("[".concat(t.streamId,"] getAudioTracks None")),e(null,"getAudioTracks None")},t._replaceMediaStreamTrack=function(e,n,i){if(t.stream){if("video"==e.kind){if(r=t.stream.getVideoTracks()[0])return t.userMuteVideo&&(e.enabled=!1),t.stream.removeTrack(r),t.stream.addTrack(e),o.default.debug("[".concat(t.streamId,"] _replaceMediaStreamTrack ").concat(e.kind," SUCCESS")),"live"==r.readyState&&(r.stop(),o.default.debug("[".concat(t.streamId,"] Track ").concat(r.kind," Stopped"))),n&&n();var a="MEDIASTREAM_TRACK_NOT_FOUND";return o.default.error("[".concat(t.streamId,"] MEDIASTREAM_TRACK_NOT_FOUND ").concat(e.kind)),i(a)}if("audio"==e.kind){var r;if(r=t.stream.getAudioTracks()[0]){t.userMuteAudio&&(e.enabled=!1);var s=new MediaStream;s.addTrack(e);var d=t.stream&&t.stream.getVideoTracks()[0];return d&&s.addTrack(d),t.stream=s,t.audioLevelHelper=null,t.player&&t.player.video&&(t.player.video.srcObject=t.stream),o.default.debug("[".concat(t.streamId,"] _replaceMediaStreamTrack SUCCESS")),"live"==r.readyState&&(r.stop(),o.default.debug("[".concat(t.streamId,"] Track ").concat(r.kind," Stopped"))),n&&n()}a="MEDIASTREAM_TRACK_NOT_FOUND";return o.default.error("[".concat(t.streamId,"] MEDIASTREAM_TRACK_NOT_FOUND ").concat(e.kind)),i(a)}a="INVALID_TRACK_TYPE";return o.default.error("[".concat(t.streamId,"] _replaceMediaStreamTrack ").concat(a," ").concat(e.kind)),i&&i(a)}a="NO_STREAM_FOUND";return o.default.error("[".concat(t.streamId,"] _replaceMediaStreamTrack ").concat(a)),i&&i(a)},t.replaceTrack=function(e,i,r){var s=a.b.reportApiInvoke(t.sid,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Stream.replaceTrack",options:arguments,tag:"tracer"});return e&&e.kind?(t._cleanupAudioMixing(),e.onended||(e.onended=n),t.pc&&t.pc.hasSender&&t.pc.hasSender(e.kind)?void t.pc.replaceTrack(e,function(){return o.default.debug("[".concat(t.streamId,"] PeerConnection.replaceTrack ").concat(e.kind," SUCCESS")),t._replaceMediaStreamTrack(e,function(e){return s(null,e)},s)},function(n){return o.default.error("[".concat(t.streamId,"] PeerConnection.replaceTrack ").concat(e.kind," Failed ").concat(n)),s(n)}):t._replaceMediaStreamTrack(e,function(e){return s(null,e)},s)):s("INVALID_TRACK")},t.setAudioVolume=function(e){var n=a.b.reportApiInvoke(t.sid,{name:"Stream.setAudioVolume",options:arguments,tag:"tracer"});Q(e,"level",0,100),t.audioLevel=e,t.player&&t.player.setAudioVolume(e),n()},t.getStats=function(e,n,i){var o={type:"collectStats",promises:[],interval:i};t.dispatchEvent(o),Promise.all(o.promises).then(function(n){for(var i={},o=n.length-1;o>=0;o--){var a=n[o];v()(i,a)}e&&setTimeout(e.bind(t,i),0)}).catch(function(e){n&&setTimeout(n.bind(t,e),0)})},t._getPCStats=function(e){return new Promise(function(n,i){if(!t.pc||"established"!==t.pc.state||!t.pc.getStats){return i("PEER_CONNECTION_NOT_ESTABLISHED")}t.pc.getStats(function(e){if(!t.pc||"established"!==t.pc.state||!t.pc.getStats){return i("PEER_CONNECTION_STATE_CHANGE")}var o=t.pc.isSubscriber?function(e){var t={};return e.forEach(function(e){e.id&&(-1===e.id.indexOf("recv")&&-1===e.id.indexOf("inbound_rtp")&&-1===e.id.indexOf("inbound-rtp")&&-1===e.id.indexOf("InboundRTP")||("audio"===e.mediaType?(H(t,"audioReceiveBytes",e.bytesReceived),H(t,"audioReceivePackets",e.packetsReceived),H(t,"audioReceivePacketsLost",e.packetsLost)):(H(t,"videoReceiveBytes",e.bytesReceived),H(t,"videoReceivePacketsLost",e.packetsLost),H(t,"videoReceivePackets",e.packetsReceived),H(t,"videoReceiveFrameRate",e.googFrameRateReceived),H(t,"videoReceiveDecodeFrameRate",e.googFrameRateDecoded),H(t,"videoReceiveResolutionWidth",e.googFrameWidthReceived),H(t,"videoReceiveResolutionHeight",e.googFrameHeightReceived))))}),t}(e):function(e){var t={};return e.forEach(function(e){e.id&&(-1===e.id.indexOf("send")&&-1===e.id.indexOf("outbound_rtp")&&-1===e.id.indexOf("OutboundRTP")||("audio"===e.mediaType?(H(t,"audioSendBytes",e.bytesSent),H(t,"audioSendPackets",e.packetsSent),H(t,"audioSendPacketsLost",e.packetsLost)):(H(t,"videoSendBytes",e.bytesSent),H(t,"videoSendPackets",e.packetsSent),H(t,"videoSendPacketsLost",e.packetsLost),H(t,"videoSendFrameRate",e.googFrameRateSent),H(t,"videoSendResolutionWidth",e.googFrameWidthSent),H(t,"videoSendResolutionHeight",e.googFrameHeightSent))))}),t}(e);return n(o)},e)}).then(function(e){return t.pc.isSubscriber?(Object(p.isFireFox)()||Object(p.isSafari)())&&(e.videoReceiveResolutionHeight&&"0"!==e.videoReceiveResolutionHeight||e.videoReceiveResolutionWidth&&"0"!==e.videoReceiveResolutionWidth||(H(e,"videoReceiveResolutionHeight",t.videoHeight),H(e,"videoReceiveResolutionWidth",t.videoWidth))):((Object(p.isSafari)()||Object(p.isFireFox)())&&(e.videoSendResolutionHeight&&"0"!==e.videoSendResolutionHeight||e.videoSendResolutionWidth&&"0"!==e.videoSendResolutionWidth||(H(e,"videoSendResolutionHeight",t.videoHeight),H(e,"videoSendResolutionWidth",t.videoWidth))),(Object(p.isSafari)()||Object(p.isFireFox)())&&t.uplinkStats&&H(e,"videoSendPacketsLost",t.uplinkStats.uplink_cumulative_lost)),Promise.resolve(e)})},t.getAudioLevel=function(){if(t.audioLevelHelper)return t.audioLevelHelper.getAudioLevel();if(t.stream){if(0!==t.stream.getAudioTracks().length)return t.audioLevelHelper=new W.a(t.stream),t.audioLevelHelper.getAudioLevel();o.default.warning("[".concat(t.streamId,"] can't get audioLevel beacuse no audio trace in stream"))}else o.default.warning("[".concat(t.streamId,"] can't get audioLevel beacuse no stream exist"))},t.setVideoProfile("480P"),t._switchVideoDevice=function(e,n,i){if(e===t.cameraId)return n&&n();var a={video:v()({},t.videoConstraint,{deviceId:{exact:e}}),audio:!1};o.default.debug("[".concat(t.streamId,"] ").concat(a)),j(a,function(o){try{var a=function(){t.isPlaying()&&(t.stop(),t.elementID&&t.play(t.elementID,t.playOptions)),t.cameraId=e,t.videoConstraint.deviceId={exact:e},t.userMuteVideo&&(t.stream.getVideoTracks()[0].enabled=!1),n&&n()};Object(p.isSafari)()?t.replaceTrack(o.getVideoTracks()[0],a,i):(t.removeTrack(t.stream.getVideoTracks()[0]),t.addTrack(o.getVideoTracks()[0]),a())}catch(e){return i&&i(e)}},function(e){return i&&i(e)})},t._switchAudioDevice=function(e,n,i){if(e===t.microphoneId)return n&&n();var a={video:!1,audio:v()({},t.audioConstraint,{deviceId:{exact:e}})};o.default.debug("[".concat(t.streamId,"] "),a),j(a,function(o){var a=function(){t._cleanupAudioMixing(),t.userMuteAudio&&(t.stream.getAudioTracks()[0].enabled=!1),t.isPlaying()&&(t.stop(),t.elementID&&t.play(t.elementID)),t.microphoneId=e,t.audioConstraint.deviceId={exact:e},n&&n()};try{Object(p.isSafari)()?t.replaceTrack(o.getAudioTracks()[0],a,i):(t.removeTrack(t.stream.getAudioTracks()[0]),t.addTrack(o.getAudioTracks()[0]),a())}catch(e){return i&&i(e)}},function(e){return i&&i(e)})},t.switchDevice=function(e,n,i,r){var s=a.b.reportApiInvoke(t.sid,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Stream.switchDevice",options:arguments,tag:"tracer"});q(n,"deviceId");var d=function(){return t.inSwitchDevice=!1,s()},c=function(e){t.inSwitchDevice=!1,o.default.error("[".concat(t.streamId,"] "),e),s(e)};if(t.inSwitchDevice)return s("Device switch is in process.");if(t.inSwitchDevice=!0,!t.local)return c("Only the local stream can switch the device.");if(t.screen&&"video"===e)return c("The device cannot be switched during screen-sharing.");if(t.videoSource||t.audioSource)return c("The device cannot be switched when using videoSource or audioSource.");if(t.lowStream)return c("The device cannot be switched when using lowstream.");var u=!1;for(var l in t.audioMixing.sounds){if(t.audioMixing.sounds[l].state!==t.audioMixing.states.IDLE){u=!0;break}}if(t.audioMixing.audioContextInited&&u)return c("The device cannot be switched when using audio Mixing.");G.getDeviceById(n,function(){if("video"===e)t._switchVideoDevice(n,d,c);else{if("audio"!==e)return c("Invalid type.");t._switchAudioDevice(n,d,c)}},function(){return c("The device does not exist.")})},t},le=n(13),pe=["live","rtc","web","interop","h264_interop","web-only"],fe=["vp8","h264"],me=["aes-128-xts","aes-256-xts","aes-128-ecb"],ge=function(e){e&&e.apply(this,[].slice.call(arguments,1))},ve=n(5),Se=function(e){var t=r();return t.needReconnect=!0,t.isTimeout=!1,t.isInit=!0,t.sendbytes=0,t.recvbytes=0,t.startTime=Date.now(),t.lastMsgTime=null,t.clientId=e.clientId,t.hostIndex=0,t.requestID=0,e.host instanceof Array?t.host=e.host:t.host=[e.host],t.getSendBytes=function(){return t.sendbytes},t.getRecvBytes=function(){return t.recvbytes},t.getDuration=function(){return Math.ceil((Date.now()-t.startTime)/1e3)},t.getURL=function(){return t.connection.url},t.reconnect=function(){t.isInit=!0,t.creatConnection()},t.connectNext=function(){t.isInit=!0,++t.hostIndex,o.default.debug("["+t.clientId+"] Gateway length:"+t.host.length+" current index:"+t.hostIndex),t.hostIndex>=t.host.length?t.dispatchEvent(u({type:"recover"})):t.creatConnection()},t.replaceHost=function(e){t.host=e||t.host,t.hostIndex=0,t.creatConnection()},t.creatConnection=function(){t.needReconnect=!0,o.default.debug("["+t.clientId+"] start connect:"+t.host[t.hostIndex]),t.lts=(new Date).getTime(),t.connection=new WebSocket("wss://"+t.host[t.hostIndex]),t.connection.onopen=function(e){o.default.debug("["+t.clientId+"] websockect opened: "+t.host[t.hostIndex]),t.needReconnect=!0,t.isTimeout=!1,t.isInit=!1,t.sendbytes=0,t.recvbytes=0,t.startTime=Date.now(),Object(ve.d)(),clearTimeout(t.timeoutCheck),t.dispatchEvent(u({type:"onopen",event:e,socket:t}))},t.connection.onmessage=function(e){t.recvbytes+=Object(W.e)(e.data);var n=JSON.parse(e.data);t.lastMsgTime=Date.now(),n.hasOwnProperty("_id")?t.dispatchEvent(u({type:n._id,msg:n})):n.hasOwnProperty("_type")&&t.dispatchSocketEvent(u({type:n._type,msg:n.message}))},t.connection.onclose=function(n){t.needReconnect?t.isTimeout||t.isInit?(o.default.debug("["+t.clientId+"] websockect connect timeout"),a.b.joinGateway(e.sid,{lts:t.lts,succ:!1,ec:"timeout",addr:t.connection.url}),t.connectNext()):t.dispatchEvent(u({type:"disconnect",event:n})):(o.default.debug("["+t.clientId+"] websockect closeed"),ge(e.onFailure,n),clearTimeout(t.timeoutCheck),t.dispatchEvent(u({type:"close",event:n})),t.connection.onopen=void 0,t.connection.onclose=void 0,t.connection.onerror=void 0,t.connection.onmessage=void 0,t.connection=void 0)},t.connection.onerror=function(e){},setTimeout(function(){t.connection&&t.connection.readyState!=WebSocket.OPEN&&(t.isTimeout=!0,t.connection.close())},5e3)},t.creatConnection(),t.sendMessage=function(e,n){if(t.connection&&t.connection.readyState==WebSocket.OPEN){var i=JSON.stringify(e);t.sendbytes+=Object(W.e)(i),t.connection.send(i)}else n({error:"Gateway not connected"})},t.disconnect=function(){t.needReconnect=!0,t.connection.close()},t.close=function(){t.needReconnect=!1,t.connection.onclose=void 0,t.connection.close()},t.sendSignalCommand=function(e,n){e._id="_request_"+t.requestID,t.requestID+=1,"publish_stats"!==e._type&&"subscribe_stats"!==e._type&&"publish_stats_low"!==e._type&&t.on(e._id,function(i){i.msg&&n&&n(i.msg._result,i.msg.message),delete t.dispatcher.eventListeners[e._id]}),t.sendMessage(e,function(e){e.reason="NOT_CONNECTED",n&&n(e.reason,e)})},t},Ie=function(e,t){var n={connect:function(){t.host=e,n.signal=Se(t),n.on=n.signal.on,n.dispatchEvent=n.signal.dispatchEvent,n.signal.on("onopen",function(e){n.signal.onEvent=function(e){n.dispatchEvent(u({type:e.event,msg:e}))},n.dispatchEvent(u({type:"connect",msg:e}))}),n.signal.on("onError",function(e){var t=e.msg;onError(t.code,"error")})},getLastMsgTime:function(){return n.signal&&n.signal.lastMsgTime},getSendBytes:function(){return n.signal.getSendBytes()},getRecvBytes:function(){return n.signal.getRecvBytes()},getDuration:function(){return n.signal.getDuration()},disconnect:function(){n.signal.disconnect()},close:function(){n.signal.close()},getURL:function(){return n.signal.getURL()},reconnect:function(){n.signal.reconnect()},connectNext:function(){n.signal.connectNext()},replaceHost:function(e){n.signal.replaceHost(e)},emitSimpleMessage:function(e,t){n.signal.sendSignalCommand(e,t)}};return n.connect(),n},he=function(e,t){var n=!1,r=0,s={command:"convergeAllocateEdge",sid:e.sid,appId:e.appId,token:e.token,uid:e.uid,cname:e.cname,ts:Math.floor(Date.now()/1e3),version:i.VERSION,seq:0,requestId:1};Object(i.getParameter)("PROXY_CS").map(function(d){var c=(new Date).getTime();ye("https://"+d+"/api/v1",s,function(s,u){if(s)return o.default.debug("["+e.clientId+"] Request proxy server failed: ",s),r++,a.b.requestProxyAppCenter(e.sid,{lts:c,succ:!1,APAddr:d,workerManagerList:null,ec:JSON.stringify(s),response:JSON.stringify({err:s,res:u})}),void(r>=Object(i.getParameter)("PROXY_CS").length&&t&&t("Get proxy server failed: request all failed"));if(!n)if((u=JSON.parse(u)).json_body){var l=JSON.parse(u.json_body);if(o.default.debug("["+e.clientId+"] App return:",l.servers),200!==l.code){s="Get proxy server failed: response code ["+l.code+"], reason [ "+l.reason+"]";o.default.debug("["+e.clientId+"] "+s),a.b.requestProxyAppCenter(e.sid,{lts:c,succ:!1,APAddr:d,workerManagerList:null,ec:s,response:JSON.stringify({err:s,res:u})})}else{n=!0;var p=be(l.servers);a.b.requestProxyAppCenter(e.sid,{lts:c,succ:!0,APAddr:d,workerManagerList:JSON.stringify(p),ec:null,response:JSON.stringify({res:u})}),t&&t(null,p)}}else o.default.debug("["+e.clientId+"] Get proxy server failed: no json_body"),a.b.requestProxyAppCenter(e.sid,{lts:c,succ:!1,APAddr:d,workerManagerList:null,ec:"Get proxy server failed: no json_body",response:JSON.stringify({res:u})})})})},ye=function(e,t,n){var i={service_name:"webrtc_proxy",json_body:JSON.stringify(t)};Object(ve.c)(e,i,function(e){n&&n(null,e)},function(e){n&&n(e)},{"X-Packet-Service-Type":0,"X-Packet-URI":61})},_e=function(e,t,n){var i=!1,r=0,s={command:"request",gatewayType:"http",appId:e.appId,cname:e.cname,uid:e.uid+"",sdkVersion:"2.3.1",sid:e.sid,seq:1,ts:+new Date,requestId:3,clientRequest:{appId:e.appId,cname:e.cname,uid:e.uid+"",sid:e.sid}};t.map(function(d){var c=(new Date).getTime();!function(e,t,n){Object(ve.c)(e,t,function(e){n&&n(null,e)},function(e){n&&n(e)})}("https://"+d+":4000/v2/machine",s,function(s,u){if(s)return o.default.debug("["+e.clientId+"] Request worker manager failed: ",s),r++,a.b.requestProxyWorkerManager(e.sid,{lts:c,succ:!1,workerManagerAddr:d,ec:JSON.stringify(s),response:JSON.stringify({res:u})}),void(r>=t.length&&n&&n("requeet worker manager server failed: request failed"));if(!i){if(!(u=JSON.parse(u)).serverResponse)return n&&n("requeet worker manager server failed: serverResponse is undefined");i=!0,a.b.requestProxyWorkerManager(e.sid,{lts:c,succ:!0,workerManagerAddr:d,ec:JSON.stringify(s),response:JSON.stringify({res:u})}),n&&n(null,{address:d,serverResponse:u.serverResponse})}})})},be=function(e){if(!e||[]instanceof Array==!1)return[];var t=[];return e.forEach(function(e){var n;e.address&&e.tcp?(e.address.match(/^[\.\:\d]+$/)?n="".concat(e.address.replace(/[^\d]/g,"-"),".edge.agora.io"):(o.default.info("["+joinInfo.clientId+"] "+"Cannot recognized as IP address ".concat(e.address,". Used As Host instead")),n="".concat(e.address,":").concat(e.tcp)),t.push(n)):o.default.error("["+joinInfo.clientId+"] Invalid address format ",e)}),t},Ee=function(e,t){var n=v()({},e),o=Object(i.getParameter)("WEBCS_DOMAIN").concat(Object(i.getParameter)("WEBCS_DOMAIN_BACKUP_LIST")),a=[],r=!1;(o=o.map(function(e){return n.proxyServer?"https://".concat(n.proxyServer,"/ap/?url=").concat(e+"/api/v1"):"https://".concat(e,"/api/v1")})).map(function(e){!function(e,t,n){var i={flag:64,cipher_method:0,timeout:1e3,features:t};Object(ve.c)(e,i,function(e){try{var t=JSON.parse(e);n&&n(null,t)}catch(e){n&&n(e)}n&&n(null,e)},function(e){n&&n(e)},{"X-Packet-Service-Type":0,"X-Packet-URI":54})}(e,n,function(e,n){r||(e?(a.push(e),a.length>=o.length&&t&&t("ALL_REQUEST_FAILED")):(r=!0,t&&t(null,n)))})})},Te={},Ae=function(e,t,n,i){var r=(new Date).getTime(),s="";t.multiIP&&t.multiIP.gateway_ip&&(s={vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]});var d={flag:4,ts:+new Date,key:t.appId,cname:t.cname,sid:t.sid,detail:{},uid:t.uid||0};s&&(d.detail[5]=JSON.stringify(s)),Object(ve.c)(e,d,function(s){try{var d=JSON.parse(s).res,c=d.code}catch(e){var u="requestChooseServer failed with unexpected body "+s;return o.default.error("["+joinInfo.clientId+"]",u),i(u)}if(c){var l=h[d.code]||c;return a.b.joinChooseServer(t.sid,{lts:r,succ:!1,csAddr:e,serverList:null,ec:l}),i("Get server node failed ["+l+"]",e,l)}var p=[],f=[".agora.io",".agoraio.cn"],m=0;if(e.indexOf(f[1])>-1&&(m=1),d.addresses.forEach(function(e){var t;e.ip&&e.port?(e.ip.match(/^[\.\:\d]+$/)?t="webrtc-".concat(e.ip.replace(/[^\d]/g,"-")).concat(f[m++%f.length],":").concat(e.port):(o.default.info("["+joinInfo.clientId+"] "+"Cannot recognized as IP address ".concat(e.ip,". Used As Host instead")),t="".concat(e.ip,":").concat(e.port)),p.push(t)):o.default.error("["+joinInfo.clientId+"] Invalid address format ",e)}),!p.length){o.default.error("["+joinInfo.clientId+"] Empty Address response",d);l="EMPTY_ADDRESS_RESPONSE";return a.b.joinChooseServer(t.sid,{lts:r,succ:!1,csAddr:e,serverList:null,ec:l}),i("Get server node failed ["+l+"]",e,l)}var g={gateway_addr:p,uid:d.uid,cid:d.cid,uni_lbs_ip:d.detail};return n(g,e)},function(e,n){"timeout"===e.type?(a.b.joinChooseServer(t.sid,{lts:r,succ:!1,csAddr:n,serverList:null,ec:"timeout"}),i("Connect choose server timeout",n)):a.b.joinChooseServer(t.sid,{lts:r,succ:!1,csAddr:n,serverList:null,ec:"server_wrong"})},{"X-Packet-Service-Type":0,"X-Packet-URI":44})},Ce=function(e,t,n){var r=!1,s=null,d=1,c=1,u=null,l=e.clientId;Te[l]=!0;var f=function t(n,c){if(!r){var f=!1,m=!1,g=[],v=p.getBrowserInfo()||{};Ee({device:v.name,system:v.os,vendor:e.appId,version:i.VERSION,cname:e.cname,sid:e.sid,session_id:Object(a.a)(),detail:"",proxyServer:n},function(t,n){m=!0;try{var i=Object.keys(n.test_tags)[0],o=JSON.parse(n.test_tags[i]);u=o[1]}catch(e){u=null}a.b.reportApiInvoke(e.sid,{name:"_config-distribute-request",options:{err:t,res:n}})(),f&&c&&c(g,u)}),function(e,t,n){for(var r=(new Date).getTime(),s=!1,d=!0,c=function(n,i){if(s)a.b.joinChooseServer(e.sid,{lts:r,succ:!0,csAddr:i,serverList:n.gateway_addr,cid:n.cid+"",uid:n.uid+"",ec:null},!1);else{if(clearTimeout(g),s=!0,o.default.debug("["+e.clientId+"] Get gateway address:",n.gateway_addr),e.proxyServer){for(var d=n.gateway_addr,c=0;c=3600?3600:2*d)})}};e.useProxyServer?function n(){!function(e,t){he(e,function(n,i){if(n)return t&&t(n);o.default.debug("["+e.clientId+"] getProxyServerList: ",i),_e(e,i,t)})}(e,function(i,r){if(i){if(o.default.debug("["+e.clientId+"]",i),!Te[l])return;return o.default.debug("["+e.clientId+"] Request proxy will be restart in "+c+"s"),s=setTimeout(function(){n()},1e3*c),void(c=c>=3600?3600:2*c)}clearTimeout(s);var d=r.address;e.proxyServer=d,e.turnServer={url:r.address,tcpport:r.serverResponse.tcpport||"3433",udpport:r.serverResponse.udpport||"3478",username:r.serverResponse.username||"test",credential:r.serverResponse.password||"111111",forceturn:!0},e.turnServer.tcpport+="",e.turnServer.udpport+="",a.b.setProxyServer(d),o.default.setProxyServer(d),f(d,t)})}():f(null,t)},Re={ERR_NO_VOCS_AVAILABLE:"tryNext",ERR_NO_VOS_AVAILABLE:"tryNext",ERR_JOIN_CHANNEL_TIMEOUT:"tryNext",WARN_REPEAT_JOIN:"quit",ERR_JOIN_BY_MULTI_IP:"recover",WARN_LOOKUP_CHANNEL_TIMEOUT:"tryNext",WARN_OPEN_CHANNEL_TIMEOUT:"tryNext",ERR_VOM_SERVICE_UNAVAILABLE:"tryNext",ERR_TOO_MANY_USERS:"tryNext",ERR_MASTER_VOCS_UNAVAILABLE:"tryNext",ERR_INTERNAL_ERROR:"tryNext",notification_test_recover:"recover",notification_test_tryNext:"tryNext",notification_test_retry:"retry"},Oe={googResidualEchoLikelihood:"A_rel",googResidualEchoLikelihoodRecentMax:"A_rem",googTypingNoiseState:"A_tns",totalSamplesDuration:"A_sd",googAdaptationChanges:"A_ac",googBandwidthLimitedResolution:"A_blr",googCpuLimitedResolution:"A_clr",googEncodeUsagePercent:"A_eup",googHasEnteredLowResolution:"A_helr",googActualEncBitrate:"A_aeb",googAvailableReceiveBandwidth:"A_arb",googAvailableSendBandwidth:"A_asb",googRetransmitBitrate:"A_rb",googTargetEncBitrate:"A_teb",googCaptureStartNtpTimeMs:"A_csnt",googPreemptiveExpandRate:"A_per",googPreferredJitterBufferMs:"A_pjbm",googSecondaryDecodedRate:"A_sder",googSecondaryDiscardedRate:"A_sdir",googSpeechExpandRate:"A_ser",googFrameHeightReceived:"A_fhr",googInterframeDelayMax:"A_ifdm",googMinPlayoutDelayMs:"A_mpdm",aecDivergentFilterFraction:"A_dff",codecImplementationName:"A_cin",googEchoCancellationReturnLoss:"A_ecl",googEchoCancellationReturnLossEnhancement:"A_ece"},Ne={};for(var we in Oe){var De=Oe[we];Oe[De]&&console.error("Key Conflict: ".concat(we)),Ne[De]=we}var ke=function(e){return Oe[e]||e},Me=function e(t){var n=!1,s=function(e){return{_type:"control",message:e}},f=function(e){var t={};return Object.keys(e).forEach(function(n){t[ke(n)]=e[n]}),{_type:"subscribe_related_stats",options:t}},m=function(e,t,n){return{_type:"publish",options:e,sdp:t,p2pid:n}},g=e.DISCONNECTED,S=e.CONNECTING,I=e.CONNECTED,h=e.DISCONNECTING,_=g,T=r();Object.defineProperty(T,"state",{set:function(t){var n=_;_=t,n!==t&&T.dispatchEvent({type:"connection-state-change",prevState:e.connetionStateMap[n],curState:e.connetionStateMap[t]})},get:function(){return _}}),T.socket=void 0,T.state=g,T.mode=t.mode,T.role=t.role,T.codec=t.codec,T.config={},T.timers={},T.timer_counter={},T.localStreams={},T.remoteStreams={},T.attemps=1,T.p2p_attemps=1,T.audioLevel={},T.activeSpeaker=void 0,T.reconnectMode="retry",T.rejoinAttempt=0,T.hasChangeBGPAddress=!1,T.traffic_stats={},T.clientId=t.clientId,T.pingpongCounter=0,T.p2ps=new Map,T.liveStreams=new Map,T.injectLiveStreams=new Map,T.remoteStreamsInChannel=new Set,T.inChannelInfo={joinAt:null,duration:0};var A=ge;T.p2pCounter=Object(W.g)(1e5),T.generateP2PId=function(){return++T.p2pCounter},T.audioVolumeIndication={enabled:!1,sortedAudioVolumes:[],smooth:3,interval:2e3},T.remoteVideoStreamTypes={REMOTE_VIDEO_STREAM_HIGH:0,REMOTE_VIDEO_STREAM_LOW:1,REMOTE_VIDEO_STREAM_MEDIUM:2},T.streamFallbackTypes={STREAM_FALLBACK_OPTION_DISABLED:0,STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW:1,STREAM_FALLBACK_OPTION_AUDIO_ONLY:2},T.configPublisher=function(e){T.config=e},T.getGatewayInfo=function(e,t){N({_type:"gateway_info"},e,t)},T.setClientRole=function(e,t){o.default.debug("[".concat(T.clientId,"] setClientRole to ").concat(e));var n=a.b.reportApiInvoke(T.joinInfo.sid,{name:"_setClientRole",callback:t});N(function(e){return{_type:"set_client_role",message:e}}(e),function(){T.role=e,T.dispatchEvent({type:"client-role-changed",role:e}),n&&n(null,{role:e})},function(t){var i=t&&t.code?t.code:0,a=b[i];if("ERR_ALREADY_IN_USE"===a)return n&&n(null);a||(a="UNKNOW_ERROR_".concat(i)),o.default.error("set Client role error to "+e+": "+a),n&&n(a)})},T.join=function(e,n,r,s){e.useProxyServer&&(T.hasChangeBGPAddress=!0);var d=(new Date).getTime(),c=e.uid;if(T.inChannelInfo.joinAt&&(T.inChannelInfo.duration+=d-T.inChannelInfo.joinAt),T.inChannelInfo.joinAt=d,T.state!==S)return o.default.error("[".concat(T.clientId,"] GatewayClient.join Failed: state "),T.state),s&&s(E.INVALID_OPERATION),void a.b.joinGateway(e.sid,{lts:d,succ:!1,ec:E.INVALID_OPERATION,addr:null});if(null!=c&&parseInt(c)!==c)return o.default.error("[".concat(T.clientId,"] Input uid is invalid")),T.state=g,s&&s(E.INVALID_PARAMETER),void a.b.joinGateway(e.sid,{lts:d,succ:!1,ec:E.INVALID_PARAMETER,addr:null});var l=Le.register(T,{uid:c,cname:e&&e.cname});if(l)return T.state=g,s&&s(l),void a.b.joinGateway(e.sid,{lts:d,succ:!1,ec:l,addr:null});T.joinInfo=v()({},e),T.uid=c,T.key=n,T.pingpongCounter=0,O(e,function(n){var c,l,p;T.state=I,o.default.debug("[".concat(T.clientId,"] Connected to gateway server")),T.pingTimer=setInterval(function(){var e=Object(i.getParameter)("PING_PONG_TIME_OUT");if(++T.pingpongCounter>=e){var t=Date.now();o.default.warning("PINGPONG Timeout. Last Socket Message: ".concat(t-T.socket.getLastMsgTime(),"ms")),T.socket&&T.socket.getLastMsgTime()&&t-T.socket.getLastMsgTime()>Object(i.getParameter)("WEBSOCKET_TIMEOUT_MIN")&&(T.pingpongCounter=0,T.socket.close(),T.socket.dispatchEvent(u({type:"disconnect",event:{msg:"PING_PONG_TIME_OUT"}})))}var n=Date.now();N({_type:"ping"},function(){T.pingpongCounter=0;var e=Date.now()-n;N({_type:"signal_stats",message:{pingpongElapse:e}},function(){},function(e){})},function(e){})},3e3),N((c={role:T.role},l=c.role,p={appId:t.appId,key:T.key,channel:T.joinInfo.cname,uid:T.uid,version:i.VERSION,browser:navigator.userAgent,mode:T.mode,codec:T.codec,role:l,config:T.config,processId:Object(a.a)()},T.joinInfo.hasOwnProperty("stringUid")&&(p.stringUid=T.joinInfo.stringUid),{_type:"join1",message:p}),function(t){if(a.b.joinGateway(e.sid,{lts:d,succ:!0,ec:null,vid:t.vid,addr:T.socket.getURL()}),T.rejoinAttempt=0,r&&r(t.uid),T.dispatchEvent({type:"join"}),T.leaveOnConnected){o.default.info("[".concat(T.clientId,"] Calling Leave() once joined"));var n=T.leaveOnConnected;T.leaveOnConnected=null,T.leave(n.onSuccess,n.onFailure)}},function(t){if(o.default.error("[".concat(T.clientId,"] User join failed [").concat(t,"]")),Re[t]&&T.rejoinAttempt<4){if(T._doWithAction(Re[t],r,s),T.leaveOnConnected){o.default.error("[".concat(T.clientId,"] Calling Leave() once joined: Join Failed"));var n=T.leaveOnConnected;T.leaveOnConnected=null,n.onFailure(E.JOIN_CHANNEL_FAILED)}}else s&&s(t);a.b.joinGateway(e.sid,{lts:d,succ:!1,ec:t,addr:T.socket.getURL()})})},function(t){o.default.error("[".concat(T.clientId,"] User join failed [").concat(t,"]")),s&&s(t),a.b.joinGateway(e.sid,{lts:d,succ:!1,ec:t,addr:T.socket.getURL()})}),clearInterval(T.timers.trafficStats),T.timers.trafficStats=setInterval(function(){N({_type:"traffic_stats"},function(e){T.traffic_stats=e;var t=T.joinInfo.stringUid,n=T.localStreams[c]||T.localStreams[t];n&&(n.traffic_stats={access_delay:e.access_delay}),e.peer_delay&&e.peer_delay.forEach(function(t){var n=T.remoteStreams[t.peer_uid];n&&(n.traffic_stats={access_delay:e.access_delay,e2e_delay:t.e2e_delay,audio_delay:t.audio_delay,video_delay:t.video_delay})})})},3e3),T.resetAudioVolumeIndication()},T.leave=function(e,t){switch(T.state){case g:return o.default.debug("[".concat(T.clientId,"] Client Already in DISCONNECTED status")),void A(e);case h:return o.default.error("[".concat(T.clientId,"] Client Already in DISCONNECTING status")),void A(t,E.INVALID_OPERATION);case S:return T.leaveOnConnected?(o.default.error("[".concat(T.clientId,"] Client.leave() already called")),void A(t,E.INVALID_OPERATION)):(o.default.debug("[".concat(T.clientId,"] Client connecting. Waiting for Client Fully Connected(And leave)")),void(T.leaveOnConnected={onSuccess:e,onFailure:t}))}var n=Le.unregister(T);if(n)o.default.error("[".concat(T.clientId,"] "),n);else{for(var i in T.state=h,clearInterval(T.pingTimer),T.timers)T.timers.hasOwnProperty(i)&&clearInterval(T.timers[i]);for(var i in T.inChannelInfo.joinAt&&(T.inChannelInfo.duration+=Date.now()-T.inChannelInfo.joinAt,T.inChannelInfo.joinAt=null),N({_type:"leave"},function(t){T.socket.close(),T.socket=void 0,o.default.info("[".concat(T.clientId,"] Leave channel success")),T.state=g,e&&e(t)},function(e){o.default.error("[".concat(T.clientId,"] Leave Channel Failed"),e),T.state=I,t&&t(e)}),T.localStreams)if(T.localStreams.hasOwnProperty(i)){var a=T.localStreams[i];delete T.localStreams[i],void 0!==a.pc&&(a.pc.close(),a.pc=void 0)}k()}},T.publish=function(e,t,n,i){var r=(new Date).getTime(),d=!1;if(e.publishLTS=r,"object"!==z()(e)||null===e)return o.default.error("[".concat(T.clientId,"] Invalid local stream")),i&&i(E.INVALID_LOCAL_STREAM),void a.b.publish(T.joinInfo.sid,{lts:r,succ:!1,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,ec:E.INVALID_LOCAL_STREAM});if(null===e.stream&&void 0===e.url)return o.default.error("[".concat(T.clientId,"] Invalid local media stream")),i&&i(E.INVALID_LOCAL_STREAM),void a.b.publish(T.joinInfo.sid,{lts:r,succ:!1,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,ec:E.INVALID_LOCAL_STREAM});if(T.state!==I)return o.default.error("[".concat(T.clientId,"] User is not in the session")),i&&i(E.INVALID_OPERATION),void a.b.publish(T.joinInfo.sid,{lts:r,succ:!1,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,ec:E.INVALID_OPERATION});var u=e.getAttributes()||{};if(e.local&&void 0===T.localStreams[e.getId()]&&(e.hasAudio()||e.hasVideo()||e.hasScreen())){var l=T.generateP2PId();if(T.p2ps.set(l,e),e.p2pId=l,void 0!==e.url)w(m({state:"url",audio:e.hasAudio(),video:e.hasVideo(),attributes:e.getAttributes(),mode:T.mode},e.url),function(t,n){"success"===t?(e.getUserId()!==n&&e.setUserId(n),T.localStreams[n]=e,e.onClose=function(){T.unpublish(e)}):o.default.error("[".concat(T.clientId,"] Publish local stream failed"),t)});else{T.localStreams[e.getId()]=e,e.connectionSpec={callback:function(u){o.default.debug("[".concat(T.clientId,"] SDP exchange in publish : send offer -- "),JSON.parse(u)),w(m({state:"offer",id:e.getId(),audio:e.hasAudio(),video:e.hasVideo()||e.hasScreen(),attributes:e.getAttributes(),streamType:t.streamType,dtx:e.DTX,hq:e.highQuality,lq:e.lowQuality,stereo:e.stereo,speech:e.speech,mode:T.mode,codec:T.codec,p2pid:l,turnip:T.joinInfo.turnServer.url,turnport:Number(T.joinInfo.turnServer.udpport),turnusername:T.joinInfo.turnServer.username,turnpassword:T.joinInfo.turnServer.credential},u),function(p,f){if("error"===p)return o.default.error("[".concat(T.clientId,"] Publish local stream failed")),i&&i(E.PUBLISH_STREAM_FAILED),void a.b.publish(T.joinInfo.sid,{lts:r,succ:!1,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,localSDP:u,ec:E.PUBLISH_STREAM_FAILED});e.pc.onsignalingmessage=function(n){e.pc.onsignalingmessage=function(){},w(m({state:"ok",id:e.getId(),audio:e.hasAudio(),video:e.hasVideo(),screen:e.hasScreen(),streamType:t.streamType,attributes:e.getAttributes(),mode:T.mode},n)),e.getUserId()!==f.id&&e.setUserId(f.id),o.default.info("[".concat(T.clientId,"] Local stream published with uid"),f.id),e.onClose=function(){T.unpublish(e)},e._onAudioUnmute=function(){N(s({action:"audio-out-on",streamId:e.getId()}),function(){},function(){})},e._onVideoUnmute=function(){N(s({action:"video-out-on",streamId:e.getId()}),function(){},function(){})},e._onAudioMute=function(){N(s({action:"audio-out-off",streamId:e.getId()}),function(){},function(){})},e._onVideoMute=function(){N(s({action:"video-out-off",streamId:e.getId()}),function(){},function(){})},e.getId()===e.getUserId()&&(e.isAudioOn()||e.hasAudio()&&(o.default.debug("[".concat(T.clientId,"] local stream audio mute")),e._onAudioMute()),e.isVideoOn()||(e.hasVideo()||e.hasScreen())&&(o.default.debug("[".concat(T.clientId,"] local stream video mute")),e._onVideoMute()))},e.pc.oniceconnectionstatechange=function(t){if("failed"===t){if(null!=T.timers[e.getId()]&&(clearInterval(T.timers[e.getId()]),clearInterval(T.timers[e.getId()]+"_RelatedStats")),o.default.error("[".concat(T.clientId,"] Publisher connection is lost -- streamId: ").concat(e.getId(),", p2pId: ").concat(l)),T.p2ps.delete(l),o.default.debug("[".concat(T.clientId,"] publish p2p failed: "),T.p2ps),!d)return d=!0,a.b.publish(T.joinInfo.sid,{lts:r,succ:!1,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,ec:E.PEERCONNECTION_FAILED}),T.dispatchEvent(c({type:"pubP2PLost",stream:e})),i&&i(E.PEERCONNECTION_FAILED);T.dispatchEvent(c({type:"pubP2PLost",stream:e}))}else if("connected"===t&&(o.default.debug("[".concat(T.clientId,"] publish p2p connected: "),T.p2ps),!d))return d=!0,a.b.publish(T.joinInfo.sid,{lts:r,succ:!0,audioName:e.hasAudio()&&e.audioName,videoName:e.hasVideo()&&e.videoName,screenName:e.hasScreen()&&e.screenName,ec:null}),n&&n()},o.default.debug("[".concat(T.clientId,"] SDP exchange in publish : receive answer -- "),JSON.parse(p)),e.pc.processSignalingMessage(p)})},audio:e.hasAudio(),video:e.hasVideo(),screen:e.hasScreen(),isSubscriber:!1,stunServerUrl:T.stunServerUrl,turnServer:T.joinInfo.turnServer,maxAudioBW:u.maxAudioBW,minVideoBW:u.minVideoBW,maxVideoBW:u.maxVideoBW,mode:T.mode,codec:T.codec,isVideoMute:e.userMuteVideo||e.peerMuteVideo,isAudioMute:e.userMuteAudio||e.peerMuteAudio,maxFrameRate:e.attributes.maxFrameRate,clientId:T.clientId},e.pc=B(e.connectionSpec),e.pc.addStream(e.stream),o.default.debug("[".concat(T.clientId,"] PeerConnection add stream :"),e.stream),e.pc.onnegotiationneeded=function(t){w(m({state:"negotiation",p2pid:l},t),function(t,n){e.pc.processSignalingMessage(t)})},T.timers[e.getId()]=setInterval(function(){var t=0;e&&e.pc&&e.pc.getStats&&e.pc.getStatsRate(function(n){n.forEach(function(n){if(n&&n.id&&!/_recv$/.test(n.id)&&!/^time$/.test(n.id)&&e.getUserId())if(-1===n.id.indexOf("outbound_rtp")&&-1===n.id.indexOf("OutboundRTP")||"video"!==n.mediaType||(n.googFrameWidthSent=e.videoWidth+"",n.googFrameHeightSent=e.videoHeight+""),e.getId()==e.getUserId()){var i=200*t;t++,setTimeout(function(){var e,t;N((e=n,t={},Object.keys(e).forEach(function(n){t[ke(n)]=e[n]}),{_type:"publish_stats",options:{stats:t},sdp:null}),null,null)},i)}else{i=200*t;t++,setTimeout(function(){var e,t;N((e=n,t={},Object.keys(e).forEach(function(n){t[ke(n)]=e[n]}),{_type:"publish_stats_low",options:{stats:t},sdp:null}),null,null)},i)}})})},3e3);var p=function(){e&&e.pc&&e.pc.getVideoRelatedStats&&e.pc.getVideoRelatedStats(function(t){var n,i;e.getId()===e.getUserId()?N((n=t,i={},Object.keys(n).forEach(function(e){i[ke(e)]=n[e]}),{_type:"publish_related_stats",options:i}),null,null):N(function(e){var t={};return Object.keys(e).forEach(function(n){t[ke(n)]=e[n]}),{_type:"publish_related_stats_low",options:t}}(t),null,null)})};p(),T.timers[e.getId()+"_RelatedStats"]=setInterval(p,1e3)}}},T.unpublish=function(e,t,n,i){return"object"!==z()(e)||null===e?(o.default.error("[".concat(T.clientId,"] Invalid local stream")),void A(i,E.INVALID_LOCAL_STREAM)):T.state!==I?(o.default.error("[".concat(T.clientId,"] User not in the session")),void A(i,E.INVALID_OPERATION)):(null!=T.timers[e.getId()]&&(clearInterval(T.timers[e.getId()]),clearInterval(T.timers[e.getId()+"_RelatedStats"])),void(void 0!==T.socket?e.local&&void 0!==T.localStreams[e.getId()]?(delete T.localStreams[e.getId()],N((a=e.getUserId(),r=t.streamType,{_type:"unpublish",message:a,streamType:r})),(e.hasAudio()||e.hasVideo()||e.hasScreen())&&void 0===e.url&&void 0!==e.pc&&(e.pc.close(),e.pc=void 0),e.onClose=void 0,e._onAudioMute=void 0,e._onAudioUnute=void 0,e._onVideoMute=void 0,e._onVideoUnmute=void 0,T.p2ps.delete(e.p2pId),n&&n()):(o.default.error("[".concat(T.clientId,"] Invalid local stream")),A(i,E.INVALID_LOCAL_STREAM)):(o.default.error("[".concat(T.clientId,"] User not in the session")),A(i,E.INVALID_OPERATION))));var a,r},T.subscribe=function(e,t,n){var r=(new Date).getTime();e.subscribeLTS=r;var u=!1;if(o.default.info("[".concat(T.clientId,"] Gatewayclient ").concat(T.uid," Subscribe ").concat(e.getId(),": ").concat(JSON.stringify(e.subscribeOptions))),"object"!==z()(e)||null===e)return o.default.error("[".concat(T.clientId,"] Invalid remote stream")),n&&n(E.INVALID_REMOTE_STREAM),void a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.INVALID_REMOTE_STREAM});if(T.state!==I&&(o.default.error("[".concat(T.clientId,"] User is not in the session")),!u))return u=!0,a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.INVALID_OPERATION}),n&&n(E.INVALID_OPERATION);if(!e.local&&T.remoteStreams.hasOwnProperty(e.getId()))if(e.hasAudio()||e.hasVideo()||e.hasScreen()){var l=T.generateP2PId();T.p2ps.set(l,e),e.p2pId=l,e.pc=B({callback:function(t){o.default.debug("[".concat(T.clientId,"] SDP exchange in subscribe : send offer -- "),JSON.parse(t));var s,d=v()({streamId:e.getId(),video:!0,audio:!0,mode:T.mode,codec:T.codec,p2pid:l,turnip:T.joinInfo.turnServer.url,turnport:Number(T.joinInfo.turnServer.udpport),turnusername:T.joinInfo.turnServer.username,turnpassword:T.joinInfo.turnServer.credential,tcc:Object(i.getParameter)("SUBSCRIBE_TCC")},e.subscribeOptions);w({_type:"subscribe",options:d,sdp:t,p2pid:s},function(t){if("error"===t)return o.default.error("[".concat(T.clientId,"] Subscribe remote stream failed, closing stream "),e.getId()),e.close(),n&&n(E.SUBSCRIBE_STREAM_FAILED),void a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.SUBSCRIBE_STREAM_FAILED});o.default.debug("[".concat(T.clientId,"] SDP exchange in subscribe : receive answer -- "),JSON.parse(t)),e.pc.processSignalingMessage(t)})},nop2p:!0,audio:!0,video:!0,screen:e.hasScreen(),isSubscriber:!0,stunServerUrl:T.stunServerUrl,turnServer:T.joinInfo.turnServer,isVideoMute:e.userMuteVideo,isAudioMute:e.userMuteAudio,uid:e.getId(),clientId:T.clientId}),e.pc.onaddstream=function(t,n){if(e._onAudioUnmute=function(){N(s({action:"audio-in-on",streamId:e.getId()}),function(){},function(){})},e._onAudioMute=function(){N(s({action:"audio-in-off",streamId:e.getId()}),function(){},function(){})},e._onVideoUnmute=function(){N(s({action:"video-in-on",streamId:e.getId()}),function(){},function(){})},e._onVideoMute=function(){N(s({action:"video-in-off",streamId:e.getId()}),function(){},function(){})},"ontrack"===n&&"video"===t.track.kind||"onaddstream"===n){o.default.info("[".concat(T.clientId,"] Remote stream subscribed with uid "),e.getId());var i=T.remoteStreams[e.getId()];if(T.remoteStreams[e.getId()].stream="onaddstream"===n?t.stream:t.streams[0],T.remoteStreams[e.getId()].hasVideo()){if(Object(p.isFireFox)()||Object(p.isSafari)()){var a=T.remoteStreams[e.getId()].stream;Object(W.h)(a,function(t,n){e.videoWidth=t,e.videoHeight=n},function(e){return o.default.warning("[".concat(T.clientId,"] vsResHack failed: ")+e)})}}else{var r=T.remoteStreams[e.getId()];r.peerMuteVideo=!0,T._adjustPCMuteStatus(r)}i&&i.isPlaying()&&i.elementID&&(o.default.debug("[".concat(T.clientId,"] Reload Player ").concat(i.elementID," StreamId ").concat(i.getId())),e.audioOutput=i.audioOutput,i.stop(),e.play(i.elementID,i.playOptions)),delete e.audioLevelHelper;var c=d({type:"stream-subscribed",stream:T.remoteStreams[e.getId()]});T.dispatchEvent(c)}},T.timers[e.getId()]=setInterval(function(){var t=0;e&&e.pc&&e.pc.getStats&&e.pc.getStatsRate(function(n){n.forEach(function(n){if(n&&n.id){if(/_send$/.test(n.id)||/^time$/.test(n.id)||/^bweforvideo$/.test(n.id))return;-1===n.id.indexOf("inbound_rtp")&&-1===n.id.indexOf("inbound-rtp")||"video"!==n.mediaType||(n.googFrameWidthReceived=e.videoWidth+"",n.googFrameHeightReceived=e.videoHeight+"");var i=200*t;t++;var o=e.getId();setTimeout(function(){var e,t,i;w((e=o,t=n,i={},Object.keys(t).forEach(function(e){i[ke(e)]=t[e]}),{_type:"subscribe_stats",options:{id:e,stats:i},sdp:null}),null,null)},i)}else;})})},3e3),T.timers[e.getId()+"_RelatedStats"]=setInterval(function(){e&&e.pc&&(e.pc.getVideoRelatedStats&&e.pc.getVideoRelatedStats(function(e){N(f(e),null,null)}),e.pc.getAudioRelatedStats&&e.pc.getAudioRelatedStats(function(e){N(f(e),null,null)}))},1e3),T.audioLevel[e.getId()]=0,T.timers[e.getId()+"audio"]=setInterval(function(){T.hasListeners("active-speaker")&&e&&e.pc&&"established"===e.pc.state&&e.pc.getStats&&e.pc.getStats(function(t){t.forEach(function(t){if("audio"===t.mediaType){if(t.audioOutputLevel>5e3)for(var n in T.audioLevel[e.getId()]<20&&(T.audioLevel[e.getId()]+=1),T.audioLevel)n!==""+e.getId()&&T.audioLevel[n]>0&&(T.audioLevel[n]-=1);var i=Object.keys(T.audioLevel).sort(function(e,t){return T.audioLevel[t]-T.audioLevel[e]});if(T.activeSpeaker!==i[0]){var a=c({type:"active-speaker",uid:i[0]});T.dispatchEvent(a),T.activeSpeaker=i[0],o.default.debug("[".concat(T.clientId,"] Update active speaker: ").concat(T.activeSpeaker))}}})},50)},50),e.pc.oniceconnectionstatechange=function(i){if("failed"===i)null!=T.timers[e.getId()]&&(clearInterval(T.timers[e.getId()]),clearInterval(T.timers[e.getId()]+"audio")),o.default.error("[".concat(T.clientId,"] Subscriber connection is lost -- streamId: ").concat(e.getId(),", p2pId: ").concat(l)),o.default.debug("[".concat(T.clientId,"] subscribe p2p failed: "),T.p2ps),u||(u=!0,n&&n(E.PEERCONNECTION_FAILED),a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.PEERCONNECTION_FAILED})),T.remoteStreams[e.getId()]&&T.p2ps.has(l)&&(T.p2ps.delete(l),T.dispatchEvent(c({type:"subP2PLost",stream:e})));else if("connected"===i&&(o.default.debug("[".concat(T.clientId,"] subscribe p2p connected: "),T.p2ps),!u)){u=!0,a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!0,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:null}),T._adjustPCMuteStatus(e);var s=!1,d=setInterval(function(){e.pc?e.pc.getStats(function(t){t.forEach(function(t){-1!==t.id.indexOf("recv")&&"audio"===t.mediaType&&parseInt(t.googDecodingNormal)>0&&(s||(s=!0,T.dispatchEvent({type:"first-audio-frame-decode",stream:e}),clearInterval(d),a.b.reportApiInvoke(T.joinInfo.sid,{name:"firstAudioDecode"})(null,{elapse:Date.now()-e.subscribeLTS})))})},100):clearInterval(d)},100),p=!1,f=setInterval(function(){e.pc?e.pc.getStats(function(t){t.forEach(function(t){-1===t.id.indexOf("recv")&&-1===t.id.indexOf("inbound_rtp")&&-1===t.id.indexOf("inbound-rtp")&&-1===t.id.indexOf("InboundRTP")||"video"===t.mediaType&&(t.framesDecoded>0||t.googFramesDecoded>0)&&(p||(p=!0,T.dispatchEvent({type:"first-video-frame-decode",stream:e}),clearInterval(f),e.firstFrameTime=(new Date).getTime()-e.subscribeLTS,a.b.firstRemoteFrame(T.joinInfo.sid,{lts:(new Date).getTime(),peerid:e.getId(),succ:!0,width:+t.googFrameWidthReceived,height:+t.googFrameHeightReceived})))})},100):clearInterval(f)},100);return e.sid=T.joinInfo.sid,t&&t()}}}else o.default.error("[".concat(T.clientId,"] Invalid remote stream")),u||(u=!0,n&&n(E.INVALID_REMOTE_STREAM),a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.INVALID_REMOTE_STREAM}));else o.default.error("[".concat(T.clientId,"] No such remote stream")),u||(u=!0,n&&n(E.NO_SUCH_REMOTE_STREAM),a.b.subscribe(T.joinInfo.sid,{lts:r,succ:!1,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:E.NO_SUCH_REMOTE_STREAM}))},T.subscribeChange=function(e,t,n){var i,r,s=Date.now();o.default.info("[".concat(T.clientId,"] Gatewayclient ").concat(T.uid," SubscribeChange ").concat(e.getId(),": ").concat(JSON.stringify(e.subscribeOptions))),T._adjustPCMuteStatus(e),N((i=e.getId(),r=e.subscribeOptions,{_type:"subscribe_change",options:v()({streamId:i},r)}),function(i){if("error"===i)return o.default.error("[".concat(T.clientId,"] Subscribe Change Failed ").concat(e.getId())),void A(n,"SUBSCRIBE_CHANGE_FAILED");var r=d({type:"stream-subscribe-changed",stream:T.remoteStreams[e.getId()]});a.b.subscribe(T.joinInfo.sid,{lts:s,succ:!0,video:e.subscribeOptions&&e.subscribeOptions.video,audio:e.subscribeOptions&&e.subscribeOptions.audio,peerid:e.getId(),ec:null}),T.dispatchEvent(r),t&&t()},n)},T._adjustPCMuteStatus=function(e){!e.local&&e.pc&&e.pc.peerConnection.getReceivers&&e.pc.peerConnection.getReceivers().forEach(function(t){if(t&&t.track&&"audio"===t.track.kind){var n=!e.userMuteAudio&&!e.peerMuteAudio;e.subscribeOptions&&!e.subscribeOptions.audio&&(n=!1),t.track.enabled=!!n}else if(t&&t.track&&"video"===t.track.kind){var i=!e.userMuteVideo&&!e.peerMuteVideo;e.subscribeOptions&&!e.subscribeOptions.video&&(i=!1),t.track.enabled=!!i}})},T.unsubscribe=function(e,t,n){if("object"!==z()(e)||null===e)return o.default.error("[".concat(T.clientId,"] Invalid remote stream")),void A(n,E.INVALID_REMOTE_STREAM);if(T.state!==I)return o.default.error("[".concat(T.clientId,"] User is not in the session")),void A(n,E.INVALID_OPERATION);if(null!=T.timers[e.getId()]&&(clearInterval(T.timers[e.getId()]),clearInterval(T.timers[e.getId()]+"audio")),null!=T.audioLevel[e.getId()]&&delete T.audioLevel[e.getId()],null!=T.timer_counter[e.getId()]&&delete T.timer_counter[e.getId()],T.remoteStreams.hasOwnProperty(e.getId())){if(!T.socket)return o.default.error("[".concat(T.clientId,"] User is not in the session")),void A(n,E.INVALID_OPERATION);if(e.local)return o.default.error("[".concat(T.clientId,"] Invalid remote stream")),void A(n,E.INVALID_REMOTE_STREAM);e.close(),N({_type:"unsubscribe",message:e.getId()},function(i){if("error"===i)return o.default.error("[".concat(T.clientId,"] Unsubscribe remote stream failed ").concat(e.getId())),void A(n,E.UNSUBSCRIBE_STREAM_FAILED);void 0!==e.pc&&(e.pc.close(),e.pc=void 0),e.onClose=void 0,e._onAudioMute=void 0,e._onAudioUnute=void 0,e._onVideoMute=void 0,e._onVideoUnmute=void 0,delete e.subscribeOptions,T.p2ps.delete(e.p2pId),o.default.info("[".concat(T.clientId,"] Unsubscribe stream success")),t&&t()},n)}else A(n,E.NO_SUCH_REMOTE_STREAM)},T.setRemoteVideoStreamType=function(e,t){if(o.default.debug("[".concat(T.clientId,"] Switching remote video stream ").concat(e.getId()," to ").concat(t)),"object"===z()(e)&&null!==e)if(T.state===I){if(!e.local){switch(t){case T.remoteVideoStreamTypes.REMOTE_VIDEO_STREAM_HIGH:case T.remoteVideoStreamTypes.REMOTE_VIDEO_STREAM_LOW:case T.remoteVideoStreamTypes.REMOTE_VIDEO_STREAM_MEDIUM:break;default:return}N(function(e,t){return{_type:"switchVideoStream",message:{id:e,type:t}}}(e.getId(),t),null,null)}}else o.default.error("[".concat(T.clientId,"] User is not in the session"));else o.default.error("[".concat(T.clientId,"] Invalid remote stream"))},T.renewToken=function(e,t,n){e?T.key?T.state!==I?(o.default.debug("[".concat(T.clientId,"] Client is not connected. Trying to rejoin")),T.key=e,T.rejoin(),t&&t()):(o.default.debug("[".concat(T.clientId,"] renewToken from ").concat(T.key," to ").concat(e)),N(function(e){return{_type:"renew_token",message:{token:e}}}(e),t,n)):(o.default.error("[".concat(T.clientId,"] Client is previously joined without token")),n&&n(E.INVALID_PARAMETER)):(o.default.error("[".concat(T.clientId,"] Invalid Token ").concat(e)),n&&n(E.INVALID_PARAMETER))},T.setStreamFallbackOption=function(e,t){if(o.default.debug("[".concat(T.clientId,"] Set stream fallback option ").concat(e.getId()," to ").concat(t)),"object"===z()(e)&&null!==e)if(T.state===I){if(!e.local){switch(t){case T.streamFallbackTypes.STREAM_FALLBACK_OPTION_DISABLED:case T.streamFallbackTypes.STREAM_FALLBACK_OPTION_VIDEO_STREAM_LOW:case T.streamFallbackTypes.STREAM_FALLBACK_OPTION_AUDIO_ONLY:break;default:return}N(function(e,t){return{_type:"setFallbackOption",message:{id:e,type:t}}}(e.getId(),t),null,null)}}else o.default.error("[".concat(T.clientId,"] User is not in the session"));else o.default.error("[".concat(T.clientId,"] Invalid remote stream"))},T.startLiveStreaming=function(e,t){T.liveStreams.set(e,t),o.default.debug("[".concat(T.clientId,"] Start live streaming ").concat(e," ").concat(t," ").concat(t)),T.state===I?N(function(e,t){return{_type:"start_live_streaming",message:{url:e,transcodingEnabled:t}}}(e,t),null,null):o.default.error("[".concat(T.clientId,"] User is not in the session"))},T.stopLiveStreaming=function(e){o.default.debug("[".concat(T.clientId,"] Stop live streaming ").concat(e)),T.state===I?(T.liveStreams.delete(e),N(function(e){return{_type:"stop_live_streaming",message:{url:e}}}(e),null,null)):o.default.error("[".concat(T.clientId,"] User is not in the session"))},T.setLiveTranscoding=function(e){Object(W.d)(e)&&(T.transcoding=e,o.default.debug("[".concat(T.clientId,"] Set live transcoding "),e),T.state===I?N(function(e){return{_type:"set_live_transcoding",message:{transcoding:e}}}(e),null,null):o.default.error("[".concat(T.clientId,"] User is not in the session")))},T.addInjectStreamUrl=function(e,t){T.injectLiveStreams.set(e,t),o.default.debug("[".concat(T.clientId,"] Add inject stream url ").concat(e," config "),t),T.state===I?N(function(e,t){return{_type:"add_inject_stream_url",message:{url:e,config:t}}}(e,t),null,null):o.default.error("[".concat(T.clientId,"] User is not in the session"))},T.removeInjectStreamUrl=function(e){o.default.debug("[".concat(T.clientId,"] Remove inject stream url ").concat(e)),T.state===I?(T.injectLiveStreams.delete(e),N(function(e){return{_type:"remove_inject_stream_url",message:{url:e}}}(e),null,null)):o.default.error("[".concat(T.clientId,"] User is not in the session"))},T.enableAudioVolumeIndicator=function(e,t){T.audioVolumeIndication.enabled=!0,T.audioVolumeIndication.interval=e,T.audioVolumeIndication.smooth=t,T.resetAudioVolumeIndication()},T.resetAudioVolumeIndication=function(){if(clearInterval(T.timers.audioVolumeIndication),clearInterval(T.timers.audioVolumeSampling),T.audioVolumeIndication.enabled&&T.audioVolumeIndication.interval){var e=Math.floor(1e3*T.audioVolumeIndication.smooth/100);T.timers.audioVolumeSampling=setInterval(function(){T.audioVolumeSampling||(T.audioVolumeSampling={});var t={};for(var n in T.remoteStreams){var i=T.remoteStreams[n];if(i.stream&&i.hasAudio()){var o=i.getAudioLevel();o>0&&o<1&&(o*=100);var a=T.audioVolumeSampling[n]||[];for(a.push(o);a.length>e;)a.shift();t[n]=a}}T.audioVolumeSampling=t},100),T.timers.audioVolumeIndication=setInterval(function(){var e=[];for(var t in T.remoteStreams)if(T.audioVolumeSampling&&T.audioVolumeSampling[t]){var n=T.audioVolumeSampling[t],i=0;n.forEach(function(e){i+=e});var a={uid:t,level:Math.floor(i/n.length)};a.level&&e.push(a)}var r=e.sort(function(e,t){return e.level-t.level});o.default.debug("[".concat(T.clientId,"] volume-indicator "),JSON.stringify(r)),T.audioVolumeIndication.sortedAudioVolumes=r;var s=c({type:"volume-indicator",attr:r});T.dispatchEvent(s)},T.audioVolumeIndication.interval)}},T.closeGateway=function(){o.default.debug("[".concat(T.clientId,"] close gateway")),T.state=g,T.socket.close(),C()};var C=function(){for(var e in T.timers)T.timers.hasOwnProperty(e)&&clearInterval(T.timers[e]);for(var e in T.remoteStreams)if(T.remoteStreams.hasOwnProperty(e)){var t=T.remoteStreams[e],n=c({type:"stream-removed",uid:t.getId(),stream:t});T.dispatchEvent(n)}T.p2ps.clear(),k(),D(),clearInterval(T.pingTimer)};T.rejoin=function(){T.socket&&(clearInterval(T.pingTimer),T.socket.close(),T.socket=void 0),T.state=S,R()};var R=function(e,t){T.dispatchEvent(c({type:"rejoin-start"})),e=e||function(e){o.default.info("[".concat(T.clientId,"] User ").concat(e," is re-joined to ").concat(T.joinInfo.cname)),T.dispatchEvent(c({type:"rejoin"})),T.liveStreams&&T.liveStreams.size&&T.liveStreams.forEach(function(e,t){e&&T.setLiveTranscoding(T.transcoding),T.startLiveStreaming(t,e)}),T.injectLiveStreams&&T.injectLiveStreams.size&&T.injectLiveStreams.forEach(function(e,t){T.addInjectStreamUrl(t,e)})},t=t||function(e){o.default.error("[".concat(T.clientId,"] Re-join to channel failed "),e),T.dispatchEvent(d({type:"error",reason:e}))},T.key?(++T.rejoinAttempt,T.join(T.joinInfo,T.key,e,t)):o.default.error("[".concat(T.clientId,"] Connection recover failed [Invalid channel key]"))},O=function(e,t,i){var r;T.onConnect=t,T.socket?(T.dispatchEvent({type:"reconnect"}),"retry"===T.reconnectMode?(o.default.debug("[".concat(T.clientId,"] Retry current gateway")),T.socket.reconnect()):"tryNext"===T.reconnectMode?(o.default.debug("[".concat(T.clientId,"] Try next gateway")),T.socket.connectNext()):"recover"===T.reconnectMode&&(o.default.debug("[".concat(T.clientId,"] Recover gateway")),o.default.debug("[".concat(T.clientId,"] Try to reconnect choose server and get gateway list again ")),Ce(T.joinInfo,function(e){T.socket.replaceHost(e.gateway_addr)}))):(r=e.gatewayAddr,T.socket=Ie(r,{sid:T.joinInfo.sid,clientId:T.clientId}),T.socket.on("onUplinkStats",function(e){T.OutgoingAvailableBandwidth=e.uplink_available_bandwidth,T.localStreams[T.uid]&&(T.localStreams[T.uid].uplinkStats=e)}),T.socket.on("connect",function(){T.dispatchEvent({type:"connected"}),T.attemps=1,N(function(e){var t=e;return e.uni_lbs_ip&&(t=v()(e,{wanip:e.uni_lbs_ip,hasChange:T.hasChangeBGPAddress})),{_type:"token",message:t}}(e),T.onConnect,i)}),T.socket.on("recover",function(){T.state=S,o.default.debug("[".concat(T.clientId,"] Try to reconnect choose server and get gateway list again ")),Ce(T.joinInfo,function(e){T.socket.replaceHost(e.gateway_addr)})}),T.socket.on("disconnect",function(e){if(T.state!==g){T.state=g;var t=d({type:"error",reason:E.SOCKET_DISCONNECTED});if(T.dispatchEvent(t),0===T.p2ps.size?T.reconnectMode="tryNext":T.reconnectMode="retry",C(),1!=n){var i,a=(i=T.attemps,1e3*Math.min(30,Math.pow(2,i)-1));o.default.error("[".concat(T.clientId,"] Disconnect from server [").concat(JSON.stringify(e),"], attempt to recover [#").concat(T.attemps,"] after ").concat(a/1e3," seconds"));setTimeout(function(){T.attemps++,T.state=S,R()},a)}}}),T.socket.on("onAddAudioStream",function(e){if(o.default.info("[".concat(T.clientId,"] Newly added audio stream with uid ").concat(e.id)),T.joinInfo.stringUid&&"string"!=typeof e.id&&o.default.error("StringUID is Mixed with UintUID"),T.remoteStreamsInChannel.has(e.id)||T.remoteStreamsInChannel.add(e.id),void 0===T.remoteStreams[e.id]){var t=ue({streamID:e.id,local:!1,audio:e.audio,video:e.video,screen:e.screen,attributes:e.attributes});t.peerMuteVideo=!0,T.remoteStreams[e.id]=t;var n=d({type:"stream-added",stream:t});T.dispatchEvent(n)}}),T.socket.on("onUpdateStream",function(e){var t=T.remoteStreams[e.id];if(T.joinInfo.stringUid&&"string"!=typeof e.id&&o.default.error("StringUID is Mixed with UintUID"),t){delete e.id,t.audio=e.audio,t.video=e.video,t.screen=e.screen,t.pc&&T._adjustPCMuteStatus(t);var n=d({type:"stream-updated",stream:t});T.dispatchEvent(n)}else o.default.debug("[".concat(T.clientId,"] Ignoring onUpdateStream event before onAddStream for uid ").concat(e.id))}),T.socket.on("onAddVideoStream",function(e){if(o.default.info("[".concat(T.clientId,"] Newly added remote stream with uid ").concat(e.id,".")),T.joinInfo.stringUid&&"string"!=typeof e.id&&o.default.error("StringUID is Mixed with UintUID"),T.remoteStreamsInChannel.has(e.id)||T.remoteStreamsInChannel.add(e.id),void 0===T.remoteStreams[e.id]){var t=ue({streamID:e.id,local:!1,audio:e.audio,video:e.video,screen:e.screen,attributes:e.attributes});T.remoteStreams[e.id]=t;var n=d({type:"stream-added",stream:t});T.dispatchEvent(n)}else{var i=T.remoteStreams[e.id];if(i.peerMuteVideo=!1,i.video=!0,void 0!==i.stream){if((t=T.remoteStreams[e.id]).pc&&T._adjustPCMuteStatus(t),o.default.info("[".concat(T.clientId,"] Stream changed: enable video ").concat(e.id)),t.isPlaying()){var a=t.player.elementID;t.stop(),t.play(a,t.playOptions)}}else if(i.p2pId)T.remoteStreams[e.id].video=!0;else{t=ue({streamID:e.id,local:!1,audio:!0,video:!0,screen:!1,attributes:e.attributes});T.remoteStreams[e.id]=t,o.default.info("[".concat(T.clientId,"] Stream changed: modify video ").concat(e.id))}}}),T.socket.on("onRemoveStream",function(e){T.remoteStreamsInChannel.has(e.id)&&T.remoteStreamsInChannel.delete(e.id);var t=T.remoteStreams[e.id];if(t){delete T.remoteStreams[e.id];var n=d({type:"stream-removed",stream:t});T.dispatchEvent(n),t.close(),void 0!==t.pc&&(t.pc.close(),t.pc=void 0,T.p2ps.delete(t.p2pId))}else console.log("ERROR stream ",e.id," not found onRemoveStream ",e)}),T.socket.on("onPublishStream",function(e){var t=T.localStreams[e.id],n=d({type:"streamPublished",stream:t});T.dispatchEvent(n)}),T.socket.on("mute_audio",function(e){o.default.info("[".concat(T.clientId,"] rcv peer mute audio: ").concat(e.peerid));var t=c({type:"mute-audio",uid:e.peerid}),n=T.remoteStreams[e.peerid];n?(n.peerMuteAudio=!0,n.pc&&T._adjustPCMuteStatus(n)):o.default.debug("Ignoring event ".concat(e.type),e),T.dispatchEvent(t)}),T.socket.on("unmute_audio",function(e){o.default.info("[".concat(T.clientId,"] rcv peer unmute audio: ").concat(e.peerid));var t=c({type:"unmute-audio",uid:e.peerid}),n=T.remoteStreams[e.peerid];n?(n.peerMuteAudio=!1,n.pc&&T._adjustPCMuteStatus(n)):o.default.debug("Ignoring event ".concat(e.type),e),T.dispatchEvent(t)}),T.socket.on("mute_video",function(e){o.default.info("[".concat(T.clientId,"] rcv peer mute video: ").concat(e.peerid));var t=c({type:"mute-video",uid:e.peerid}),n=T.remoteStreams[e.peerid];n?(n.peerMuteVideo=!0,n.pc&&T._adjustPCMuteStatus(n)):o.default.debug("Ignoring event ".concat(e.type),e),T.dispatchEvent(t)}),T.socket.on("unmute_video",function(e){o.default.info("[".concat(T.clientId,"] rcv peer unmute video: ").concat(e.peerid));var t=c({type:"unmute-video",uid:e.peerid}),n=T.remoteStreams[e.peerid];n?(n.peerMuteVideo=!1,n.pc&&T._adjustPCMuteStatus(n)):o.default.debug("Ignoring event ".concat(e.type),e),T.dispatchEvent(t)}),T.socket.on("user_banned",function(e){o.default.info("[".concat(T.clientId,"] user banned uid: ").concat(e.id," error: ").concat(e.errcode));var t=c({type:"client-banned",uid:e.id,attr:e.errcode});T.dispatchEvent(t),n=!0}),T.socket.on("stream_fallback",function(e){o.default.info("[".concat(T.clientId,"] stream fallback uid: ").concat(e.id," peerId: ").concat(e.peerid," type: ").concat(e.type));var t=c({type:"stream-fallback",uid:e.id,stream:e.peerid,attr:e.type});T.dispatchEvent(t)}),T.socket.on("stream_recover",function(e){o.default.info("[".concat(T.clientId,"] stream recover uid: ").concat(e.id," peerId: ").concat(e.peerid," type: ").concat(e.type));var t=c({type:"stream-recover",uid:e.id,stream:e.peerid,attr:e.type});T.dispatchEvent(t)}),T.socket.on("onP2PLost",function(e){o.default.debug("[".concat(T.clientId,"] p2plost: "),e,"p2ps:",T.p2ps);var t,n="DTLS failed";(t=T.localStreams[e.uid]||T.remoteStreams[e.uid])?(t.pc&&t.pc.offerCandidates&&0===t.pc.offerCandidates.length&&(n="NO_CANDIDATES_IN_OFFER"),"publish"===e.event&&a.b.publish(T.joinInfo.sid,{lts:t.publishLTS,succ:!1,audioName:t.hasAudio()&&t.audioName,videoName:t.hasVideo()&&t.videoName,screenName:t.hasScreen()&&t.screenName,ec:n}),"subscribe"===e.event&&a.b.subscribe(T.joinInfo.sid,{lts:t.subscribeLTS,succ:!1,video:t.subscribeOptions&&t.subscribeOptions.video,audio:t.subscribeOptions&&t.subscribeOptions.audio,peerid:e.uid+"",ec:n})):o.default.warning("P2PLost Stream Not found",e),o.default.debug("[".concat(T.clientId,"] p2plost:"),e.p2pid),(t=T.p2ps.get(e.p2pid))&&(T.p2ps.delete(e.p2pid),t.local?T.dispatchEvent(c({type:"pubP2PLost",stream:t,attr:n})):T.remoteStreams[t.getId()]&&T.dispatchEvent(c({type:"subP2PLost",stream:t,attr:n})))}),T.socket.on("onTokenPrivilegeWillExpire",function(e){o.default.debug("[".concat(T.clientId,"] Received Message onTokenPrivilegeWillExpire")),T.dispatchEvent(c({type:"onTokenPrivilegeWillExpire"}))}),T.socket.on("onTokenPrivilegeDidExpire",function(){o.default.warning("[".concat(T.clientId,"] Received Message onTokenPrivilegeDidExpire, please get new token and join again")),T.closeGateway(),T.dispatchEvent(c({type:"onTokenPrivilegeDidExpire"}))}),T._doWithAction=function(e,t,n){"tryNext"===e?function(e,t){o.default.debug("[".concat(T.clientId,"] Connect next gateway")),T.state=g,T.socket.close(),C(),T.reconnectMode="tryNext",R(e,t)}(t,n):"retry"===e?function(e,t){o.default.debug("[".concat(T.clientId,"] Reconnect gateway")),T.state=g,T.socket.close(),C(),T.reconnectMode="retry",R(e,t)}(t,n):"quit"===e?(o.default.debug("[".concat(T.clientId,"] quit gateway")),T.state=g,T.socket.close(),C()):"recover"===e&&(o.default.debug("[".concat(T.clientId,"] Reconnect gateway")),T.state=g,T.socket.close(),C(),T.reconnectMode="recover",R())},T.socket.on("notification",function(e){if(o.default.debug("[".concat(T.clientId,"] Receive notification: "),e),"ERR_JOIN_BY_MULTI_IP"===y[e.code])return T.dispatchEvent({type:"onMultiIP",arg:e});e.detail?T._doWithAction(Re[y[e.code]]):e.action&&T._doWithAction(e.action)}),T.socket.on("onPeerLeave",function(e){var t=c({type:"peer-leave",uid:e.id});if(T.remoteStreamsInChannel.has(e.id)&&T.remoteStreamsInChannel.delete(e.id),T.remoteStreams.hasOwnProperty(e.id)&&(t.stream=T.remoteStreams[e.id]),T.dispatchEvent(t),T.remoteStreams.hasOwnProperty(e.id)){o.default.info("[".concat(T.clientId,"] closing stream on peer leave"),e.id);var n=T.remoteStreams[e.id];n.close(),delete T.remoteStreams[e.id],void 0!==n.pc&&(n.pc.close(),n.pc=void 0,T.p2ps.delete(n.p2pId))}T.timers.hasOwnProperty(e.id)&&(clearInterval(T.timers[e.id]),clearInterval(T.timers[e.id]+"_RelatedStats"),delete T.timers[e.id]),null!=T.audioLevel[e.id]&&delete T.audioLevel[e.id],null!=T.timer_counter[e.id]&&delete T.timer_counter[e.id]}),T.socket.on("onUplinkStats",function(e){}),T.socket.on("liveStreamingStarted",function(e){var t=l({type:"liveStreamingStarted",url:e.url});T.dispatchEvent(t)}),T.socket.on("liveStreamingFailed",function(e){var t=l({type:"liveStreamingFailed",url:e.url});T.dispatchEvent(t)}),T.socket.on("liveStreamingStopped",function(e){var t=l({type:"liveStreamingStopped",url:e.url});T.dispatchEvent(t)}),T.socket.on("liveTranscodingUpdated",function(e){var t=l({type:"liveTranscodingUpdated",reason:e.reason});T.dispatchEvent(t)}),T.socket.on("streamInjectedStatus",function(e){var t=l({type:"streamInjectedStatus",url:e.url,uid:e.uid,status:e.status});T.dispatchEvent(t)}),T.socket.on("onUserOnline",function(e){T.joinInfo.stringUid&&"string"!=typeof e.id&&o.default.error("StringUID is Mixed with UintUID"),T.dispatchEvent({type:"peer-online",uid:e.id})}))},N=function(e,t,n){if(void 0===T.socket)return o.default.error("[".concat(T.clientId,"] No socket available")),void A(n,E.INVALID_OPERATION);try{T.socket.emitSimpleMessage(e,function(e,i){"success"===e?"function"==typeof t&&t(i):"function"==typeof n&&n(y[i]||i)})}catch(t){o.default.error("[".concat(T.clientId,"] Socket emit message failed ").concat(JSON.stringify(e))),o.default.error("[".concat(T.clientId,"] "),t),A(n,E.SOCKET_ERROR)}},w=function(e,t){if(void 0!==T.socket)try{T.socket.emitSimpleMessage(e,function(e,n){t&&t(e,n)})}catch(e){o.default.error("[".concat(T.clientId,"] Error in sendSimpleSdp [").concat(e,"]"))}else o.default.error("[".concat(T.clientId,"] Error in sendSimpleSdp [socket not ready]"))},D=function(){for(var e in T.localStreams)if(void 0!==T.localStreams[e]){var t=T.localStreams[e];delete T.localStreams[e],void 0!==t.pc&&(t.pc.close(),t.pc=void 0)}},k=function(){for(var e in T.remoteStreamsInChannel.clear(),T.remoteStreams)if(T.remoteStreams.hasOwnProperty(e)){var t=T.remoteStreams[e];t.isPlaying()&&t.stop(),t.close(),delete T.remoteStreams[e],void 0!==t.pc&&(t.pc.close(),t.pc=void 0)}};return T},Le={_gatewayClients:{},register:function(e,t){if(!t.uid){var n="NO_UID_PROVIDED";return o.default.error("[".concat(e.clientId,"] "),n,t),n}if(t.cname){if(this._gatewayClients[t.cname]&&this._gatewayClients[t.cname][t.uid]&&this._gatewayClients[t.cname][t.uid]!==e){n="UID_CONFLICT";return o.default.error("[".concat(e.clientId,"] "),n,t),n}return o.default.debug("[".concat(e.clientId,"] register client Channel"),t.cname,"Uid",t.uid),this._gatewayClients[t.cname]||(this._gatewayClients[t.cname]={}),this._gatewayClients[t.cname][t.uid]=e,null}var n="NO_CHANNEL_PROVIDED";return o.default.error("[".concat(e.clientId,"] "),n,t),n},unregister:function(e){var t=e&&e.uid,n=e.joinInfo&&e.joinInfo.cname;if(!t||!n){var i="INVALID_GATEWAYCLIENT";return o.default.error("[".concat(e.clientId,"] "),i),i}if(this._gatewayClients[n]&&this._gatewayClients[n][t]){if(this._gatewayClients[n][t]!==e){i="GATEWAYCLIENT_UID_CONFLICT";return o.default.error("[".concat(e.clientId,"] "),i),i}return o.default.debug("[".concat(e.clientId,"] unregister client "),e.uid),delete this._gatewayClients[n][t],null}var i="GATEWEAY_CLIENT_UNREGISTERED";o.default.error("[".concat(e.clientId,"] "),i)}};Me.DISCONNECTED=0,Me.CONNECTING=1,Me.CONNECTED=2,Me.DISCONNECTING=3,Me.connetionStateMap={0:"DISCONNECTED",1:"CONNECTING",2:"CONNECTED",3:"DISCONNECTING"};var Pe=Me,xe=function(e){var t;switch(e){case"120p":case"120p_1":t=["120p_1","120p_1","120p_1"];break;case"120p_3":t=["120p_3","120p_3","120p_3"];break;case"180p":case"180p_1":t=["90p_1","90p_1","180p_1"];break;case"180p_3":t=["120p_3","120p_3","180p_3"];break;case"180p_4":t=["120p_1","120p_1","180p_4"];break;case"240p":case"240p_1":t=["120p_1","120p_1","240p_1"];break;case"240p_3":t=["120p_3","120p_3","240p_3"];break;case"240p_4":t=["120p_4","120p_4","240p_4"];break;case"360p":case"360p_1":case"360p_4":case"360p_9":case"360p_10":case"360p_11":t=["90p_1","90p_1","360p_1"];break;case"360p_3":case"360p_6":t=["120p_3","120p_3","360p_3"];break;case"360p_7":case"360p_8":t=["120p_1","120p_1","360p_7"];break;case"480p":case"480p_1":case"480p_2":case"480p_4":case"480p_10":t=["120p_1","120p_1","480p_1"];break;case"480p_3":case"480p_6":t=["120p_3","120p_3","480p_3"];break;case"480p_8":case"480p_9":t=["120p_4","120p_4","480p_8"];break;case"720p":case"720p_1":case"720p_2":case"720p_3":t=["90p_1","90p_1","720p_1"];break;case"720p_5":case"720p_6":t=["120p_1","120p_1","720p_5"];break;case"1080p":case"1080p_1":case"1080p_2":case"1080p_3":case"1080p_5":t=["90p_1","90p_1","1080p_1"];break;case"1440p":case"1440p_1":case"1440p_2":t=["90p_1","90p_1","1440p_1"];break;case"4k":case"4k_1":case"4k_3":t=["90p_1","90p_1","4k_1"];break;default:t=["120p_1","120p_1","360p_7"]}return Object(p.isOpera)()?[e,15,50]:Object(p.isFireFox)()?[t[1],15,100]:Object(p.isSafari)()?[t[2],15,50]:[t[0],15,50]},Ve={1001:"FRAMERATE_INPUT_TOO_LOW",1002:"FRAMERATE_SENT_TOO_LOW",1003:"SEND_VIDEO_BITRATE_TOO_LOW",1005:"RECV_VIDEO_DECODE_FAILED",2001:"AUDIO_INPUT_LEVEL_TOO_LOW",2002:"AUDIO_OUTPUT_LEVEL_TOO_LOW",2003:"SEND_AUDIO_BITRATE_TOO_LOW",2005:"RECV_AUDIO_DECODE_FAILED",3001:"FRAMERATE_INPUT_TOO_LOW_RECOVER",3002:"FRAMERATE_SENT_TOO_LOW_RECOVER",3003:"SEND_VIDEO_BITRATE_TOO_LOW_RECOVER",3005:"RECV_VIDEO_DECODE_FAILED_RECOVER",4001:"AUDIO_INPUT_LEVEL_TOO_LOW_RECOVER",4002:"AUDIO_OUTPUT_LEVEL_TOO_LOW_RECOVER",4003:"SEND_AUDIO_BITRATE_TOO_LOW_RECOVER",4005:"RECV_AUDIO_DECODE_FAILED_RECOVER"},Ue={FramerateInput:1001,FramerateSent:1002,SendVideoBitrate:1003,VideoDecode:1005,AudioIntputLevel:2001,AudioOutputLevel:2002,SendAudioBitrate:2003,AudioDecode:2005},Fe=function(e){var t={remoteStreamStorage:{},localStreamStorage:{}};return t.gatewayClient=e,t.checkAudioOutputLevel=function(e){return!(e&&parseInt(e.audioRecvBytesDelta)>0&&parseInt(e.audioDecodingNormalDelta)>0&&0===parseInt(e.audioOutputLevel))},t.checkAudioIntputLevel=function(e){return!e||0!==parseInt(e.audioInputLevel)},t.checkFramerateInput=function(e,t){if(!e||!t.attributes)return!0;var n=parseInt(t.attributes.maxFrameRate),i=parseInt(e.googFrameRateInput);return!n||!i||!(n>10&&i<5||n<10&&n>=5&&i<=1)},t.checkFramerateSent=function(e){return!(e&&parseInt(e.googFrameRateInput)>5&&parseInt(e.googFrameRateSent)<=1)},t.checkSendVideoBitrate=function(e){return!e||0!==parseInt(e.videoSendBytesDelta)},t.checkSendAudioBitrate=function(e){return!e||0!==parseInt(e.audioSendBytesDelta)},t.checkVideoDecode=function(e){return!e||0===parseInt(e.videoRecvBytesDelta)||0!==parseInt(e.googFrameRateDecoded)},t.checkAudioDecode=function(e){return!e||0===parseInt(e.audioRecvBytesDelta)||0!==parseInt(e.audioDecodingNormalDelta)},t.record=function(e,n,i,o,a){i[e]||(i[e]={isPrevNormal:!0,record:[]});var r=i[e],s=t["check"+e](n,a);if(r.record.push(s),r.record.length>=5){r.isCurNormal=-1!==r.record.indexOf(!0);var d=Ue[e];r.isPrevNormal&&!r.isCurNormal&&t.gatewayClient.dispatchEvent({type:"exception",code:d,msg:Ve[d],uid:o}),!r.isPrevNormal&&r.isCurNormal&&t.gatewayClient.dispatchEvent({type:"exception",code:d+2e3,msg:Ve[d+2e3],uid:o}),r.isPrevNormal=r.isCurNormal,r.record=[]}},t.setLocalStats=function(e){var n={};Object.keys(e).map(function(i){var o=e[i],a=t.gatewayClient.localStreams[parseInt(i)],r=t.localStreamStorage[i]||{};a&&a.hasVideo()&&(t.record("SendVideoBitrate",o.videoStats,r,i),t.record("FramerateInput",o.videoStats,r,i,a),t.record("FramerateSent",o.videoStats,r,i)),a&&a.hasAudio()&&(t.record("AudioIntputLevel",o.audioStats,r,i),t.record("SendAudioBitrate",o.audioStats,r,i)),n[i]=r}),t.localStreamStorage=n},t.setRemoteStats=function(n){var i={};Object.keys(n).map(function(o){var a=n[o],r=e.remoteStreams[o],s=t.remoteStreamStorage[o]||{};r&&r.hasVideo()&&r.isPlaying()&&t.record("VideoDecode",a.videoStats,s,o),r&&r.hasAudio()&&r.isPlaying()&&(t.record("AudioOutputLevel",a.audioStats,s,o),t.record("AudioDecode",a.audioStats,s,o)),i[o]=s}),t.remoteStreamStorage=i},t},Be=new function(){var e=r();return e.states={UNINIT:"UNINIT",INITING:"INITING",INITED:"INITED"},e.state=e.states.UNINIT,e.type=null,e.lastConnectedAt=null,e.lastDisconnectedAt=null,e.lastTypeChangedAt=null,e.networkChangeTimer=null,e._init=function(t,n){if(e.state=e.states.INITING,navigator.connection&&navigator.connection.addEventListener){var i=e._getNetworkInfo();e.type=i&&i.type,e.state=e.states.INITED,t&&t()}else e.state=e.states.UNINIT,n&&n("DO_NOT_SUPPORT")},e._getNetworkInfo=function(){return navigator.connection},e._reloadNetworkInfo=function(){var t=e._getNetworkInfo(),n=t&&t.type||"UNSUPPORTED",i=Date.now();if(n!==e.type){e.lastTypeChangedAt=i,"none"==n?e.lastDisconnectedAt=i:"none"==e.type&&(e.lastConnectedAt=i),e.type=n;var o={type:"networkTypeChanged",networkType:n};e.dispatchEvent(o)}},e.getStats=function(t,n){var i={},o=e._getNetworkInfo();o&&(i.NetworkType=o.type||"UNSUPPORTED"),setTimeout(function(){t(i)},0)},e._init(function(){navigator.connection.addEventListener("change",function(){e._reloadNetworkInfo()}),e.networkChangeTimer=setInterval(function(){e._reloadNetworkInfo()},5e3)},function(e){}),e},je=function(e){var t={key:void 0,highStream:null,lowStream:null,lowStreamParameter:null,isDualStream:!1,highStreamState:2,lowStreamState:2,proxyServer:null,turnServer:{},useProxyServer:!1};t.mode=e.mode,t.clientId=Object(W.b)().slice(0,5),t.uintUid=null;e=v()({},e);return t.aespassword=null,t.aesmode="none",t.hasPublished=!1,t.getConnectionState=function(){var n=a.b.reportApiInvoke(e.sessionId,{name:"Client.getConnectionState",options:arguments,tag:"tracer"}),i=Pe.connetionStateMap[t.gatewayClient.state];return n(),i},t.setClientRole=function(n,i){var r=a.b.reportApiInvoke(e.sessionId,{callback:i,name:"Client.setClientRole",options:arguments,tag:"tracer"});if(K(n,"setClientRole",["host","audience"]),"rtc"===t.mode){var s="RTC mode can not use setClientRole";return o.default.warning("[".concat(t.clientId,"] ").concat(s)),r&&r(s)}t.gatewayClient&&t.gatewayClient.state===Pe.CONNECTED?("audience"===n&&(0===this.highStreamState?this._unpublish(this.highStream,function(){r&&r(null,{role:n})},function(e){r&&r(e)}):t.gatewayClient.setClientRole("audience",r)),"host"===n&&t.gatewayClient.setClientRole("host",r)):(t.gatewayClient.role=n,r&&r(null,{role:n}))},t.getGatewayInfo=function(e){if(t.gatewayClient.state!==Pe.CONNECTED){var n="Client is not in connected state";return o.default.error("[".concat(t.clientId,"] ").concat(n)),void e(n)}t.gatewayClient.getGatewayInfo(function(t){e(null,t)},e)},t.renewToken=function(n,i,r){var s=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Client.renewToken",options:arguments,tag:"tracer"});if(!te(n))throw new Error("Invalid token: Token is of the string type .Length of the string: [1,255]. ASCII characters only.");return t.gatewayClient?t.key?(t.key=n,void t.gatewayClient.renewToken(n,function(e){return s(null,e)},s)):(o.default.error("[".concat(t.clientId,"] renewToken should not be called before user join")),s(E.INVALID_OPERATION)):(o.default.error("[".concat(t.clientId,"] renewToken Failed. GatewayClient not Exist")),s(E.INVALID_OPERATION))},t.setLowStreamParameter=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setLowStreamParameter",options:arguments,tag:"tracer"});Y(n,"param");var r=n.width,s=n.height,d=n.framerate,c=n.bitrate;ae(r)||Q(r,"width"),ae(s)||Q(s,"height"),ae(d)||Q(d,"framerate"),ae(c)||Q(c,"bitrate",1,1e7),(!r&&s||r&&!s)&&o.default.warning("[".concat(t.clientId,"] The width and height parameters take effect only when both are set")),t.lowStreamParameter=n,i()},t.init=function(n,i,r){var s=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Client.init",options:arguments,tag:"tracer"});q(n),Object(p.isChromeKernel)()&&Object(p.getChromeKernelVersion)()<=48?r?s(E.BAD_ENVIRONMENT):Object(W.f)():(o.default.info("[".concat(t.clientId,"] Initializing AgoraRTC client, appId: ").concat(n,".")),e.appId=n,e.sessionId=Object(W.b)(),s())},t.setTurnServer=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setTurnServer",options:arguments,tag:"tracer"});if(t.gatewayClient&&t.gatewayClient.state!==Pe.DISCONNECTED)throw new Error("Set turn server before join channel");if(t.useProxyServer)throw new Error("You have already set the proxy");Y(n,"turnServer");var r=n.turnServerURL,s=n.username,d=n.password,c=n.udpport,u=n.forceturn,l=n.tcpport;q(r,"turnServerURL"),q(s,"username"),q(d,"password"),q(c,"udpport"),ae(u)||X(u,"forceturn"),t.turnServer.url=r,t.turnServer.udpport=c,t.turnServer.username=s,t.turnServer.credential=d,t.turnServer.forceturn=u||!1,ae(l)||(q(l,"tcpport"),t.turnServer.tcpport=l,o.default.info("[".concat(t.clientId,"] Set turnserver tcpurl. ").concat(t.turnServer.url,":").concat(t.turnServer.tcpport))),o.default.info("[".concat(t.clientId,"] Set turnserver udpurl. ").concat(t.turnServer.url,":").concat(t.turnServer.udpport,",username: ").concat(t.turnServer.uername,",password: ").concat(t.turnServer.credential)),i()},t.setProxyServer=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setProxyServer",options:arguments,tag:"tracer"});if(t.gatewayClient&&t.gatewayClient.state!==Pe.DISCONNECTED)throw new Error("Set proxy server before join channel");if(!n)throw new Error("Do not set the proxyServer parameter as empty");if(t.useProxyServer)throw new Error("You have already set the proxy");q(n,"proxyServer"),t.proxyServer=n,a.b.setProxyServer(n),o.default.setProxyServer(n),i()},t.startProxyServer=function(){var n=a.b.reportApiInvoke(e.sessionId,{name:"Client.startProxyServer",options:arguments,tag:"tracer"});if(t.gatewayClient&&t.gatewayClient.state!==Pe.DISCONNECTED)throw new Error("Start proxy server before join channel");if(t.proxyServer||t.turnServer.url)throw new Error("You have already set the proxy");t.useProxyServer=!0,n()},t.stopProxyServer=function(){var n=a.b.reportApiInvoke(e.sessionId,{name:"Client.stopProxyServer",options:arguments,tag:"tracer"});if(t.gatewayClient&&t.gatewayClient.state!==Pe.DISCONNECTED)throw new Error("Stop proxy server after leave channel");a.b.setProxyServer(),o.default.setProxyServer(),t.turnServer={},t.proxyServer=null,t.useProxyServer=!1,n()},t.setEncryptionSecret=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setEncryptionSecret",options:arguments,tag:"tracer"});q(n,"password"),t.aespassword=n,i()},t.setEncryptionMode=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setEncryptionMode",options:arguments,tag:"tracer"});if(q(n,"encryptionMode"),-1===me.indexOf(n))throw new Error('Invalid encryptionMode: encryptionMode should be "aes-128-xts" | "aes-256-xts" | "aes-128-ecb"');t.aesmode=n,i()},t.configPublisher=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.configPublisher",options:arguments,tag:"tracer"});Y(n,"config");var o=n.width,r=n.height,s=n.framerate,d=n.bitrate,c=n.publisherUrl;Q(o,"width"),Q(r,"height"),Q(s,"framerate"),Q(d,"bitrate",1,1e7),c&&q(c,"publisherUrl"),t.gatewayClient.configPublisher(n),i()},t.enableDualStream=function(n,i){var r=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return i&&i(e);n&&n(t)},name:"Client.enableDualStream",options:arguments,tag:"tracer"});return"iOS"===Object(p.getBrowserOS)()?(a.b.streamSwitch(e.sessionId,{lts:(new Date).getTime(),isdual:!0,succ:!1}),r(E.IOS_NOT_SUPPORT)):Object(p.isWeChatBrowser)()?(a.b.streamSwitch(e.sessionId,{lts:(new Date).getTime(),isdual:!0,succ:!1}),r(E.WECHAT_NOT_SUPPORT)):(a.b.streamSwitch(e.sessionId,{lts:(new Date).getTime(),isdual:!0,succ:!0}),t.isDualStream=!0,void(0===t.highStreamState?t._publishLowStream(function(e){return r(null,e)},function(e){o.default.warning("[".concat(t.clientId,"]"),e),r(E.ENABLE_DUALSTREAM_FAILED)}):1===t.highStreamState?r(E.STILL_ON_PUBLISHING):r(null)))},t.disableDualStream=function(n,i){var r=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return i&&i(e);n&&n(t)},name:"Client.disableDualStream",options:arguments,tag:"tracer"});a.b.streamSwitch(e.sessionId,{lts:(new Date).getTime(),isdual:!1,succ:!0}),t.isDualStream=!1,0===t.highStreamState?t._unpublishLowStream(function(){t.highStream.lowStream=null,r()},function(e){o.default.warning("[".concat(t.clientId,"]"),e),r(E.DISABLE_DUALSTREAM_FAILED)}):1===t.highStreamState?r(E.STILL_ON_PUBLISHING):r()},t._createLowStream=function(e,n){if(t.highStream&&t.highStream.stream){var a=v()({},t.highStream.params);if(a.streamID+=1,a.audio=!1,a.video){var r=t.highStream.stream.getVideoTracks()[0];r?G.getVideoCameraIdByLabel(r.label,function(r){a.cameraId=r;var s=new ue(a);if(s.streamId=t.highStream.getId()+1,t.lowStreamParameter){var d=v()({},t.lowStreamParameter);if(!d.width||!d.height){var c=xe(t.highStream.profile),u=i.SUPPORT_RESOLUTION_LIST[c[0]];d.width=u[0],d.height=u[1]}if(d.framerate=d.framerate||5,d.bitrate=d.bitrate||50,Object(p.isSafari)()||Object(p.isOpera)()){o.default.debug("[".concat(t.clientId,"] Shimming lowStreamParameter"));u=i.SUPPORT_RESOLUTION_LIST[t.highStream.profile];d.width=u[0],d.height=u[1]}s.setVideoProfileCustomPlus(d)}else s.setVideoProfileCustom(xe(t.highStream.profile));s.init(function(){t.highStream.lowStream=s,t.highStream.userMuteVideo&&s.muteVideo(),e&&e(s)},n)},n):n&&n(E.HIGH_STREAM_NOT_VIDEO_TRACE)}else n&&n(E.HIGH_STREAM_NOT_VIDEO_TRACE)}else n&&n(E.HIGH_STREAM_NOT_VIDEO_TRACE)},t._getLowStream=function(e,n){t.lowStream?e(t.lowStream):t._createLowStream(function(n){t.lowStream=n,e(t.lowStream)},n)},t._publishLowStream=function(e,n){return 2!==t.lowStreamState?n&&n(E.LOW_STREAM_ALREADY_PUBLISHED):t.highStream&&t.highStream.hasScreen()?n&&n(E.SHARING_SCREEN_NOT_SUPPORT):void t._getLowStream(function(i){t.lowStreamState=1,t.gatewayClient.publish(i,{streamType:1},function(){t.lowStreamState=0,e&&e()},function(e){o.default.debug("[".concat(t.clientId,"] publish low stream failed")),n&&n(e)})},n)},t._unpublishLowStream=function(e,n){if(0!==t.lowStreamState)return n&&n(E.LOW_STREAM_NOT_YET_PUBLISHED);t.lowStream&&(t.gatewayClient.unpublish(t.lowStream,{streamType:1},function(){},function(e){o.default.debug("[".concat(t.clientId,"] unpublish low stream failed")),n&&n(e)}),t.lowStream.close(),t.lowStream=null,t.lowStreamState=2,e&&e())},t.join=function(n,i,r,s,d){var c,u=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return d&&d(e);s&&s(t)},name:"Client.join",options:arguments,tag:"tracer"});if(n&&!te(n))return o.default.warning("[".concat(t.clientId,"] Param channelKey should be string")),u(E.INVALID_PARAMETER);if(!oe(c=i)||!/^[a-zA-Z0-9!#$%&()+-:;<=.>?@[\]^_{}|~,\s]{1,64}$/.test(c))return o.default.error("Invalid Channel Name ".concat(i)),o.default.warning("[".concat(t.clientId,"] The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")),u(E.INVALID_PARAMETER);if("string"==typeof i&&""===i)return o.default.warning("[".concat(t.clientId,"] Param channel should not be empty")),u(E.INVALID_PARAMETER);if(r&&!Object(W.c)(r)&&!$(r,1,255))return o.default.error("Invalid UID ".concat(r," ").concat(z()(r))),o.default.warning("[".concat(t.clientId,"] [String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]")),u(E.INVALID_PARAMETER);if("string"==typeof r&&0==r.length)return o.default.warning("[".concat(t.clientId,"] String uid should not be empty")),u(E.INVALID_PARAMETER);if("string"==typeof r&&r.length>256)return o.default.warning("[".concat(t.clientId,"] Length of string uid should be less than 255")),u(E.INVALID_PARAMETER);t.highStream=null,t.lowStream=null,t.lowStreamParameter=null,t.isDualStream=!1,t.highStreamState=2,t.lowStreamState=2;var l={clientId:t.clientId,appId:e.appId,sid:e.sessionId,cname:i,uid:r,turnServer:t.turnServer,proxyServer:t.proxyServer,token:n||e.appId,useProxyServer:t.useProxyServer};if("string"==typeof r&&(l.stringUid=r,l.uid=t.uintUid||0),t.aespassword&&"none"!==t.aesmode&&v()(l,{aespassword:t.aespassword,aesmode:t.aesmode}),a.b.sessionInit(e.sessionId,{lts:(new Date).getTime(),cname:i,appid:e.appId,mode:e.mode,succ:!0}),t.onSuccess=function(e){t.rtcStatsCollector.startNetworkQualityTimer(),t.onSuccess=null,u(null,e)},t.onFailure=function(e){return u(e)},t.channel=i,t.gatewayClient.state!==Pe.DISCONNECTED)return o.default.error("[".concat(t.clientId,"] Client already in connecting/connected state")),u(E.INVALID_OPERATION),void a.b.joinGateway(e.sessionId,{lts:Date.now(),succ:!1,ec:E.INVALID_OPERATION,addr:null});t.gatewayClient.state=Pe.CONNECTING,Ce(l,function(a,r){o.default.info("[".concat(t.clientId,"] Joining channel: ").concat(i)),t.gatewayClient.dispatchEvent({type:"config-distribute",config:r,joinInfo:l}),t.key=n||e.appId,l.cid=a.cid,l.uid=a.uid,l.clientId=t.clientId,t.uintUid=a.uid,a.uni_lbs_ip&&a.uni_lbs_ip[1]&&(l.uni_lbs_ip=a.uni_lbs_ip[1]),l.gatewayAddr=a.gateway_addr,t.joinInfo=l,t.gatewayClient.join(l,t.key,function(e){o.default.info("[".concat(t.clientId,"] Join channel ").concat(i," success, join with uid: ").concat(e,".")),t.onSuccess=null,t.rtcStatsCollector.startNetworkQualityTimer(),u(null,e)},function(e){return u(e)})})},t.renewChannelKey=function(n,i,r){var s=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return r&&r(e);i&&i(t)},name:"Client.renewChannelKey",options:arguments,tag:"tracer"});q(n,"key",1,2047),void 0===t.key?(o.default.error("[".concat(t.clientId,"] renewChannelKey should not be called before user join")),s(E.INVALID_OPERATION)):(t.key=n,t.gatewayClient.key=n,t.gatewayClient.rejoin(),s())},t.leave=function(n,r){var s=!1,d=a.b.reportApiInvoke(e.sessionId,{callback:function(e,i){if(e)return r&&r(e);var o,a;o=t.clientId,a=!1,Te[o]=a,t._renewSession(),t.rtcStatsCollector.clearNetworkQualityTimer(),n&&n(i)},name:"Client.leave",options:arguments,tag:"tracer"});o.default.info("[".concat(t.clientId,"] Leaving channel")),t.gatewayClient.leave(function(e){s=!0,d(null,e)},d),setTimeout(function(){s||(t.gatewayClient.socket.close(),t.gatewayClient.socket=null,t.gatewayClient.state=Pe.DISCONNECTED,d(null,"LEAVE_MSG_TIMEOUT"))},Object(i.getParameter)("LEAVE_MSG_TIMEOUT"))},t._renewSession=function(){var n=Object(W.b)();if(o.default.debug("renewSession ".concat(e.sessionId," => ").concat(n)),e.sessionId=n,t.joinInfo&&(t.joinInfo.sid=n),t.gatewayClient&&(t.gatewayClient.joinInfo&&(t.gatewayClient.joinInfo.sid=n),t.gatewayClient.localStreams))for(var i in t.gatewayClient.localStreams){var a=t.gatewayClient.localStreams[i];a&&(a.sid=n)}},t._publish=function(n,i,a){if(2!==t.highStreamState)return o.default.warning("[".concat(t.clientId,"] Can't publish stream when stream already publish ").concat(n.getId())),a&&a(E.STREAM_ALREADY_PUBLISHED);o.default.info("[".concat(t.clientId,"] Publishing stream, uid ").concat(n.getId())),t.highStream=n,t.highStreamState=1,t.highStream.streamId=t.joinInfo.stringUid||t.joinInfo.uid,t.hasPublished=!1;var r=function(n,i,a){t.gatewayClient.publish(n,{streamType:0},function(){n.sid=e.sessionId,t.highStreamState=0,o.default.info("[".concat(t.clientId,"] Publish success, uid: ").concat(n.getId())),t.isDualStream?t._publishLowStream(function(){i&&i()},function(e){o.default.warning("[".concat(t.clientId,"] "),e),i&&i()}):i&&i()},a)};"audience"===t.gatewayClient.role&&"live"===t.mode?t.gatewayClient.setClientRole("host",function(e){if(e)return a&&a(e);r(n,i,a)}):r(n,i,a)},t._unpublish=function(e,n,i){if(0!==t.highStreamState)return o.default.warning("[".concat(t.clientId,"] Can't unpublish stream when stream not publish")),i&&i(E.STREAM_NOT_YET_PUBLISHED);o.default.info("[".concat(t.clientId,"] Unpublish stream, uid ").concat(e.getId()));var a=function(e,n,i){t.isDualStream&&t.lowStream&&t._unpublishLowStream(null,i),t.gatewayClient.unpublish(e,{streamType:0},function(){t.highStreamState=2,o.default.info("[".concat(t.clientId,"] Unpublish stream success, uid: ").concat(e.getId())),n&&n()},function(n){o.default.info("[".concat(t.clientId,"] Unpublish stream fail, uid: ").concat(e.getId())),i&&i(n)})};"host"===t.gatewayClient.role&&"live"===t.mode?t.gatewayClient.setClientRole("audience",function(t){if(t)return i&&i(t);a(e,n,i)}):a(e,n,i)},t.publish=function(n,i){var o=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return i&&i(e)},name:"Client.publish",tag:"tracer",options:{stream:"too long to show",onFailure:!!i}});2===t.highStreamState?t._publish(n,function(e){return o(null,e)},function(e){return o(e)}):o(E.STREAM_ALREADY_PUBLISHED)},t.unpublish=function(n,i,o){var r=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return i&&i(e);o&&o(t)},name:"Client.unpublish",tag:"tracer",options:{stream:"too long to show",onFailure:!!i}});0===t.highStreamState?t._unpublish(n,function(e){return r(null,e)},function(e){return r(e)}):r(E.STREAM_NOT_YET_PUBLISHED)},t.subscribe=function(n,i,r){var s=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return r&&r(e)},name:"Client.subscribe",tag:"tracer",options:{stream:"too long to show",options:i,onFailure:!!r}});"function"==typeof i&&(r=i,i=null),Y(n,"stream"),ae(i)||(Y(i,"options"),ae(i.video)||X(i.video,"options.video"),ae(i.audio)||X(i.audio,"options.audio"));var d={video:!0,audio:!0};if(!ae(i)){if(Object(p.isSafari)()&&(!i.video||!i.audio)){var c="SAFARI_NOT_SUPPORTED_FOR_TRACK_SUBSCRIPTION";return o.default.error("[".concat(t.clientId,"] "),c),void s(c)}if(!ae(i.video)&&!ee(i.video)||!ae(i.audio)&&!ee(i.audio)||!1===i.audio&&!1===i.video){c="INVALID_PARAMETER ".concat(JSON.stringify(i));return o.default.error("[".concat(t.clientId,"] "),c),void s(c)}}n.subscribeOptions?(v()(n.subscribeOptions,d,i),t.gatewayClient.subscribeChange(n,function(e){return s(null,e)},s)):(n.subscribeOptions=v()({},d,i),t.gatewayClient.subscribe(n,function(e){return s(null,e)},s))},t.unsubscribe=function(n,i){var r=a.b.reportApiInvoke(e.sessionId,{callback:function(e,t){if(e)return i&&i(e)},name:"Client.unsubscribe",tag:"tracer",options:{stream:"too long to show",onFailure:!!i}});o.default.info("[".concat(t.clientId,"] Unsubscribe stream, uid: ").concat(n.getId())),t.gatewayClient.unsubscribe(n,function(e){return r(null,e)},r)},t.setRemoteVideoStreamType=function(n,i){var o=a.b.reportApiInvoke(e.sessionId,{name:"Client.setRemoteVideoStreamType",tag:"tracer",options:{stream:"too long to show",streamType:i}});K(i,"streamType",[0,1]),t.gatewayClient.setRemoteVideoStreamType(n,i),o()},t.setStreamFallbackOption=function(n,i){var o=a.b.reportApiInvoke(e.sessionId,{name:"Client.setStreamFallbackOption",tag:"tracer",options:{stream:"too long to show",fallbackType:i}});K(i,"fallbackType",[0,1,2]),t.gatewayClient.setStreamFallbackOption(n,i),o()},t.startLiveStreaming=function(n,i){var o=a.b.reportApiInvoke(e.sessionId,{name:"Client.startLiveStreaming",options:arguments,tag:"tracer"});q(n,"url"),ae(i)||X(i,"transcodingEnabled"),t.gatewayClient.startLiveStreaming(n,i),o()},t.stopLiveStreaming=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.stopLiveStreaming",options:arguments,tag:"tracer"});q(n,"url"),t.gatewayClient.stopLiveStreaming(n),i()},t.setLiveTranscoding=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.setLiveTranscoding",options:arguments,tag:"tracer"});Y(n,"transcoding");var o=n.width,r=n.height,s=n.videoBitrate,d=n.videoFramerate,c=n.lowLatency,u=n.audioSampleRate,l=n.audioBitrate,p=n.audioChannels,f=n.videoGop,m=n.videoCodecProfile,g=n.userCount,S=n.backgroundColor,I=n.transcodingUsers;if(ae(o)||Q(o,"width"),ae(r)||Q(r,"height"),ae(s)||Q(s,"videoBitrate",1,1e6),ae(d)||Q(d,"videoFramerate"),ae(c)||X(c,"lowLatency"),ae(u)||K(u,"audioSampleRate",[32e3,44100,48e3]),ae(l)||Q(l,"audioBitrate",1,128),ae(p)||K(p,"audioChannels",[1,2,3,4,5]),ae(f)||Q(f,"videoGop"),ae(m)||K(m,"videoCodecProfile",[66,77,100]),ae(g)||Q(g,"userCount",0,17),ae(S)||Q(S,"backgroundColor",0,16777215),!ae(I)){if(!(I instanceof Array))throw new Error("[transcodingUsers]: transcodingUsers should be Array");if(I.length>17)throw new Error("The length of transcodingUsers cannot greater than 17");I.map(function(e,t){if(!ae(e.uid)&&!Object(W.c)(e.uid)&&!$(e.uid,1,255))throw new Error("[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");if(ae(e.x)||Q(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),ae(e.y)||Q(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),ae(e.width)||Q(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),ae(e.height)||Q(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),ae(e.zOrder)||Q(e.zOrder,"transcodingUser[".concat(t,"].zOrder"),0,100),!(ae(e.alpha)||"number"==typeof e.alpha&&e.alpha<=1&&e.alpha>=0))throw new Error("transcodingUser[${index}].alpha: The value range is [0, 1]")})}v()(We,n),t.gatewayClient.setLiveTranscoding(We),i()},t.addInjectStreamUrl=function(n,i){var o=a.b.reportApiInvoke(e.sessionId,{name:"Client.addInjectStreamUrl",options:arguments,tag:"tracer"});q(n,"url",1,255),Y(i,"config"),!ae(i&&i.width)&&Q(i.width,"config.width",0,1e4),!ae(i&&i.height)&&Q(i.height,"config.height",0,1e4),!ae(i&&i.videoGop)&&Q(i.videoGop,"config.videoGop",1,1e4),!ae(i&&i.videoFramerate)&&Q(i.videoFramerate,"config.videoFramerate",1,1e4),!ae(i&&i.videoBitrate)&&Q(i.videoBitrate,"config.videoBitrate",1,1e4),!ae(i&&i.audioSampleRate)&&K(i.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),!ae(i&&i.audioBitrate)&&Q(i.audioBitrate,"config.audioBitrate",1,1e4),!ae(i&&i.audioChannels)&&Q(i.audioChannels,"config.audioChannels",1,2),v()(He,i),t.gatewayClient.addInjectStreamUrl(n,He),o()},t.removeInjectStreamUrl=function(n){var i=a.b.reportApiInvoke(e.sessionId,{name:"Client.removeInjectStreamUrl",options:arguments,tag:"tracer"});q(n,"url",1,255),t.gatewayClient.removeInjectStreamUrl(n),i()},t.enableAudioVolumeIndicator=function(n,i){var r=a.b.reportApiInvoke(e.sessionId,{name:"Client.enableAudioVolumeIndicator",options:arguments,tag:"tracer"});n=n||2e3,Q(i=i||3,"smooth",1,100),Q(n,"interval",50,1e5),t.audioVolumeIndication=t.audioVolumeIndication||{enabled:!0},t.audioVolumeIndication.interval=n,t.audioVolumeIndication.smooth=i,t.audioVolumeIndication={interval:n,smooth:i},o.default.info("[".concat(t.clientId,"] enableAudioVolumeIndicator interval ").concat(n," smooth ").concat(i)),t.gatewayClient.enableAudioVolumeIndicator(n,i),r()},t.getNetworkStats=function(e,n){return o.default.deprecate("[".concat(t.clientId,"] client.getNetworkStats is deprecated. Use client.getTransportStats instead.")),Be.getStats(e,n)},t.getSystemStats=function(e,t){return m.getStats(e,t)},t.getRecordingDevices=function(e,t){return G.getRecordingDevices(e,t)},t.getPlayoutDevices=function(e,t){return G.getPlayoutDevices(e,t)},t.getCameras=function(e,t){return G.getCameras(e,t)},t.getRemoteAudioStats=function(e,n){return t.rtcStatsCollector.getRemoteAudioStats(e,n)},t.getLocalAudioStats=function(e,n){return t.rtcStatsCollector.getLocalAudioStats(e,n)},t.getRemoteVideoStats=function(e,n){return t.rtcStatsCollector.getRemoteVideoStats(e,n)},t.getLocalVideoStats=function(e,n){return t.rtcStatsCollector.getLocalVideoStats(e,n)},t._getRemoteVideoQualityStats=function(e,n){return t.rtcStatsCollector.getRemoteVideoQualityStats(e,n)},t._getRemoteAudioQualityStats=function(e,n){return t.rtcStatsCollector.getRemoteAudioQualityStats(e,n)},t.getTransportStats=function(e,n){return t.rtcStatsCollector.getTransportStats(function(t){return Be.getStats(function(n){var i=v()({},t,n);e&&e(i)},n)},n)},t.getSessionStats=function(e,n){return t.rtcStatsCollector.getSessionStats(e,n)},t.onNetworkQuality=function(){return t.rtcStatsCollector.onNetworkQuality(onSuccess,onFailure)},e.clientId=t.clientId,t.gatewayClient=Pe(e),t.on=t.gatewayClient.on,t.off=t.gatewayClient.removeEventListener,t.rtcStatsCollector=function(e){var t=r();return t.gatewayClient=e,t.exceptionMonitor=new Fe(e),t.localStats={},t.remoteStats={},t.session={sendBytes:0,recvBytes:0,WSSendBytes:0,WSSendBytesDelta:0,WSRecvBytes:0,WSRecvBytesDelta:0,HTTPSendBytes:0,HTTPSendBytesDelta:0,HTTPRecvBytes:0,HTTPRecvBytesDelta:0},t.getRemoteAudioStats=function(e){var n={};for(var i in t.remoteStats){var o={},a=t.remoteStats[i];H(o,"End2EndDelay",a.peer_delay&&a.peer_delay.audio_delay),H(o,"TransportDelay",a.peer_delay&&a.peer_delay.e2e_delay),H(o,"PacketLossRate",a.peer_delay&&a.peer_delay.e2e_audio_lost_ratio_400ms),H(o,"RecvLevel",a.audioStats&&a.audioStats.audioOutputLevel),H(o,"RecvBitrate",a.audioRecvBitrate),H(o,"CodecType",a.audioStats&&a.audioStats.googCodecName),H(o,"MuteState",a.audioDisabled),H(o,"TotalFreezeTime",a.audioStats&&a.audioStats.audioTotalFreezeTime),H(o,"TotalPlayDuration",a.audioStats&&a.audioStats.audioTotalPlayDuration),n[i]=o}e&&e(n)},t.getLocalAudioStats=function(e){var n={};for(var i in t.localStats){var o={},a=t.localStats[i];H(o,"RecordingLevel",a.audioStats&&a.audioStats.audioInputLevel),H(o,"SendLevel",a.audioStats&&a.audioStats.totalAudioEnergy),H(o,"SamplingRate",a.audioStats&&a.audioStats.totalSamplesDuration),H(o,"SendBitrate",a.audioSendBitrate),H(o,"CodecType",a.audioStats&&a.audioStats.googCodecName),H(o,"MuteState",a.audioDisabled);var r=t.gatewayClient.localStreams[i];r&&r.isPlaying()&&H(o,"MuteState",r.userMuteAudio?"1":"0"),n[i]=o}e&&e(n)},t.getRemoteVideoStats=function(e){var n={};for(var i in t.remoteStats){var o={},a=t.remoteStats[i];H(o,"End2EndDelay",a.peer_delay&&a.peer_delay.video_delay),H(o,"TransportDelay",a.peer_delay&&a.peer_delay.e2e_delay),H(o,"PacketLossRate",a.peer_delay&&a.peer_delay.e2e_video_lost_ratio_400ms),H(o,"RecvBitrate",a.videoRecvBitrate),H(o,"RecvResolutionWidth",a.videoStats&&a.videoStats.googFrameWidthReceived),H(o,"RecvResolutionHeight",a.videoStats&&a.videoStats.googFrameHeightReceived),H(o,"RenderResolutionWidth",a.videoStats&&a.videoStats.renderRemoteWidth),H(o,"RenderResolutionHeight",a.videoStats&&a.videoStats.renderRemoteHeight),H(o,"RenderFrameRate",a.videoStats&&a.videoStats.googFrameRateOutput),H(o,"MuteState",a.videoDisabled),H(o,"TotalFreezeTime",a.videoStats&&a.videoStats.videoTotalFreezeTime),H(o,"TotalPlayDuration",a.videoStats&&a.videoStats.videoTotalPlayDuration),n[i]=o}e&&e(n)},t.getLocalVideoStats=function(e){var n={};for(var i in t.localStats){var o={},a=t.localStats[i];H(o,"TargetSendBitrate",a.videoTargetSendBitrate),H(o,"SendFrameRate",a.videoStats&&a.videoStats.googFrameRateSent),H(o,"SendBitrate",a.videoSendBitrate),H(o,"SendResolutionWidth",a.videoStats&&a.videoStats.googFrameWidthSent),H(o,"SendResolutionHeight",a.videoStats&&a.videoStats.googFrameHeightSent),H(o,"CaptureResolutionWidth",a.videoStats&&a.videoStats.googFrameWidthInput),H(o,"CaptureResolutionHeight",a.videoStats&&a.videoStats.googFrameHeightInput),H(o,"EncodeDelay",a.videoStats&&a.videoStats.googAvgEncodeMs),H(o,"MuteState",a.videoDisabled),H(o,"TotalFreezeTime",a.videoStats&&a.videoStats.videoTotalFreezeTime),H(o,"TotalDuration",a.videoStats&&a.videoStats.videoTotalPlayDuration),H(o,"CaptureFrameRate",a.videoStats&&a.videoStats.googFrameRateSent),a.videoStats.googFrameWidthInput||H(o,"CaptureResolutionWidth",a.videoStats&&a.videoStats.renderLocalWidth),a.videoStats.googFrameHeightInput||H(o,"CaptureResolutionHeight",a.videoStats&&a.videoStats.renderLocalHeight),n[i]=o,e&&e(n)}},t.getRemoteVideoQualityStats=function(e){var n={};for(var i in t.remoteStats){var o={},a=t.remoteStats[i];H(o,"videoReceiveDelay",a.videoStats&&a.videoStats.googCurrentDelayMs),H(o,"VideoFreezeRate",a.videoStats&&a.videoStats.videoFreezeRate),H(o,"FirstFrameTime",a.firstFrameTime),n[i]=o}e&&e(n)},t.getRemoteAudioQualityStats=function(e){var n={};for(var i in t.remoteStats){var o={},a=t.remoteStats[i];H(o,"audioReceiveDelay",a.audioStats&&a.audioStats.googCurrentDelayMs),H(o,"AudioFreezeRate",a.videoStats&&a.videoStats.videoFreezeRate),n[i]=o}e&&e(n)},t.getTransportStats=function(e){var n={},i={},o=t.gatewayClient.traffic_stats,a=o.peer_delay;if(H(n,"OutgoingAvailableBandwidth",t.gatewayClient.OutgoingAvailableBandwidth/1e3),H(n,"RTT",o&&o.access_delay),a){var r=!0,s=!1,d=void 0;try{for(var c,u=a[Symbol.iterator]();!(r=(c=u.next()).done);r=!0){var l=c.value;l.downlink_estimate_bandwidth&&(i[l.peer_uid]=l.downlink_estimate_bandwidth/1e3+"")}}catch(e){s=!0,d=e}finally{try{r||null==u.return||u.return()}finally{if(s)throw d}}}n.IncomingAvailableBandwidth=i,e&&e(n)},t.getSessionStats=function(e){var n={},i=t.gatewayClient.traffic_stats,o=t.gatewayClient.socket,a=0,r=0;for(var s in t.remoteStats)(d=t.remoteStats[s])&&d.videoStats&&d.videoStats.videoRecvBytesDelta&&(r+=parseInt(d.videoStats.videoRecvBytesDelta)),d&&d.audioStats&&d.audioStats.audioRecvBytesDelta&&(r+=parseInt(d.audioStats.audioRecvBytesDelta));for(var s in t.localStats){var d;(d=t.localStats[s])&&d.videoStats&&d.videoStats.videoSendBytesDelta&&(a+=parseInt(d.videoStats.videoSendBytesDelta)),d&&d.audioStats&&d.audioStats.audioSendBytesDelta&&(a+=parseInt(d.audioStats.audioSendBytesDelta))}var c=a+t.session.WSSendBytesDelta+t.session.HTTPSendBytesDelta,u=r+t.session.WSRecvBytesDelta+t.session.HTTPRecvBytesDelta,l=t.session.sendBytes+Object(ve.b)(),p=t.session.recvBytes+Object(ve.a)();t.gatewayClient.socket&&t.gatewayClient.socket.state===t.gatewayClient.CONNECTED&&(l+=o.getSendBytes(),p+=o.getRecvBytes());var f=1;i.peer_delay&&(f=i.peer_delay.length,f+=1),H(n,"Duration",o.getDuration()),H(n,"UserCount",f),H(n,"SendBytes",l),H(n,"RecvBytes",p),H(n,"SendBitrate",8*c/1e3),H(n,"RecvBitrate",8*u/1e3),e&&e(n)},t.isLocalVideoFreeze=function(e,t){var n=0,i=0;if(!e||!t)return!1;if(Object(p.isChrome)()||Object(p.isOpera)())n=e.googFrameRateInput,i=e.googFrameRateSent;else if(Object(p.isSafari)())n=parseInt(e.framerateMean),i=parseInt(e.framesEncoded)-parseInt(t.framesEncoded);else{if(!Object(p.isFireFox)())return!1;n=parseInt(e.framerateMean),i=parseInt(e.framesEncoded)-parseInt(t.framesEncoded)}return n>5&&i<3},t.isRemoteVideoFreeze=function(e,t){var n=0,i=0;if(!e||!t)return!1;if(Object(p.isChrome)()||Object(p.isOpera)())n=e.googFrameRateReceived,i=e.googFrameRateDecoded;else if(Object(p.isSafari)())n=e.framerateMean,i=parseInt(e.framesDecoded)-parseInt(t.framesDecoded);else{if(!Object(p.isFireFox)())return!1;n=parseInt(e.framesReceived)-parseInt(t.framesReceived),i=parseInt(e.framesDecoded)-parseInt(t.framesDecoded)}return n>5&&n<10&&i<3||n>10&&n<20&&i<4||n>20&&i<5},t.isAudioFreeze=function(e){if(Object(p.isChrome)()&&e){if(e.googDecodingPLC&&e.googDecodingPLCCNG&&e.googDecodingCTN)return(parseInt(e.googDecodingPLC)+parseInt(e.googDecodingPLCCNG))/parseInt(e.googDecodingCTN)>.2}else if((Object(p.isSafari)()||Object(p.isFireFox)())&&e.packetsLost&&e.packetsReceived)return parseInt(e.packetsLost)/(parseInt(e.packetsLost)+parseInt(e.packetsReceived))>.2;return!1},t.isAudioDecodeFailed=function(e){return!!((Object(p.isChrome)()||Object(p.isOpera)())&&e&&parseInt(e.bytesReceived)>0&&0===parseInt(e.googDecodingNormal))},t.startNetworkQualityTimer=function(){t.clearNetworkQualityTimer(),t.networkQualityTimer=setInterval(function(){if(t.gatewayClient.state!==Pe.CONNECTED)t.gatewayClient.dispatchEvent({type:"network-quality",uplinkNetworkQuality:0,downlinkNetworkQuality:0});else{var e=t.gatewayClient.traffic_stats;t.gatewayClient.dispatchEvent({type:"network-quality",uplinkNetworkQuality:t.networkQualityTrans(e.uplink_network_quality),downlinkNetworkQuality:t.networkQualityTrans(e.downlink_network_quality)})}},2e3)},t.clearNetworkQualityTimer=function(){t.networkQualityTimer&&clearInterval(t.networkQualityTimer)},t.networkQualityTrans=function(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0},t.getStatsTimer=setInterval(function(){var e=t.gatewayClient.traffic_stats,n=Date.now();t.gatewayClient.dispatchEvent({type:"_testException"}),Object.keys(t.localStats).length&&t.exceptionMonitor.setLocalStats(t.localStats),Object.keys(t.remoteStats).length&&t.exceptionMonitor.setRemoteStats(t.remoteStats);var i={};Object.keys(t.gatewayClient.remoteStreams).forEach(function(o){var a=t.gatewayClient.remoteStreams[o],r=t.remoteStats[o],s={id:o,updatedAt:n};i[o]=s,s.firstFrameTime=a.firstFrameTime,r?(s.audioTotalPlayDuration=r.audioTotalPlayDuration+1,s.audioTotalFreezeTime=r.audioTotalFreezeTime,s.isAudioFreeze=!1,s.isAudioDecodeFailed=!1,s.videoTotalPlayDuration=r.videoTotalPlayDuration+1,s.videoTotalFreezeTime=r.videoTotalFreezeTime,s.isVideoFreeze=!1):(s.audioTotalPlayDuration=1,s.audioTotalFreezeTime=0,s.videoTotalPlayDuration=1,s.videoTotalFreezeTime=0);var d=e&&e.peer_delay&&e.peer_delay.find(function(e){return e.peer_uid==o});d&&(s.peer_delay=d),a&&(a.isPlaying()&&(s.audioDisabled=a.userMuteAudio||a.peerMuteAudio?"1":"0",s.videoDisabled=a.userMuteVideo||a.peerMuteVideo?"1":"0"),r&&r.peer_delay&&d&&r.peer_delay.stream_type!==d.stream_type&&t.gatewayClient.dispatchEvent({type:"streamTypeChange",uid:o,streamType:d.stream_type}),a.pc&&"established"==a.pc.state&&a.pc.getStats(function(e){if(s.pcStats=e,s.audioStats=e.find(function(e){return"audio"==e.mediaType&&(e.id.indexOf("_recv")>-1||e.id.toLowerCase().indexOf("inbound")>-1)}),s.videoStats=e.find(function(e){return"video"==e.mediaType&&(e.id.indexOf("_recv")>-1||e.id.toLowerCase().indexOf("inbound")>-1)}),r&&r.audioStats&&s.audioStats){var n=parseInt(s.audioStats.bytesReceived)-parseInt(r.audioStats.bytesReceived),i=parseInt(s.audioStats.googDecodingNormal)-parseInt(r.audioStats.googDecodingNormal);if(s.audioStats.audioRecvBytesDelta=n,s.audioStats.audioDecodingNormalDelta=i,t.session.recvBytes+=n,isFinite(n)&&s.audioStats.timestamp){var o=s.audioStats.timestamp.getTime()-r.audioStats.timestamp.getTime();s.audioRecvBitrate=Math.floor(8*n/o)}t.isAudioFreeze(s.audioStats)&&s.audioTotalPlayDuration>10&&(s.audioTotalFreezeTime++,s.isAudioFreeze=!0),t.isAudioDecodeFailed(s.audioStats)&&s.audioTotalPlayDuration>10&&(s.isAudioDecodeFailed=!0),s.audioStats.audioTotalFreezeTime=s.audioTotalFreezeTime,s.audioStats.audioTotalPlayDuration=s.audioTotalPlayDuration,s.audioStats.audioFreezeRate=Math.ceil(100*s.audioTotalFreezeTime/s.audioTotalPlayDuration)}if(r&&r.videoStats&&s.videoStats){var d=parseInt(s.videoStats.bytesReceived)-parseInt(r.videoStats.bytesReceived);s.videoStats.videoRecvBytesDelta=d,t.session.recvBytes+=d,isFinite(d)&&s.videoStats.timestamp&&(o=s.videoStats.timestamp.getTime()-r.videoStats.timestamp.getTime(),s.videoRecvBitrate=Math.floor(8*d/o)),t.isRemoteVideoFreeze(s.videoStats,r.videoStats)&&(s.videoTotalFreezeTime++,s.isVideoFreeze=!0),s.videoStats.videoTotalFreezeTime=s.videoTotalFreezeTime,s.videoStats.videoTotalPlayDuration=s.videoTotalPlayDuration,s.videoStats.videoFreezeRate=Math.ceil(100*s.videoTotalFreezeTime/s.videoTotalPlayDuration),a.player&&a.player.video&&a.player.video.videoWidth&&a.player.video.videoHeight?(s.videoStats.renderRemoteWidth=a.player.video.videoWidth,s.videoStats.renderRemoteHeight=a.player.video.videoHeight):(s.videoStats.renderRemoteWidth=a.videoWidth||s.videoStats.googFrameWidthReceived,s.videoStats.renderRemoteHeight=a.videoHeight||s.videoStats.googFrameHeightReceived)}}))}),t.remoteStats=i;var o={};if(Object.keys(t.gatewayClient.localStreams).forEach(function(e){var i=t.gatewayClient.localStreams[e],a=t.localStats[e],r={id:e,updatedAt:n};o[e]=r,a?(r.videoTotalPlayDuration=a.videoTotalPlayDuration+1,r.videoTotalFreezeTime=a.videoTotalFreezeTime,r.isVideoFreeze=!1):(r.videoTotalPlayDuration=1,r.videoTotalFreezeTime=0),i&&(i.isPlaying()&&(r.audioDisabled=i.userMuteAudio?"1":"0",r.videoDisabled=i.userMuteVideo?"1":"0"),i.video&&i.attributes.maxVideoBW?r.videoTargetSendBitrate=i.attributes.maxVideoBW:i.video&&i.screenAttributes&&(r.videoTargetSendBitrate=i.screenAttributes.maxVideoBW),i.pc&&"established"==i.pc.state&&i.pc.getStats(function(e){if(r.pcStats=e.reverse(),r.audioStats=e.find(function(e){return"audio"==e.mediaType&&(e.id.indexOf("_send")>-1||e.id.toLowerCase().indexOf("outbound")>-1)}),r.videoStats=e.find(function(e){return"video"==e.mediaType&&(e.id.indexOf("_send")>-1||e.id.toLowerCase().indexOf("outbound")>-1)}),r.audioStats&&a&&a.audioStats){var n=parseInt(r.audioStats.bytesSent)-parseInt(a.audioStats.bytesSent);if(r.audioStats.audioSendBytesDelta=n,t.session.sendBytes+=n,isFinite(n)&&r.audioStats.timestamp){var o=r.audioStats.timestamp.getTime()-a.audioStats.timestamp.getTime();r.audioSendBitrate=Math.floor(8*n/o)}}if(r.videoStats&&a&&a.videoStats){var s=parseInt(r.videoStats.bytesSent)-parseInt(a.videoStats.bytesSent);r.videoStats.videoSendBytesDelta=s,t.session.sendBytes+=s,isFinite(s)&&r.videoStats.timestamp&&(o=r.videoStats.timestamp.getTime()-a.videoStats.timestamp.getTime(),r.videoSendBitrate=Math.floor(8*s/o)),t.isLocalVideoFreeze(r.videoStats,a.videoStats)&&(r.videoTotalFreezeTime++,r.isVideoFreeze=!0),r.videoStats.videoTotalFreezeTime=r.videoTotalFreezeTime,r.videoStats.videoTotalPlayDuration=r.videoTotalPlayDuration,r.videoStats.videoFreezeRate=Math.ceil(100*r.videoTotalFreezeTime/r.videoTotalPlayDuration),r.videoStats.renderLocalWidth=i.videoWidth||r.videoStats.googFrameWidthSent,r.videoStats.renderLocalHeight=i.videoHeight||r.videoStats.googFrameHeightSent}}))}),t.localStats=o,t.session.HTTPSendBytesDelta=Object(ve.b)()-t.session.HTTPSendBytes,t.session.HTTPSendBytes=Object(ve.b)(),t.session.HTTPRecvBytesDelta=Object(ve.a)()-t.session.HTTPRecvBytes,t.session.HTTPRecvBytes=Object(ve.a)(),t.gatewayClient.socket&&t.gatewayClient.socket.state===t.gatewayClient.CONNECTED){var a=t.gatewayClient.socket;t.session.WSSendBytesDelta=a.getSendBytes()-t.session.WSSendBytes,t.session.WSSendBytes=a.getSendBytes(),t.session.WSRecvBytesDelta=a.getRecvBytes()-t.session.WSRecvBytes,t.session.WSRecvBytes=a.getRecvBytes()}},1e3),t.gatewayClient.on("join",function(){t.session={sendBytes:0,recvBytes:0,WSSendBytes:0,WSSendBytesDelta:0,WSRecvBytes:0,WSRecvBytesDelta:0,HTTPSendBytes:0,HTTPSendBytesDelta:0,HTTPRecvBytes:0,HTTPRecvBytesDelta:0}}),t}(t.gatewayClient),t.configDistributManager=function(e){var t={};return t.client=e,t.client.on("config-distribute",function(n){var o=n.joinInfo,r=n.config;if(r){ae(r.uploadLog)||(Object(i.setParameter)("UPLOAD_LOG",r.uploadLog),a.b.reportApiInvoke(o.sid,{name:"_configDistribute",options:{feature:"uploadLog",value:r.uploadLog}})()),ae(r.dualStream)||(e.isDualStream=r.dualStream,a.b.reportApiInvoke(o.sid,{name:"_configDistribute",options:{feature:"dualStream",value:r.dualStream}})()),ae(r.streamFallbackOption)||t.client.on("stream-subscribed",function(e){var n=e.stream;n?(t.client.gatewayClient.setStreamFallbackOption(n,r.streamFallbackOption),a.b.reportApiInvoke(o.sid,{name:"_configDistribute",options:{feature:"streamFallbackOption",value:r.streamFallbackOption,streamId:n.getId()}})()):a.b.reportApiInvoke(o.sid,{name:"_configDistribute",options:{feature:"streamFallbackOption",value:r.streamFallbackOption,streamId:n.getId(),err:"invalid stream"}})()});try{Object.keys(r).map(function(e){return Object(i.setParameter)(e,r[e])})}catch(e){}}}),t}(t),ae(e.turnServer)||t.setTurnServer(e.turnServer),ae(e.proxyServer)||t.setProxyServer(e.proxyServer),"live"===t.mode&&(t.gatewayClient.role="audience"),"rtc"===t.mode&&(t.gatewayClient.role="host"),t.on("onMultiIP",function(e){t.gatewayClient.closeGateway(),t.gatewayClient.socket=void 0,t.gatewayClient.hasChangeBGPAddress=!0,t.joinInfo.multiIP=e.arg.option,t.gatewayClient.state=Pe.CONNECTING,Ce(t.joinInfo,function(e){o.default.info("[".concat(t.clientId,"] Joining channel: ").concat(t.channel)),t.joinInfo.cid=e.cid,t.joinInfo.uid=e.uid,t.joinInfo.uni_lbs_ip=e.uni_lbs_ip,t.joinInfo.gatewayAddr=e.gateway_addr,t.onSuccess?t.gatewayClient.join(t.joinInfo,t.key,function(e){o.default.info("[".concat(t.clientId,"] Join channel ").concat(t.channel," success"));var n=t.onSuccess;t.onSuccess=null,t.onFailure=null,n(e)},t.onFailure):(t.gatewayClient.joinInfo=v()({},t.joinInfo),t.gatewayClient.rejoin())},t.onFailure)}),t.on("rejoin-start",function(){t._renewSession(),a.b.sessionInit(e.sessionId,{lts:(new Date).getTime(),extend:{rejoin:!0},cname:t.channel,appid:e.appId,mode:e.mode,succ:!0})}),t.on("recover",function(){t._renewSession(),a.b.sessionInit(e.sessionId,{lts:(new Date).getTime(),extend:{recover:!0},cname:t.channel,appid:e.appId,mode:e.mode,succ:!0})}),t.on("rejoin",function(){var e=2===t.highStreamState?2:0;if(t.onSuccess){var n=t.onSuccess;t.onSuccess=null,t.onFailure=null,n()}t.highStream&&0===e&&(o.default.info("[".concat(t.clientId,"] publish after rejoin")),t.highStreamState=2,t.lowStreamState=2,t.publish(t.highStream,function(e){e&&o.default.info("[".concat(t.clientId,"] "),e)}))}),t.on("streamPublished",function(e){t.hasPublished||(t.hasPublished=!0,t.gatewayClient.dispatchEvent(d({type:"stream-published",stream:e.stream})))}),t.on("pubP2PLost",function(e){o.default.debug("[".concat(t.clientId,"] Start reconnect local peerConnection: ").concat(t.highStream.getId())),t.gatewayClient.dispatchEvent({type:"stream-reconnect-start",uid:t.highStream.getId()}),1===t.highStreamState&&(t.highStreamState=0,t.lowStreamState=0),t._unpublish(t.highStream,function(){t._publish(t.highStream,function(){o.default.debug("[".concat(t.clientId,"] Reconnect local peerConnection success: ").concat(t.highStream.getId())),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:t.highStream.getId(),success:!0,reason:""})},function(e){o.default.debug("[".concat(t.clientId,"] Reconnect local peerConnection failed: ").concat(e)),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:t.highStream.getId(),success:!1,reason:e})})},function(e){o.default.debug("[".concat(t.clientId,"] Reconnect local peerConnection failed: ").concat(e)),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:t.highStream.getId(),success:!1,reason:e})})}),t.on("subP2PLost",function(e){o.default.debug("[".concat(t.clientId,"] Start reconnect remote peerConnection: ").concat(e.stream.getId())),t.gatewayClient.dispatchEvent({type:"stream-reconnect-start",uid:e.stream.getId()}),t.gatewayClient.unsubscribe(e.stream,function(){t.gatewayClient.subscribe(e.stream,function(){o.default.debug("[".concat(t.clientId,"] Reconnect remote peerConnection success: ").concat(e.stream.getId())),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:e.stream.getId(),success:!1,reason:""})},function(n){o.default.debug("[".concat(t.clientId,"] Reconnect remote peerConnection failed: "),n),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:e.stream.getId(),success:!1,reason:n})})},function(n){o.default.debug("[".concat(t.clientId,"] \" + 'Reconnect remote peerConnection failed: "),n),t.gatewayClient.dispatchEvent({type:"stream-reconnect-end",uid:e.stream.getId(),success:!1,reason:n})})}),Be.on("networkTypeChanged",function(e){t.gatewayClient&&t.gatewayClient.dispatchEvent(e);var n=v()({},e,{type:"network-type-changed"});t.gatewayClient.dispatchEvent(n)}),G.on("recordingDeviceChanged",function(e){t.gatewayClient&&t.gatewayClient.dispatchEvent(e);var n=v()({},e,{type:"recording-device-changed"});t.gatewayClient.dispatchEvent(n)}),G.on("playoutDeviceChanged",function(e){t.gatewayClient&&t.gatewayClient.dispatchEvent(e);var n=v()({},e,{type:"playout-device-changed"});t.gatewayClient.dispatchEvent(n)}),G.on("cameraChanged",function(e){t.gatewayClient&&t.gatewayClient.dispatchEvent(e);var n=v()({},e,{type:"camera-changed"});t.gatewayClient.dispatchEvent(n)}),t.gatewayClient.on("streamTypeChange",function(n){var i=v()({},n,{type:"stream-type-changed"});t.gatewayClient.dispatchEvent(i),a.b.reportApiInvoke(e.sessionId,{name:"streamTypeChange"})(null,JSON.stringify(n))}),t},We={width:640,height:360,videoBitrate:400,videoFramerate:15,lowLatency:!1,audioSampleRate:48e3,audioBitrate:48,audioChannels:1,videoGop:30,videoCodecProfile:100,userCount:0,userConfigExtraInfo:{},backgroundColor:0,transcodingUsers:[]},He={width:0,height:0,videoGop:30,videoFramerate:15,videoBitrate:400,audioSampleRate:44100,audioBitrate:48,audioChannels:1},Ge=G.getDevices,Je=x,ze=JSON.parse(JSON.stringify(i.SUPPORT_RESOLUTION_LIST));t.default={TranscodingUser:{uid:0,x:0,y:0,width:0,height:0,zOrder:0,alpha:1},LiveTranscoding:We,createClient:function(e){var t=a.b.reportApiInvoke(null,{name:"createClient",options:arguments,tag:"tracer"});(e=v()({},e||{})).codec||(e.codec=function(e){switch(e){case"h264_interop":return"h264";default:return"vp8"}}(e.mode));var n=function(e){return-1===pe.indexOf(e.mode)?E.INVALID_CLIENT_MODE:-1===fe.indexOf(e.codec)?E.INVALID_CLIENT_CODEC:"h264_interop"==e.mode&&"h264"!==e.codec&&E.CLIENT_MODE_CODEC_MISMATCH}(e);if(n)throw o.default.error("Invalid parameter setting MODE: ".concat(e.mode," CODEC: ").concat(e.codec," ERROR ").concat(n)),t(n),new Error(n);return o.default.info("Creating client, MODE: ".concat(e.mode," CODEC: ").concat(e.codec)),function(e){switch(e.mode){case"interop":case"h264_interop":e.mode="live";break;case"web-only":e.mode="rtc"}}(e),t(null,e),je(e)},createStream:function(e){var t=a.b.reportApiInvoke(null,{name:"createStream",options:arguments,tag:"tracer"});Y(e,"StreamSpec");var n=e.streamID,i=e.audio,r=e.video,s=e.screen,d=(e.audioSource,e.videoSource,e.cameraId),c=e.microphoneId,u=e.mirror,l=e.extensionId,p=e.mediaSource,f=e.audioProcessing;if(!ae(n)&&!Object(W.c)(n)&&!$(n,1,255))throw new Error("[String streamID] Length of the string: [1,255]. ASCII characters only. [Number streamID] The value range is Uint32");if(X(i,"audio"),X(r,"video"),ae(s)||X(s,"screen"),ae(d)||q(d,"cameraId",0,255,!1),ae(c)||q(c,"microphoneId",0,255,!1),ae(l)||q(l,"extensionId"),ae(p)||K(p,"mediaSource",["screen","application","window"]),ae(u)||X(u,"mirror"),!ae(f)){var m=f.AGC,g=f.AEC,v=f.ANS;ae(m)||X(m,"AGC"),ae(g)||X(g,"AEC"),ae(v)||X(v,"ANS")}o.default.debug("Create stream");var S=ue(e);return t(),S},Logger:o.default,getDevices:Ge,getScreenSources:Je,getParameter:i.getParameter,setParameter:i.setParameter,checkSystemRequirements:function(){var e=a.b.reportApiInvoke(null,{name:"checkSystemRequirements",options:arguments,tag:"tracer"}),t=window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,n=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,i=window.WebSocket,r=!!t&&!!n&&!!i,s=!1;o.default.debug(p.getBrowserInfo(),"isAPISupport:"+r),p.isChrome()&&p.getBrowserVersion()>=58&&"iOS"!==p.getBrowserOS()&&(s=!0),p.isFireFox()&&p.getBrowserVersion()>=56&&(s=!0),p.isOpera()&&p.getBrowserVersion()>=45&&(s=!0),p.isSafari()&&p.getBrowserVersion()>=11&&(s=!0),p.isEdge()&&(s=!0),(p.isWeChatBrowser()||p.isQQBrowser())&&"iOS"!==p.getBrowserOS()&&(s=!0),p.isSupportedPC()||p.isSupportedMobile()||(s=!1);var d=r&&s;return e(null,d),d},getSupportedCodec:le.getSupportedCodec,VERSION:i.VERSION,BUILD:i.BUILD,PROFILE_TABLE:ze,AUDIO_SAMPLE_RATE_32000:32e3,AUDIO_SAMPLE_RATE_44100:44100,AUDIO_SAMPLE_RATE_48000:48e3,VIDEO_CODEC_PROFILE_BASELINE:66,VIDEO_CODEC_PROFILE_MAIN:77,VIDEO_CODEC_PROFILE_HIGH:100,REMOTE_VIDEO_STREAM_HIGH:0,REMOTE_VIDEO_STREAM_LOW:1,REMOTE_VIDEO_STREAM_MEDIUM:2}}]).default});