/**
 * AgoraWebSDK_N-v4.7.3-0-g0eb931c7 Copyright AgoraInc.
 */

/*
 @license
 UAParser.js v0.7.28
 Lightweight JavaScript-based User-Agent string parser
 https://github.com/faisalman/ua-parser-js

 Copyright ? 2012-2021 Faisal Salman <f@faisalman.com>
 Licensed under MIT License
 *****************************************************************************
 Copyright (c) Microsoft Corporation. All rights reserved.
 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
 this file except in compliance with the License. You may obtain a copy of the
 License at http://www.apache.org/licenses/LICENSE-2.0

 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
 MERCHANTABLITY OR NON-INFRINGEMENT.

 See the Apache Version 2.0 License for specific language governing permissions
 and limitations under the License.
*****************************************************************************/
'use strict';!function(ub,hc){"object"==typeof exports&&"undefined"!=typeof module?module.exports=hc():"function"==typeof define&&define.amd?define(hc):(ub="undefined"!=typeof globalThis?globalThis:ub||self).AgoraRTC=hc()}(this,function(){function ub(d,g,a){return d(a={path:g,exports:{},require:function(a,c){throw Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");}},a.exports),a.exports}function hc(d,g,a){return(d=d.match(g))&&d.length>=a&&wa(d[a],10)}function Zc(d,
g,a){if(d.RTCPeerConnection){d=d.RTCPeerConnection.prototype;var b=d.addEventListener;d.addEventListener=function(c,d){if(c!==g)return b.apply(this,arguments);let e=b=>{(b=a(b))&&d(b)};return this._eventMap=this._eventMap||{},this._eventMap[d]=e,b.apply(this,[c,e])};var c=d.removeEventListener;d.removeEventListener=function(a,b){if(a!==g||!this._eventMap||!this._eventMap[b])return c.apply(this,arguments);let e=this._eventMap[b];return delete this._eventMap[b],c.apply(this,[a,e])};Q(d,"on"+g,{get(){return this["_on"+
g]},set(a){this["_on"+g]&&(this.removeEventListener(g,this["_on"+g]),delete this["_on"+g]);a&&this.addEventListener(g,this["_on"+g]=a)},enumerable:!0,configurable:!0})}}function Vn(d){return"boolean"!=typeof d?Error("Argument type: "+typeof d+". Please use a boolean."):($h=d,d?"adapter.js logging disabled":"adapter.js logging enabled")}function Wn(d){return"boolean"!=typeof d?Error("Argument type: "+typeof d+". Please use a boolean."):(ai=!d,"adapter.js deprecation warnings "+(d?"disabled":"enabled"))}
function Pb(){"object"!=typeof window||$h||"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}function Ae(d,g){ai&&console.warn(d+" is deprecated, please use "+g+" instead.")}function ic(d){let {navigator:g}=d,a={browser:null,version:null};if(void 0===d||!d.navigator)return a.browser="Not a browser.",a;if(g.mozGetUserMedia)a.browser="firefox",a.version=hc(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||!1===d.isSecureContext&&d.webkitRTCPeerConnection&&
!d.RTCIceGatherer)a.browser="chrome",a.version=hc(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))a.browser="edge",a.version=hc(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!d.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return a.browser="Not a supported browser.",a;a.browser="safari";a.version=hc(g.userAgent,/AppleWebKit\/(\d+)\./,1);a.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype}return a}
function bi(d){var g;return"[object Object]"===Object.prototype.toString.call(d)?Be(g=W(d)).call(g,function(a,b){var c="[object Object]"===Object.prototype.toString.call(d[b]);let e=c?bi(d[b]):d[b];c=c&&!W(e).length;return void 0===e||c?a:Ya(a,{[b]:e})},{}):d}function ci(d,g,a){let b=a?"outbound-rtp":"inbound-rtp",c=new ba;if(null===g)return c;let e=[];return t(d).call(d,a=>{"track"===a.type&&a.trackIdentifier===g.id&&e.push(a)}),t(e).call(e,a=>{t(d).call(d,e=>{e.type===b&&e.trackId===a.id&&function X(a,
b,c){var e;b&&!c.has(b.id)&&(c.set(b.id,b),t(e=W(b)).call(e,e=>{if(di(e).call(e,"Id"))X(a,a.get(b[e]),c);else if(di(e).call(e,"Ids")){var d;t(d=b[e]).call(d,b=>{X(a,a.get(b),c)})}}))}(d,e,c)})}),c}function ei(d){let g=d&&d.navigator;if(g.mediaDevices){var a=ic(d),b=function(a){var b;if("object"!=typeof a||a.mandatory||a.optional)return a;const c={};var e;(t(b=W(a)).call(b,b=>{if("require"!==b&&"advanced"!==b&&"mediaSource"!==b){var e="object"==typeof a[b]?a[b]:{ideal:a[b]};void 0!==e.exact&&"number"==
typeof e.exact&&(e.min=e.max=e.exact);var d=function(a,b){return a?a+b.charAt(0).toUpperCase()+Ma(b).call(b,1):"deviceId"===b?"sourceId":b};if(void 0!==e.ideal){c.optional=c.optional||[];let a={};"number"==typeof e.ideal?(a[d("min",b)]=e.ideal,c.optional.push(a),a={},a[d("max",b)]=e.ideal,c.optional.push(a)):(a[d("",b)]=e.ideal,c.optional.push(a))}var f;void 0!==e.exact&&"number"!=typeof e.exact?(c.mandatory=c.mandatory||{},c.mandatory[d("",b)]=e.exact):t(f=["min","max"]).call(f,a=>{void 0!==e[a]&&
(c.mandatory=c.mandatory||{},c.mandatory[d(a,b)]=e[a])})}}),a.advanced)&&(c.optional=m(e=c.optional||[]).call(e,a.advanced));return c},c=function(c,e){if(61<=a.version)return e(c);if((c=JSON.parse(A(c)))&&"object"==typeof c.audio){var d=function(a,b,c){b in a&&!(c in a)&&(a[c]=a[b],delete a[b])};d((c=JSON.parse(A(c))).audio,"autoGainControl","googAutoGainControl");d(c.audio,"noiseSuppression","googNoiseSuppression");c.audio=b(c.audio)}if(c&&"object"==typeof c.video){let f=c.video.facingMode;f=f&&
("object"==typeof f?f:{ideal:f});d=66>a.version;if(!(!f||"user"!==f.exact&&"environment"!==f.exact&&"user"!==f.ideal&&"environment"!==f.ideal||g.mediaDevices.getSupportedConstraints&&g.mediaDevices.getSupportedConstraints().facingMode&&!d)){let a;if(delete c.video.facingMode,"environment"===f.exact||"environment"===f.ideal?a=["back","rear"]:"user"!==f.exact&&"user"!==f.ideal||(a=["front"]),a)return g.mediaDevices.enumerateDevices().then(d=>{d=I(d).call(d,a=>"videoinput"===a.kind);let h=U(d).call(d,
b=>fi(a).call(a,a=>{var c;return Z(c=b.label.toLowerCase()).call(c,a)}));return!h&&d.length&&Z(a).call(a,"back")&&(h=d[d.length-1]),h&&(c.video.deviceId=f.exact?{exact:h.deviceId}:{ideal:h.deviceId}),c.video=b(c.video),gi("chrome: "+A(c)),e(c)})}c.video=b(c.video)}return gi("chrome: "+A(c)),e(c)},e=function(b){return 64<=a.version?b:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",
TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[b.name]||b.name,message:b.message,constraint:b.constraint||b.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};d=function(a,b,d){c(a,a=>{g.webkitGetUserMedia(a,b,a=>{d&&d(e(a))})})};if(g.getUserMedia=xa(d).call(d,g),g.mediaDevices.getUserMedia){var f;
let a=xa(f=g.mediaDevices.getUserMedia).call(f,g.mediaDevices);g.mediaDevices.getUserMedia=function(b){return c(b,b=>a(b).then(a=>{var c;if(b.audio&&!a.getAudioTracks().length||b.video&&!a.getVideoTracks().length)throw t(c=a.getTracks()).call(c,a=>{a.stop()}),new DOMException("","NotFoundError");return a},a=>y.reject(e(a))))}}}}function hi(d){d.MediaStream=d.MediaStream||d.webkitMediaStream}function ii(d){if("object"!=typeof d||!d.RTCPeerConnection||"ontrack"in d.RTCPeerConnection.prototype)Zc(d,
"track",d=>(d.transceiver||Q(d,"transceiver",{value:{receiver:d.receiver}}),d));else{Q(d.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(a){this._ontrack&&this.removeEventListener("track",this._ontrack);this.addEventListener("track",this._ontrack=a)},enumerable:!0,configurable:!0});let g=d.RTCPeerConnection.prototype.setRemoteDescription;d.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=a=>{var b;a.stream.addEventListener("addtrack",
b=>{let c;var f;d.RTCPeerConnection.prototype.getReceivers?c=U(f=this.getReceivers()).call(f,a=>a.track&&a.track.id===b.track.id):c={track:b.track};f=new Event("track");f.track=b.track;f.receiver=c;f.transceiver={receiver:c};f.streams=[a.stream];this.dispatchEvent(f)});t(b=a.stream.getTracks()).call(b,b=>{let c;var f;d.RTCPeerConnection.prototype.getReceivers?c=U(f=this.getReceivers()).call(f,a=>a.track&&a.track.id===b.id):c={track:b};f=new Event("track");f.track=b;f.receiver=c;f.transceiver={receiver:c};
f.streams=[a.stream];this.dispatchEvent(f)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function ji(d){if("object"==typeof d&&d.RTCPeerConnection&&!("getSenders"in d.RTCPeerConnection.prototype)&&"createDTMFSender"in d.RTCPeerConnection.prototype){let g=function(a,b){return{track:b,get dtmf(){return void 0===this._dtmf&&("audio"===b.kind?this._dtmf=a.createDTMFSender(b):this._dtmf=null),this._dtmf},_pc:a}};if(!d.RTCPeerConnection.prototype.getSenders){d.RTCPeerConnection.prototype.getSenders=
function(){var a;return this._senders=this._senders||[],Ma(a=this._senders).call(a)};let a=d.RTCPeerConnection.prototype.addTrack;d.RTCPeerConnection.prototype.addTrack=function(b,c){let e=a.apply(this,arguments);return e||(e=g(this,b),this._senders.push(e)),e};let b=d.RTCPeerConnection.prototype.removeTrack;d.RTCPeerConnection.prototype.removeTrack=function(a){var c;b.apply(this,arguments);let e=J(c=this._senders).call(c,a);var d;-1!==e&&Ra(d=this._senders).call(d,e,1)}}let a=d.RTCPeerConnection.prototype.addStream;
d.RTCPeerConnection.prototype.addStream=function(b){var c;this._senders=this._senders||[];a.apply(this,[b]);t(c=b.getTracks()).call(c,a=>{this._senders.push(g(this,a))})};let b=d.RTCPeerConnection.prototype.removeStream;d.RTCPeerConnection.prototype.removeStream=function(a){var c;this._senders=this._senders||[];b.apply(this,[a]);t(c=a.getTracks()).call(c,a=>{var b;let c=U(b=this._senders).call(b,b=>b.track===a);var e,d;c&&Ra(e=this._senders).call(e,J(d=this._senders).call(d,c),1)})}}else if("object"==
typeof d&&d.RTCPeerConnection&&"getSenders"in d.RTCPeerConnection.prototype&&"createDTMFSender"in d.RTCPeerConnection.prototype&&d.RTCRtpSender&&!("dtmf"in d.RTCRtpSender.prototype)){let g=d.RTCPeerConnection.prototype.getSenders;d.RTCPeerConnection.prototype.getSenders=function(){let a=g.apply(this,[]);return t(a).call(a,a=>a._pc=this),a};Q(d.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),
this._dtmf}})}}function ki(d){if(d.RTCPeerConnection){var g=d.RTCPeerConnection.prototype.getStats;d.RTCPeerConnection.prototype.getStats=function(){let [a,b,c]=arguments;if(0<arguments.length&&"function"==typeof a)return g.apply(this,arguments);if(0===g.length&&(0===arguments.length||"function"!=typeof a))return g.apply(this,[]);let e=function(a){const b={};a=a.result();return t(a).call(a,a=>{var c;const e={id:a.id,timestamp:a.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[a.type]||
a.type};t(c=a.names()).call(c,b=>{e[b]=a.stat(b)});b[e.id]=e}),b},d=function(a){var b;return new ba(z(b=W(a)).call(b,b=>[b,a[b]]))};return 2<=arguments.length?g.apply(this,[function(a){b(d(e(a)))},a]):(new y((a,b)=>{g.apply(this,[function(b){a(d(e(b)))},b])})).then(b,c)}}}function li(d){if("object"==typeof d&&d.RTCPeerConnection&&d.RTCRtpSender&&d.RTCRtpReceiver){if(!("getStats"in d.RTCRtpSender.prototype)){let a=d.RTCPeerConnection.prototype.getSenders;a&&(d.RTCPeerConnection.prototype.getSenders=
function(){let b=a.apply(this,[]);return t(b).call(b,a=>a._pc=this),b});let b=d.RTCPeerConnection.prototype.addTrack;b&&(d.RTCPeerConnection.prototype.addTrack=function(){let a=b.apply(this,arguments);return a._pc=this,a});d.RTCRtpSender.prototype.getStats=function(){let a=this;return this._pc.getStats().then(b=>ci(b,a.track,!0))}}if(!("getStats"in d.RTCRtpReceiver.prototype)){let a=d.RTCPeerConnection.prototype.getReceivers;a&&(d.RTCPeerConnection.prototype.getReceivers=function(){let b=a.apply(this,
[]);return t(b).call(b,a=>a._pc=this),b});Zc(d,"track",a=>(a.receiver._pc=a.srcElement,a));d.RTCRtpReceiver.prototype.getStats=function(){let a=this;return this._pc.getStats().then(b=>ci(b,a.track,!1))}}if("getStats"in d.RTCRtpSender.prototype&&"getStats"in d.RTCRtpReceiver.prototype){var g=d.RTCPeerConnection.prototype.getStats;d.RTCPeerConnection.prototype.getStats=function(){if(0<arguments.length&&arguments[0]instanceof d.MediaStreamTrack){var a,b;let c=arguments[0],e,d,h;return t(a=this.getSenders()).call(a,
a=>{a.track===c&&(e?h=!0:e=a)}),t(b=this.getReceivers()).call(b,a=>(a.track===c&&(d?h=!0:d=a),a.track===c)),h||e&&d?y.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():d?d.getStats():y.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return g.apply(this,arguments)}}}}function mi(d){d.RTCPeerConnection.prototype.getLocalStreams=function(){var a;return this._shimmedLocalStreams=this._shimmedLocalStreams||
{},z(a=W(this._shimmedLocalStreams)).call(a,a=>this._shimmedLocalStreams[a][0])};let g=d.RTCPeerConnection.prototype.addTrack;d.RTCPeerConnection.prototype.addTrack=function(a,b){var c;if(!b)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let e=g.apply(this,arguments);return this._shimmedLocalStreams[b.id]?-1===J(c=this._shimmedLocalStreams[b.id]).call(c,e)&&this._shimmedLocalStreams[b.id].push(e):this._shimmedLocalStreams[b.id]=[b,e],e};let a=d.RTCPeerConnection.prototype.addStream;
d.RTCPeerConnection.prototype.addStream=function(b){var c,e,d;this._shimmedLocalStreams=this._shimmedLocalStreams||{};t(c=b.getTracks()).call(c,a=>{var b;if(U(b=this.getSenders()).call(b,b=>b.track===a))throw new DOMException("Track already exists.","InvalidAccessError");});let g=this.getSenders();a.apply(this,arguments);c=I(e=this.getSenders()).call(e,a=>-1===J(g).call(g,a));this._shimmedLocalStreams[b.id]=m(d=[b]).call(d,c)};let b=d.RTCPeerConnection.prototype.removeStream;d.RTCPeerConnection.prototype.removeStream=
function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],b.apply(this,arguments)};let c=d.RTCPeerConnection.prototype.removeTrack;d.RTCPeerConnection.prototype.removeTrack=function(a){var b;(this._shimmedLocalStreams=this._shimmedLocalStreams||{},a)&&t(b=W(this._shimmedLocalStreams)).call(b,b=>{var c;let e=J(c=this._shimmedLocalStreams[b]).call(c,a);var d;-1!==e&&Ra(d=this._shimmedLocalStreams[b]).call(d,e,1);1===this._shimmedLocalStreams[b].length&&
delete this._shimmedLocalStreams[b]});return c.apply(this,arguments)}}function ni(d){function g(a,b){var c;let e=b.sdp;return t(c=W(a._reverseStreams||[])).call(c,b=>{b=a._reverseStreams[b];e=e.replace(new RegExp(a._streams[b.id].id,"g"),b.id)}),new RTCSessionDescription({type:b.type,sdp:e})}function a(a,b){var c;let e=b.sdp;return t(c=W(a._reverseStreams||[])).call(c,b=>{b=a._reverseStreams[b];e=e.replace(new RegExp(b.id,"g"),a._streams[b.id].id)}),new RTCSessionDescription({type:b.type,sdp:e})}
var b;if(d.RTCPeerConnection){var c=ic(d);if(d.RTCPeerConnection.prototype.addTrack&&65<=c.version)return mi(d);var e=d.RTCPeerConnection.prototype.getLocalStreams;d.RTCPeerConnection.prototype.getLocalStreams=function(){let a=e.apply(this);return this._reverseStreams=this._reverseStreams||{},z(a).call(a,a=>this._reverseStreams[a.id])};var f=d.RTCPeerConnection.prototype.addStream;d.RTCPeerConnection.prototype.addStream=function(a){var b;(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||
{},t(b=a.getTracks()).call(b,a=>{var b;if(U(b=this.getSenders()).call(b,b=>b.track===a))throw new DOMException("Track already exists.","InvalidAccessError");}),this._reverseStreams[a.id])||(b=new d.MediaStream(a.getTracks()),this._streams[a.id]=b,this._reverseStreams[b.id]=a,a=b);f.apply(this,[a])};var h=d.RTCPeerConnection.prototype.removeStream;d.RTCPeerConnection.prototype.removeStream=function(a){this._streams=this._streams||{};this._reverseStreams=this._reverseStreams||{};h.apply(this,[this._streams[a.id]||
a]);delete this._reverseStreams[this._streams[a.id]?this._streams[a.id].id:a.id];delete this._streams[a.id]};d.RTCPeerConnection.prototype.addTrack=function(a,b){var c,e,f;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let h=Ma([]).call(arguments,1);if(1!==h.length||!U(c=h[0].getTracks()).call(c,b=>b===a))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.",
"NotSupportedError");if(U(e=this.getSenders()).call(e,b=>b.track===a))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{};this._reverseStreams=this._reverseStreams||{};(c=this._streams[b.id])?(c.addTrack(a),y.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))})):(c=new d.MediaStream([a]),this._streams[b.id]=c,this._reverseStreams[c.id]=b,this.addStream(c));return U(f=this.getSenders()).call(f,b=>b.track===a)};t(b=["createOffer",
"createAnswer"]).call(b,function(a){let b=d.RTCPeerConnection.prototype[a];d.RTCPeerConnection.prototype[a]={[a](){const a=arguments;return arguments.length&&"function"==typeof arguments[0]?b.apply(this,[b=>{b=g(this,b);a[0].apply(null,[b])},b=>{a[1]&&a[1].apply(null,b)},arguments[2]]):b.apply(this,arguments).then(a=>g(this,a))}}[a]});var l=d.RTCPeerConnection.prototype.setLocalDescription;d.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=
a(this,arguments[0]),l.apply(this,arguments)):l.apply(this,arguments)};var r=ca(d.RTCPeerConnection.prototype,"localDescription");Q(d.RTCPeerConnection.prototype,"localDescription",{get(){let a=r.get.apply(this);return""===a.type?a:g(this,a)}});d.RTCPeerConnection.prototype.removeTrack=function(a){var b;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!a._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.",
"TypeError");if(a._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let c;this._streams=this._streams||{};t(b=W(this._streams)).call(b,b=>{var e;U(e=this._streams[b].getTracks()).call(e,b=>a.track===b)&&(c=this._streams[b])});c&&(1===c.getTracks().length?this.removeStream(this._reverseStreams[c.id]):c.removeTrack(a.track),this.dispatchEvent(new Event("negotiationneeded")))}}}function Mf(d){let g=ic(d);if(!d.RTCPeerConnection&&d.webkitRTCPeerConnection&&
(d.RTCPeerConnection=d.webkitRTCPeerConnection),d.RTCPeerConnection){var a;53>g.version&&t(a=["setLocalDescription","setRemoteDescription","addIceCandidate"]).call(a,function(a){let b=d.RTCPeerConnection.prototype[a];d.RTCPeerConnection.prototype[a]={[a](){return arguments[0]=new ("addIceCandidate"===a?d.RTCIceCandidate:d.RTCSessionDescription)(arguments[0]),b.apply(this,arguments)}}[a]});var b=d.RTCPeerConnection.prototype.addIceCandidate;d.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?
78>g.version&&arguments[0]&&""===arguments[0].candidate?y.resolve():b.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),y.resolve())}}}function oi(d){Zc(d,"negotiationneeded",d=>{if("stable"===d.target.signalingState)return d})}function pi(d,g,a,b,c){g=H.writeRtpDescription(d.kind,g);if(g+=H.writeIceParameters(d.iceGatherer.getLocalParameters()),g+=H.writeDtlsParameters(d.dtlsTransport.getLocalParameters(),"offer"===a?"actpass":c||"active"),g+="a=mid:"+d.mid+"\r\n",d.rtpSender&&d.rtpReceiver?
g+="a=sendrecv\r\n":d.rtpSender?g+="a=sendonly\r\n":d.rtpReceiver?g+="a=recvonly\r\n":g+="a=inactive\r\n",d.rtpSender)a=d.rtpSender._initialTrackId||d.rtpSender.track.id,d.rtpSender._initialTrackId=a,b="msid:"+(b?b.id:"-")+" "+a+"\r\n",g=g+("a="+b)+("a=ssrc:"+d.sendEncodingParameters[0].ssrc+" "+b),d.sendEncodingParameters[0].rtx&&(g+="a=ssrc:"+d.sendEncodingParameters[0].rtx.ssrc+" "+b,g+="a=ssrc-group:FID "+d.sendEncodingParameters[0].ssrc+" "+d.sendEncodingParameters[0].rtx.ssrc+"\r\n");return g+=
"a=ssrc:"+d.sendEncodingParameters[0].ssrc+" cname:"+H.localCName+"\r\n",d.rtpSender&&d.sendEncodingParameters[0].rtx&&(g+="a=ssrc:"+d.sendEncodingParameters[0].rtx.ssrc+" cname:"+H.localCName+"\r\n"),g}function Ce(d,g){var a={codecs:[],headerExtensions:[],fecMechanisms:[]},b=function(a,b){a=parseInt(a,10);for(var c=0;c<b.length;c++)if(b[c].payloadType===a||b[c].preferredPayloadType===a)return b[c]},c=function(a,c,d,g){a=b(a.parameters.apt,d);c=b(c.parameters.apt,g);return a&&c&&a.name.toLowerCase()===
c.name.toLowerCase()};return d.codecs.forEach(function(b){for(var e=0;e<g.codecs.length;e++){var h=g.codecs[e];if(b.name.toLowerCase()===h.name.toLowerCase()&&b.clockRate===h.clockRate&&("rtx"!==b.name.toLowerCase()||!b.parameters||!h.parameters.apt||c(b,h,d.codecs,g.codecs))){(h=JSON.parse(JSON.stringify(h))).numChannels=Math.min(b.numChannels,h.numChannels);a.codecs.push(h);h.rtcpFeedback=h.rtcpFeedback.filter(function(a){for(var c=0;c<b.rtcpFeedback.length;c++)if(b.rtcpFeedback[c].type===a.type&&
b.rtcpFeedback[c].parameter===a.parameter)return!0;return!1});break}}}),d.headerExtensions.forEach(function(b){for(var c=0;c<g.headerExtensions.length;c++){var d=g.headerExtensions[c];if(b.uri===d.uri){a.headerExtensions.push(d);break}}}),a}function qi(d,g,a){return-1!=={offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[g][d].indexOf(a)}
function Nf(d,g){var a=d.getRemoteCandidates().find(function(a){return g.foundation===a.foundation&&g.ip===a.ip&&g.port===a.port&&g.priority===a.priority&&g.protocol===a.protocol&&g.type===a.type});return a||d.addRemoteCandidate(g),!a}function bb(d,g){g=Error(g);return g.name=d,g.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[d],g}function ri(d){var g;d=d&&d.navigator;let a=xa(g=d.mediaDevices.getUserMedia).call(g,d.mediaDevices);d.mediaDevices.getUserMedia=
function(b){return a(b).catch(a=>y.reject(function(a){return{name:{PermissionDeniedError:"NotAllowedError"}[a.name]||a.name,message:a.message,constraint:a.constraint,toString(){return this.name}}}(a)))}}function si(d){var g;"getDisplayMedia"in d.navigator&&d.navigator.mediaDevices&&(d.navigator.mediaDevices&&"getDisplayMedia"in d.navigator.mediaDevices||(d.navigator.mediaDevices.getDisplayMedia=xa(g=d.navigator.getDisplayMedia).call(g,d.navigator)))}function Of(d){let g=ic(d);if(d.RTCIceGatherer&&
(d.RTCIceCandidate||(d.RTCIceCandidate=function(a){return a}),d.RTCSessionDescription||(d.RTCSessionDescription=function(a){return a}),15025>g.version)){let a=ca(d.MediaStreamTrack.prototype,"enabled");Q(d.MediaStreamTrack.prototype,"enabled",{set(b){a.set.call(this,b);let c=new Event("enabled");c.enabled=b;this.dispatchEvent(c)}})}!d.RTCRtpSender||"dtmf"in d.RTCRtpSender.prototype||Q(d.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new d.RTCDtmfSender(this):
"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}});d.RTCDtmfSender&&!d.RTCDTMFSender&&(d.RTCDTMFSender=d.RTCDtmfSender);let a=Xn(d,g.version);d.RTCPeerConnection=function(b){return b&&b.iceServers&&(b.iceServers=function(a,b){let c=!1;return a=JSON.parse(A(a)),I(a).call(a,a=>{if(a&&(a.urls||a.url)){var b=a.urls||a.url;a.url&&!a.urls&&Ae("RTCIceServer.url","RTCIceServer.urls");let d="string"==typeof b;return d&&(b=[b]),b=I(b).call(b,a=>0===J(a).call(a,"stun:")?!1:(a=Hd(a).call(a,"turn")&&
!Hd(a).call(a,"turn:[")&&Z(a).call(a,"transport=udp"))&&!c?(c=!0,!0):a&&!c),delete a.url,a.urls=d?b[0]:b,!!b.length}})}(b.iceServers,g.version),Pb("ICE servers after filtering:",b.iceServers)),new a(b)};d.RTCPeerConnection.prototype=a.prototype}function ti(d){!d.RTCRtpSender||"replaceTrack"in d.RTCRtpSender.prototype||(d.RTCRtpSender.prototype.replaceTrack=d.RTCRtpSender.prototype.setTrack)}function ui(d){let g=ic(d),a=d&&d.navigator;d=d&&d.MediaStreamTrack;if(a.getUserMedia=function(b,d,f){Ae("navigator.getUserMedia",
"navigator.mediaDevices.getUserMedia");a.mediaDevices.getUserMedia(b).then(d,f)},!(55<g.version&&"autoGainControl"in a.mediaDevices.getSupportedConstraints())){var b;let c=function(a,b,c){b in a&&!(c in a)&&(a[c]=a[b],delete a[b])},e=xa(b=a.mediaDevices.getUserMedia).call(b,a.mediaDevices);if(a.mediaDevices.getUserMedia=function(a){return"object"==typeof a&&"object"==typeof a.audio&&(a=JSON.parse(A(a)),c(a.audio,"autoGainControl","mozAutoGainControl"),c(a.audio,"noiseSuppression","mozNoiseSuppression")),
e(a)},d&&d.prototype.getSettings){let a=d.prototype.getSettings;d.prototype.getSettings=function(){let b=a.apply(this,arguments);return c(b,"mozAutoGainControl","autoGainControl"),c(b,"mozNoiseSuppression","noiseSuppression"),b}}if(d&&d.prototype.applyConstraints){let a=d.prototype.applyConstraints;d.prototype.applyConstraints=function(b){return"audio"===this.kind&&"object"==typeof b&&(b=JSON.parse(A(b)),c(b,"autoGainControl","mozAutoGainControl"),c(b,"noiseSuppression","mozNoiseSuppression")),a.apply(this,
[b])}}}}function vi(d){"object"==typeof d&&d.RTCTrackEvent&&"receiver"in d.RTCTrackEvent.prototype&&!("transceiver"in d.RTCTrackEvent.prototype)&&Q(d.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Pf(d){let g=ic(d);if("object"==typeof d&&(d.RTCPeerConnection||d.mozRTCPeerConnection)){var a;(!d.RTCPeerConnection&&d.mozRTCPeerConnection&&(d.RTCPeerConnection=d.mozRTCPeerConnection),53>g.version)&&t(a=["setLocalDescription","setRemoteDescription","addIceCandidate"]).call(a,
function(a){let b=d.RTCPeerConnection.prototype[a];d.RTCPeerConnection.prototype[a]={[a](){return arguments[0]=new ("addIceCandidate"===a?d.RTCIceCandidate:d.RTCSessionDescription)(arguments[0]),b.apply(this,arguments)}}[a]});var b=d.RTCPeerConnection.prototype.addIceCandidate;d.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?68>g.version&&arguments[0]&&""===arguments[0].candidate?y.resolve():b.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),y.resolve())};
var c={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},e=d.RTCPeerConnection.prototype.getStats;d.RTCPeerConnection.prototype.getStats=function(){let [a,b,d]=arguments;return e.apply(this,[a||null]).then(a=>{if(53>g.version&&!b)try{t(a).call(a,a=>{a.type=c[a.type]||a.type})}catch(p){if("TypeError"!==p.name)throw p;t(a).call(a,(b,d)=>{a.set(d,Ya({},b,{type:c[b.type]||b.type}))})}return a}).then(b,
d)}}}function wi(d){if("object"==typeof d&&d.RTCPeerConnection&&d.RTCRtpSender&&!(d.RTCRtpSender&&"getStats"in d.RTCRtpSender.prototype)){var g=d.RTCPeerConnection.prototype.getSenders;g&&(d.RTCPeerConnection.prototype.getSenders=function(){let a=g.apply(this,[]);return t(a).call(a,a=>a._pc=this),a});var a=d.RTCPeerConnection.prototype.addTrack;a&&(d.RTCPeerConnection.prototype.addTrack=function(){let b=a.apply(this,arguments);return b._pc=this,b});d.RTCRtpSender.prototype.getStats=function(){return this.track?
this._pc.getStats(this.track):y.resolve(new ba)}}}function xi(d){if("object"==typeof d&&d.RTCPeerConnection&&d.RTCRtpSender&&!(d.RTCRtpSender&&"getStats"in d.RTCRtpReceiver.prototype)){var g=d.RTCPeerConnection.prototype.getReceivers;g&&(d.RTCPeerConnection.prototype.getReceivers=function(){let a=g.apply(this,[]);return t(a).call(a,a=>a._pc=this),a});Zc(d,"track",a=>(a.receiver._pc=a.srcElement,a));d.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function yi(d){!d.RTCPeerConnection||
"removeStream"in d.RTCPeerConnection.prototype||(d.RTCPeerConnection.prototype.removeStream=function(d){var a;Ae("removeStream","removeTrack");t(a=this.getSenders()).call(a,a=>{var b;a.track&&Z(b=d.getTracks()).call(b,a.track)&&this.removeTrack(a)})})}function zi(d){d.DataChannel&&!d.RTCDataChannel&&(d.RTCDataChannel=d.DataChannel)}function Ai(d){if("object"==typeof d&&d.RTCPeerConnection){if("getLocalStreams"in d.RTCPeerConnection.prototype||(d.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||
(this._localStreams=[]),this._localStreams}),!("addStream"in d.RTCPeerConnection.prototype)){let g=d.RTCPeerConnection.prototype.addTrack;d.RTCPeerConnection.prototype.addStream=function(a){var b,c,d;this._localStreams||(this._localStreams=[]);Z(b=this._localStreams).call(b,a)||this._localStreams.push(a);t(c=a.getAudioTracks()).call(c,b=>g.call(this,b,a));t(d=a.getVideoTracks()).call(d,b=>g.call(this,b,a))};d.RTCPeerConnection.prototype.addTrack=function(a,b){var c;b&&(this._localStreams?Z(c=this._localStreams).call(c,
b)||this._localStreams.push(b):this._localStreams=[b]);return g.call(this,a,b)}}"removeStream"in d.RTCPeerConnection.prototype||(d.RTCPeerConnection.prototype.removeStream=function(d){var a,b,c;this._localStreams||(this._localStreams=[]);let e=J(a=this._localStreams).call(a,d);if(-1!==e){Ra(b=this._localStreams).call(b,e,1);var f=d.getTracks();t(c=this.getSenders()).call(c,a=>{Z(f).call(f,a.track)&&this.removeTrack(a)})}})}}function Bi(d){if("object"==typeof d&&d.RTCPeerConnection&&("getRemoteStreams"in
d.RTCPeerConnection.prototype||(d.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in d.RTCPeerConnection.prototype))){Q(d.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(a){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly));this.addEventListener("addstream",this._onaddstream=a);this.addEventListener("track",this._onaddstreampoly=
a=>{var b;t(b=a.streams).call(b,a=>{var b;(this._remoteStreams||(this._remoteStreams=[]),Z(b=this._remoteStreams).call(b,a))||(this._remoteStreams.push(a),b=new Event("addstream"),b.stream=a,this.dispatchEvent(b))})})}});let g=d.RTCPeerConnection.prototype.setRemoteDescription;d.RTCPeerConnection.prototype.setRemoteDescription=function(){let a=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(b){var c;t(c=b.streams).call(c,b=>{var c;(a._remoteStreams||
(a._remoteStreams=[]),0<=J(c=a._remoteStreams).call(c,b))||(a._remoteStreams.push(b),c=new Event("addstream"),c.stream=b,a.dispatchEvent(c))})}),g.apply(a,arguments)}}}function Ci(d){if("object"==typeof d&&d.RTCPeerConnection){d=d.RTCPeerConnection.prototype;var g=d.createOffer,a=d.createAnswer,b=d.setLocalDescription,c=d.setRemoteDescription,e=d.addIceCandidate;d.createOffer=function(a,b){let c=g.apply(this,[2<=arguments.length?arguments[2]:arguments[0]]);return b?(c.then(a,b),y.resolve()):c};d.createAnswer=
function(b,c){let d=a.apply(this,[2<=arguments.length?arguments[2]:arguments[0]]);return c?(d.then(b,c),y.resolve()):d};var f=function(a,c,d){a=b.apply(this,[a]);return d?(a.then(c,d),y.resolve()):a};d.setLocalDescription=f;f=function(a,b,d){a=c.apply(this,[a]);return d?(a.then(b,d),y.resolve()):a};d.setRemoteDescription=f;f=function(a,b,c){a=e.apply(this,[a]);return c?(a.then(b,c),y.resolve()):a};d.addIceCandidate=f}}function Di(d){let g=d&&d.navigator;if(g.mediaDevices&&g.mediaDevices.getUserMedia){var a;
d=g.mediaDevices;let b=xa(a=d.getUserMedia).call(a,d);g.mediaDevices.getUserMedia=a=>b(Ei(a))}var b;!g.getUserMedia&&g.mediaDevices&&g.mediaDevices.getUserMedia&&(g.getUserMedia=xa(b=function(a,b,d){g.mediaDevices.getUserMedia(a).then(b,d)}).call(b,g))}function Ei(d){return d&&void 0!==d.video?Ya({},d,{video:bi(d.video)}):d}function Fi(d){let g=d.RTCPeerConnection;d.RTCPeerConnection=function(a,b){if(a&&a.iceServers){let b=[];for(let c=0;c<a.iceServers.length;c++){let d=a.iceServers[c];!d.hasOwnProperty("urls")&&
d.hasOwnProperty("url")?(Ae("RTCIceServer.url","RTCIceServer.urls"),d=JSON.parse(A(d)),d.urls=d.url,delete d.url,b.push(d)):b.push(a.iceServers[c])}a.iceServers=b}return new g(a,b)};d.RTCPeerConnection.prototype=g.prototype;"generateCertificate"in d.RTCPeerConnection&&Q(d.RTCPeerConnection,"generateCertificate",{get:()=>g.generateCertificate})}function Gi(d){"object"==typeof d&&d.RTCPeerConnection&&"receiver"in d.RTCTrackEvent.prototype&&!d.RTCTransceiver&&Q(d.RTCTrackEvent.prototype,"transceiver",
{get(){return{receiver:this.receiver}}})}function Hi(d){let g=d.RTCPeerConnection.prototype.createOffer;d.RTCPeerConnection.prototype.createOffer=function(a){if(a){var b,c;void 0!==a.offerToReceiveAudio&&(a.offerToReceiveAudio=!!a.offerToReceiveAudio);let d=U(b=this.getTransceivers()).call(b,a=>"audio"===a.receiver.track.kind);!1===a.offerToReceiveAudio&&d?"sendrecv"===d.direction?d.setDirection?d.setDirection("sendonly"):d.direction="sendonly":"recvonly"===d.direction&&(d.setDirection?d.setDirection("inactive"):
d.direction="inactive"):!0!==a.offerToReceiveAudio||d||this.addTransceiver("audio");void 0!==a.offerToReceiveVideo&&(a.offerToReceiveVideo=!!a.offerToReceiveVideo);b=U(c=this.getTransceivers()).call(c,a=>"video"===a.receiver.track.kind);!1===a.offerToReceiveVideo&&b?"sendrecv"===b.direction?b.setDirection?b.setDirection("sendonly"):b.direction="sendonly":"recvonly"===b.direction&&(b.setDirection?b.setDirection("inactive"):b.direction="inactive"):!0!==a.offerToReceiveVideo||b||this.addTransceiver("video")}return g.apply(this,
arguments)}}function De(d){if(d.RTCIceCandidate&&!(d.RTCIceCandidate&&"foundation"in d.RTCIceCandidate.prototype)){var g=d.RTCIceCandidate;d.RTCIceCandidate=function(a){var b;if("object"==typeof a&&a.candidate&&0===J(b=a.candidate).call(b,"a=")&&((a=JSON.parse(A(a))).candidate=a.candidate.substr(2)),a.candidate&&a.candidate.length){b=new g(a);a=H.parseCandidate(a.candidate);let c=Ya(b,a);return c.toJSON=function(){return{candidate:c.candidate,sdpMid:c.sdpMid,sdpMLineIndex:c.sdpMLineIndex,usernameFragment:c.usernameFragment}},
c}return new g(a)};d.RTCIceCandidate.prototype=g.prototype;Zc(d,"icecandidate",a=>(a.candidate&&Q(a,"candidate",{value:new d.RTCIceCandidate(a.candidate),writable:"false"}),a))}}function Id(d){if(d.RTCPeerConnection){var g=ic(d);"sctp"in d.RTCPeerConnection.prototype||Q(d.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});var a=function(a){if(!a||!a.sdp)return!1;a=H.splitSections(a.sdp);return a.shift(),fi(a).call(a,a=>{var b;return(a=H.parseMLine(a))&&"application"===
a.kind&&-1!==J(b=a.protocol).call(b,"SCTP")})},b=function(a){a=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===a||2>a.length)return-1;a=wa(a[1],10);return a!=a?-1:a},c=function(a){let b=65536;return"firefox"===g.browser&&(b=57>g.version?-1===a?16384:2147483637:60>g.version?57===g.version?65535:65536:2147483637),b},e=function(a,b){let c=65536;"firefox"===g.browser&&57===g.version&&(c=65535);a=H.matchPrefix(a.sdp,"a=max-message-size:");return 0<a.length?c=wa(a[0].substr(19),10):"firefox"===
g.browser&&-1!==b&&(c=2147483637),c},f=d.RTCPeerConnection.prototype.setRemoteDescription;d.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===g.browser&&76<=g.version){var {sdpSemantics:d}=this.getConfiguration();"plan-b"===d&&Q(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(a(arguments[0])){var l=b(arguments[0]);d=c(l);l=e(arguments[0],l);let a;a=0===d&&0===l?Number.POSITIVE_INFINITY:0===d||0===l?Math.max(d,
l):Math.min(d,l);d={};Q(d,"maxMessageSize",{get:()=>a});this._sctp=d}return f.apply(this,arguments)}}}function Jd(d){function g(a,c){let b=a.send;a.send=function(){var d=arguments[0];d=d.length||d.size||d.byteLength;if("open"===a.readyState&&c.sctp&&d>c.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+c.sctp.maxMessageSize+" bytes)");return b.apply(a,arguments)}}if(d.RTCPeerConnection&&"createDataChannel"in d.RTCPeerConnection.prototype){var a=d.RTCPeerConnection.prototype.createDataChannel;
d.RTCPeerConnection.prototype.createDataChannel=function(){let b=a.apply(this,arguments);return g(b,this),b};Zc(d,"datachannel",a=>(g(a.channel,a.target),a))}}function Qf(d){var g;if(d.RTCPeerConnection&&!("connectionState"in d.RTCPeerConnection.prototype)){var a=d.RTCPeerConnection.prototype;Q(a,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0});Q(a,"onconnectionstatechange",{get(){return this._onconnectionstatechange||
null},set(a){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange);a&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=a)},enumerable:!0,configurable:!0});t(g=["setLocalDescription","setRemoteDescription"]).call(g,b=>{let c=a[b];a[b]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=a=>{let b=a.target;if(b._lastConnectionState!==b.connectionState){b._lastConnectionState=
b.connectionState;let c=new Event("connectionstatechange",a);b.dispatchEvent(c)}return a},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),c.apply(this,arguments)}})}}function Rf(d){if(d.RTCPeerConnection){var g=ic(d);if(!("chrome"===g.browser&&71<=g.version)){var a=d.RTCPeerConnection.prototype.setRemoteDescription;d.RTCPeerConnection.prototype.setRemoteDescription=function(b){var c,d;b&&b.sdp&&-1!==J(c=b.sdp).call(c,"\na=extmap-allow-mixed")&&(b.sdp=I(d=b.sdp.split("\n")).call(d,
a=>"a=extmap-allow-mixed"!==Fc(a).call(a)).join("\n"));return a.apply(this,arguments)}}}}function V(d){d&&Sf.setUA(d);cb=Sf.getResult();d=Yn(cb);var g;var a=(g="Blink"===cb.engine.name?cb.engine.version||"":cb.browser.version||"",g.split(".")[0]);a:switch(cb.os.name){case "Windows":g=cb.os.version?cb.os.name+" "+cb.os.version:cb.os.name;break a;default:g=cb.os.name||""}return{name:d,version:a,os:g,osVersion:cb.os.version}}function Yn(d){if("Blink"===d.engine.name)return S.CHROME;switch(d.browser.name){case "Chrome Headless":case "Chrome":case "Chromium":return S.CHROME;
case "Safari":case "Mobile Safari":return S.SAFARI;case "Edge":return S.EDGE;case "Firefox":return S.FIREFOX;case "QQBrowser":return S.QQ;case "Opera":return S.OPERA;case "WeChat":return S.WECHAT;default:return d.browser.name||""}}function Ee(){let d=V();return!!("WebKit"===cb.engine.name&&d.os===Na.MAC_OS&&navigator.maxTouchPoints&&0<navigator.maxTouchPoints&&d.name!==S.SAFARI||vb()&&d.name!==S.SAFARI)}function Zn(){var d=V();return Ee()&&(d.os===Na.MAC_OS||d.os===Na.IOS&&((d=cb.os.version&&cb.os.version.split("."))&&
14===Number(d[0])&&d[1]&&3<=Number(d[1])||d&&14<Number(d[0])))?!0:!1}function Kd(){return V().name===S.CHROME}function $c(){return V().name===S.SAFARI}function db(){return V().name===S.FIREFOX}function vb(){return V().os===Na.IOS}function ad(){var d=V();if(d.os!==Na.IOS||!d.osVersion)return!1;d=d.osVersion.split(".");return 15===Number(d[0])}function Ii(){var d=V();if(d.os!==Na.IOS||!d.osVersion)return!1;d=d.osVersion.split(".");return 15===Number(d[0])&&0===Number(d[1])}function Ji(){var d=V();if(d.os!==
Na.IOS||!d.osVersion)return!1;d=d.osVersion.split(".");return 15===Number(d[0])&&1<=Number(d[1])}function jc(){return $c()&&0<navigator.maxTouchPoints}function Ki(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&35>=window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]}function Tf(){let d=V();return d.name===S.EDGE||d.name===S.SAFARI?!1:!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function bd(d){return"string"==typeof d?
Ya({},$n[d]):d}function Uf(d){return"string"==typeof d?Ya({},ao[d]):d}function Fe(d){return"string"==typeof d?Ya({},bo[d]):d}function Ge(d){return"string"==typeof d?Ya({},co[d]):d}function eb(d,g){var a;Z(a=W(v)).call(a,d)&&(v[d]=g)}function cd(d,g,a){return{sampleRate:d,stereo:g,bitrate:a}}function M(d,g,a,b,c){return{width:d,height:g,frameRate:a,bitrateMin:b,bitrateMax:c}}function Eb(d,g,a,b,c){return{width:{max:d},height:{max:g},frameRate:a,bitrateMin:b,bitrateMax:c}}function Vf(d,g){return{numSpatialLayers:d,
numTemporalLayers:g}}function Li(d){return"[object Array]"===dd.call(d)}function Mi(d){return null!==d&&"object"==typeof d}function Ni(d){return"[object Function]"===dd.call(d)}function He(d,g){if(null!=d)if("object"!=typeof d&&(d=[d]),Li(d))for(var a=0,b=d.length;a<b;a++)g.call(null,d[a],a,d);else for(a in d)Object.prototype.hasOwnProperty.call(d,a)&&g.call(null,d[a],a,d)}function Oi(d){return encodeURIComponent(d).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,
"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ie(){this.handlers=[]}function Pi(d,g){!O.isUndefined(d)&&O.isUndefined(d["Content-Type"])&&(d["Content-Type"]=g)}function Ld(d){this.defaults=d;this.interceptors={request:new Qi,response:new Qi}}function Wf(d){this.message=d}function Je(d){if("function"!=typeof d)throw new TypeError("executor must be a function.");var g;this.promise=new Promise(function(a){g=a});var a=this;d(function(b){a.reason||(a.reason=new Ri(b),g(a.reason))})}function Si(d){d=
new Ke(d);var g=Ti(Ke.prototype.request,d);return O.extend(g,Ke.prototype,d),O.extend(g,d),g}function Ui(){let d=new Date;return d.toTimeString().split(" ")[0]+":"+d.getMilliseconds()}function Le(d,g){if("boolean"!=typeof d)throw new q(n.INVALID_PARAMS,"Invalid ".concat(g,": The value is of the boolean type."));}function fb(d,g,a){var b;if(!Z(a).call(a,d))throw new q(n.INVALID_PARAMS,m(b="".concat(g," can only be set as ")).call(b,A(a)));}function ha(d,g,a=1,b=1E4,c=!0){if(d<a||d>b||c&&("number"!=
typeof d||0!=d%1)){var e,f;throw new q(n.INVALID_PARAMS,m(e=m(f="invalid ".concat(g,": the value range is [")).call(f,a,", ")).call(e,b,"]. integer only"));}}function Sa(d,g,a=1,b=255,c=!0){if(null==d)throw new q(n.INVALID_PARAMS,"".concat(g||"param"," cannot be empty"));var e,f,h;if(!Vi(d,a,b,c))throw new q(n.INVALID_PARAMS,m(e=m(f=m(h="Invalid ".concat(g||"string param",": Length of the string: [")).call(h,a,",")).call(f,b,"].")).call(e,c?" ASCII characters only.":""));}function Xf(d,g){if(!Qb(d))throw new q(n.INVALID_PARAMS,
"".concat(g," should be an array"));}function Yf(d){if("string"!=typeof d||!/^[a-zA-Z0-9 !#\$%&\(\)\+\-:;<=\.>\?@\[\]\^_\{\}\|~,]{1,64}$/.test(d))throw k.error("Invalid Channel Name ".concat(d)),new q(n.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,");}function Zf(d){var g;if(!("number"==typeof d&&Math.floor(d)===d&&0<=d&&4294967295>=d||Vi(d,1,255)))throw k.error(m(g="Invalid UID ".concat(d,
" ")).call(g,typeof d)),new q(n.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");"string"==typeof d&&k.warning("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}function Vi(d,g=1,a=255,b=!0){if(g="string"==typeof d&&d.length<=a&&d.length>=g){if(!(b=!b))a:if("string"!=typeof d)b=!1;else{for(b=0;b<d.length;b+=1)if(g=d.charCodeAt(b),0>g||255<
g){b=!1;break a}b=!0}g=b}return g}function eo(d){return Sa(d.reportId,"params.reportId",0,100,!1),Sa(d.category,"params.category",0,100,!1),Sa(d.event,"params.event",0,100,!1),Sa(d.label,"params.label",0,100,!1),ha(d.value,"params.value",-9007199254740991,9007199254740991,!1),!0}function Wi(d){return ha(d.timeout,"config.timeout",0,1E5),ha(d.timeoutFactor,"config.timeoutFactor",0,100,!1),ha(d.maxRetryCount,"config.maxRetryConfig",0,1/0),ha(d.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function Xi(d){if(!Qb(d)||
1>d.length)return!1;try{t(d).call(d,d=>{if(!d.urls)throw Error();})}catch(g){return!1}return!0}function Yi(d){return Sa(d.turnServerURL,"turnServerURL"),Sa(d.username,"username"),Sa(d.password,"password"),d.udpport&&ha(d.udpport,"udpport",1,99999,!0),d.forceturn&&Le(d.forceturn,"forceturn"),d.security&&Le(d.security,"security"),d.tcpport&&ha(d.tcpport,"tcpport",1,99999,!0),!0}function Zi(d){return void 0!==d.level&&fb(d.level,"level",[1,2,3]),!0}function $f(d,g){Sa(d.url,"".concat(g,".url"),1,1E3,
!1);null==d.x||ha(d.x,"".concat(g,".x"),0,1E4);null==d.y||ha(d.y,"".concat(g,".y"),0,1E4);null==d.width||ha(d.width,"".concat(g,".width"),0,1E4);null==d.height||ha(d.height,"".concat(g,".height"),0,1E4);null==d.zOrder||ha(d.zOrder,"".concat(g,".zOrder"),0,255);null==d.alpha||ha(d.alpha,"".concat(g,".alpha"),0,1,!1)}function $i(d){if(!d.channelName)throw new q(n.INVALID_PARAMS,"invalid channelName in info");if(!d.uid||"number"!=typeof d.uid)throw new q(n.INVALID_PARAMS,"invalid uid in info, uid must be a number");
return d.token&&Sa(d.token,"info.token",1,2047),Zf(d.uid),Yf(d.channelName),!0}function aj(d){return fb(d,"mediaSource",["screen","window","application"]),!0}function bj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function Rb(d,g,a){return new y((b,c)=>{g.timeout=g.timeout||v.HTTP_CONNECT_TIMEOUT;g.responseType=g.responseType||"json";g.data&&!a?(g.data=A(g.data),Me+=ed(g.data)):a&&(g.data.size?Me+=g.data.size:g.data instanceof
FormData?Me+=function(a){let b=0;/DingTalk/i.test(navigator.userAgent)&&a.realFormData&&(a=a.realFormData);return t(a).call(a,a=>{b+="string"==typeof a?ed(a):a.size}),b+138}(g.data):Me+=ed(A(g.data)));g.headers=g.headers||{};g.headers["Content-Type"]=g.headers["Content-Type"]||"application/json";g.method="POST";g.url=d;$b.request(g).then(a=>{"string"==typeof a.data?ag+=ed(a.data):a.data instanceof ArrayBuffer||a.data instanceof Uint8Array?ag+=a.data.byteLength:ag+=ed(A(a.data));b(a.data)}).catch(a=>
{$b.isCancel(a)?c(new q(n.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===a.code?c(new q(n.NETWORK_TIMEOUT,a.message)):a.response?c(new q(n.NETWORK_RESPONSE_ERROR,a.response.status)):c(new q(n.NETWORK_ERROR,a.message))})})}async function fo(d,g){let a=new Blob([g.data],{type:"buffer"});return await Rb(d,function(a){for(var b=1;b<arguments.length;b++){var d,f=null!=arguments[b]?arguments[b]:{};if(b%2)t(d=bj(Object(f),!0)).call(d,function(b){gb(a,b,f[b])});else if(ka)hb(a,ka(f));else{var h;
t(h=bj(Object(f))).call(h,function(b){Q(a,b,ca(f,b))})}}return a}({},g,{data:a,headers:{"Content-Type":"application/octet-stream"}}),!0)}function ac(d,g,a,b){let c=Ya({},Ga,b),e=c.timeout,f=async()=>{await jb(e);e*=c.timeoutFactor;e=Math.min(c.maxRetryTimeout,e)},h=!1;b=new y(async(b,e)=>{g=g||(()=>!1);a=a||(()=>!0);for(let l=0;l<c.maxRetryCount;l+=1){if(h)return e(new q(n.OPERATION_ABORTED));try{const a=await d();if(!g(a,l)||l+1===c.maxRetryCount)return b(a);await f()}catch(w){if(!a(w,l)||l+1===
c.maxRetryCount)return e(w);await f()}}});return b.cancel=()=>h=!0,b}function cj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function Ea(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=cj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=cj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Md(d={report:u}){return function(g,
a,b){let c=g[a];if("function"==typeof c){let e="AgoraRTCClient"===g.constructor.name?"Client":g.constructor.name;b.value=function(...b){var f;let g=d.report.reportApiInvoke(this._sessionId||null,{name:m(f="".concat(e,".")).call(f,a),options:b,tag:C.TRACER});try{let a=c.apply(this,b);return g.onSuccess(),a}catch(r){throw g.onError(r),r;}}}return b}}function bg(d={report:u}){return function(g,a,b){let c=g[a];if("function"==typeof c){let e="AgoraRTCClient"===g.constructor.name?"Client":g.constructor.name;
b.value=async function(...b){var f;let g=d.report.reportApiInvoke(this._sessionId||null,{name:m(f="".concat(e,".")).call(f,a),options:b,tag:C.TRACER});try{let a=await c.apply(this,b);return g.onSuccess(),a}catch(r){throw g.onError(r),r;}}}return b}}function go(){dj?(k.info("create audio context"),Sb=new dj,da.curState=Sb.state,Sb.onstatechange=()=>{var d;da.prevState=da.curState;da.curState=Sb?Sb.state:void 0;k.debug("AudioContext State Change",m(d="".concat(da.prevState,"=>")).call(d,da.curState));
(vb()||jc())&&"running"===da.prevState&&"interrupted"===da.curState&&(k.info("ios-interruption-start"),da.emit(Ha.IOS_INTERRUPTION_START));(vb()||jc())&&"interrupted"===da.prevState&&"running"===da.curState&&(k.info("ios-interruption-end"),da.emit(Ha.IOS_INTERRUPTION_END));da.emit("state-change")},async function(d){function g(c){"running"===d.state?a(!1):vb()||jc()?"suspended"===d.state&&(a(!0),c?d.resume().then(b,b):a(!1)):"closed"!==d.state&&(a(!0),c?d.resume().then(b,b):a(!1))}function a(a){if(w!==
a){w=a;for(let b=0,d=r;b<d.length;b+=1){let e=d[b];a?window.addEventListener(e,c,{capture:!0,passive:!0}):window.removeEventListener(e,c,{capture:!0,passive:!0})}}}function b(){g(!1)}function c(){g(!0)}function e(a){if(!k)if(p.paused)if(a){f(!1);k=!0;a=void 0;try{(a=p.play())?a.then(h,h):(p.addEventListener("playing",h),p.addEventListener("abort",h),p.addEventListener("error",h))}catch(B){h()}}else f(!0);else f(!1)}function f(a){if(X!==a){X=a;for(let b=0,c=r;b<c.length;b++){let d=c[b];a?window.addEventListener(d,
l,{capture:!0,passive:!0}):window.removeEventListener(d,l,{capture:!0,passive:!0})}}}function h(){p.removeEventListener("playing",h);p.removeEventListener("abort",h);p.removeEventListener("error",h);k=!1;e(!1)}function l(){e(!0)}let r="click contextmenu auxclick dblclick mousedown mouseup touchend keydown keyup".split(" "),p,w=!1,X=!1,k=!1;if(vb()){let a=d.createMediaStreamDestination(),b=document.createElement("div");b.innerHTML="<audio x-webkit-airplay='deny'></audio>";p=b.children.item(0);p.controls=
!1;p.disableRemotePlayback=!0;p.preload="auto";p.srcObject=a.stream;e(!0)}da.on("state-change",function(){g(!0)});g(!1)}(Sb)):k.error("your browser is not support web audio")}function Nd(){if(!Sb&&(go(),!Sb))throw new q(n.NOT_SUPPORTED,"can not create audio context");return Sb}function Od(d){if(!function(){if(null!==cg)return cg;var a=Nd();let c=a.createBufferSource(),d=a.createGain();a=a.createGain();c.connect(d);c.connect(a);c.disconnect(d);a=!1;try{c.disconnect(d)}catch(f){a=!0}return c.disconnect(),
cg=a,a}()){k.debug("polyfill audio node");var g=d.connect,a=d.disconnect;d.connect=(a,c,e)=>{var b;return d._inputNodes||(d._inputNodes=[]),Z(b=d._inputNodes).call(b,a)||(a instanceof AudioNode?(d._inputNodes.push(a),g.call(d,a,c,e)):g.call(d,a,c)),d};d.disconnect=(b,c,e)=>{a.call(d);b?Gc(d._inputNodes,b):d._inputNodes=[];for(let a of d._inputNodes)g.call(d,a)}}}function dg(d,g){let a=1/g,b=Nd(),c=b.createGain();c.gain.value=0;c.connect(b.destination);let e=!1,f=()=>{if(e)return void(c=null);const h=
b.createOscillator();h.onended=f;h.connect(c);h.start(0);h.stop(b.currentTime+a);d(b.currentTime)};return f(),()=>{e=!0}}async function ej(d,g){let a=(a,c)=>a?"number"!=typeof a?a.max||a.exact||a.ideal||a.min||c:a:c;d={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:d,maxHeight:a(g.height,1080),maxWidth:a(g.width,1920)}}};return g.frameRate&&"number"!=typeof g.frameRate?(d.video.mandatory.maxFrameRate=g.frameRate.max,d.video.mandatory.minFrameRate=g.frameRate.min):"number"==
typeof g.frameRate&&(d.video.mandatory.maxFrameRate=g.frameRate),await navigator.mediaDevices.getUserMedia(d)}async function ho(d){let g=await function(a){return new y((b,c)=>{const d=document.createElement("div");d.innerText="share screen";d.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");const f=document.createElement("div");f.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");
const h=document.createElement("div");h.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.";h.setAttribute("style","height: 12%;");const g=document.createElement("div");g.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;");const r=document.createElement("div");
r.setAttribute("style","text-align: right; padding: 16px 0;");const p=document.createElement("button");p.innerHTML="cancel";p.setAttribute("style","width: 85px;");p.onclick=()=>{document.body.removeChild(w);const a=Error("NotAllowedError");a.name="NotAllowedError";c(a)};r.appendChild(p);f.appendChild(h);f.appendChild(g);f.appendChild(r);const w=document.createElement("div");w.setAttribute("style","position: fixed; 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%);");
w.appendChild(d);w.appendChild(f);document.body.appendChild(w);z(a).call(a,a=>{if(a.id){const c=document.createElement("div");c.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let d=a.thumbnail;const {width:e}=d.getSize();1920<e&&(d=d.resize({width:1920}));c.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+
d.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+(a.name.replace(/[\u00A0-\u9999<>&]/g,function(a){return"&#"+a.charCodeAt(0)+";"})+"</span>");c.onclick=()=>{document.body.removeChild(w);b(a.id)};g.appendChild(c)}})})}(await fj(d.mediaSource));return await ej(g,d)}async function fj(d){let g=["window","screen"];"application"!==d&&"window"!==d||(g=["window"]);
"screen"===d&&(g=["screen"]);let a=gj();if(!a)throw new q(n.ELECTRON_IS_NULL);d=null;try{d=a.desktopCapturer.getSources({types:g})}catch(b){d=null}d&&d.then||(d=new y((b,c)=>{a.desktopCapturer.getSources({types:g},(a,d)=>{a?c(a):b(d)})}));try{return await d}catch(b){throw new q(n.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,b.toString());}}function gj(){if(Ne)return Ne;try{return Ne=window.require("electron"),Ne}catch(d){return null}}async function Fb(d,g){let a=0,b=null;for(;2>a;)try{b=await io(d,
g,0<a);break}catch(f){var c,e;if(f instanceof q)throw k.error(m(e="[".concat(g,"] ")).call(e,f.toString())),f;let b=Oe(f.name||f.code||f,f.message);if(b.code===n.MEDIA_OPTION_INVALID)k.debug("[".concat(g,"] detect media option invalid, retry")),a+=1,await jb(500);else throw k.error(m(c="[".concat(g,"] ")).call(c,b.toString())),b;}if(!b)throw new q(n.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return b}async function io(d,g,a){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new q(n.NOT_SUPPORTED,
"can not find getUserMedia");a&&(d.video&&(delete d.video.width,delete d.video.height),d.screen&&(delete d.screen.width,delete d.screen.height));var b=la;a=new MediaStream;if(d.audioSource&&a.addTrack(d.audioSource),d.videoSource&&a.addTrack(d.videoSource),!d.audio&&!d.video&&!d.screen)return k.debug("Using Video Source/ Audio Source"),a;if(d.screen)if(gj())d.screen.sourceId?fd(a,await ej(d.screen.sourceId,d.screen)):fd(a,await ho(d.screen));else if(Kd()&&d.screen.extensionId&&d.screen.mandatory){if(!b.getStreamFromExtension)throw new q(n.NOT_SUPPORTED,
"This browser does not support screen sharing");k.debug("[".concat(g,'] Screen access on chrome stable, looking for extension"'));var c=await (e=d.screen.extensionId,f=g,new y((a,b)=>{try{chrome.runtime.sendMessage(e,{getStream:!0},c=>{if(!c||!c.streamId)return k.error("[".concat(f,"] No response from Chrome Plugin. Plugin not installed properly"),c),void b(new q(n.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));a(c.streamId)})}catch(w){var c;k.error(m(c=
"[".concat(f,"] AgoraRTC screensharing plugin is not accessible(")).call(c,e,")"),w.toString());b(new q(n.CHROME_PLUGIN_NOT_INSTALL))}}));d.screen.mandatory.chromeMediaSourceId=c;fd(a,await navigator.mediaDevices.getUserMedia({video:{mandatory:d.screen.mandatory}}))}else if(b.getDisplayMedia)d.screen.mediaSource&&aj(d.screen.mediaSource),c={width:d.screen.width,height:d.screen.height,frameRate:d.screen.frameRate,displaySurface:"screen"===d.screen.mediaSource?"monitor":d.screen.mediaSource},k.debug("[".concat(g,
"] getDisplayMedia:"),A({video:c,audio:!!d.screenAudio})),fd(a,await navigator.mediaDevices.getDisplayMedia({video:c,audio:!!d.screenAudio}));else{if(!db())throw k.error("[".concat(g,"] This browser does not support screenSharing")),new q(n.NOT_SUPPORTED,"This browser does not support screen sharing");d.screen.mediaSource&&aj(d.screen.mediaSource);b={video:{mediaSource:d.screen.mediaSource,width:d.screen.width,height:d.screen.height,frameRate:d.screen.frameRate}};k.debug(m(c="[".concat(g,"] getUserMedia: ")).call(c,
A(b)));fd(a,await navigator.mediaDevices.getUserMedia(b))}var e,f;if(!d.video&&!d.audio)return a;d={video:d.video,audio:d.audio};k.debug("[".concat(g,"] GetUserMedia"),A(d));V();let h;g=null;($c()||vb()||Ee())&&(g=await eg.lock());try{h=await navigator.mediaDevices.getUserMedia(d)}catch(l){throw g&&g(),l;}return d.audio&&(hj=!0),d.video&&(ij=!0),fd(a,h),g&&g(),a}function Oe(d,g){switch(d){case "Starting video failed":case "OverconstrainedError":case "TrackStartError":var a;return new q(n.MEDIA_OPTION_INVALID,
m(a="".concat(d,": ")).call(a,g));case "NotFoundError":case "DevicesNotFoundError":var b;return new q(n.DEVICE_NOT_FOUND,m(b="".concat(d,": ")).call(b,g));case "NotSupportedError":var c;return new q(n.NOT_SUPPORTED,m(c="".concat(d,": ")).call(c,g));case "NotReadableError":var e;return new q(n.NOT_READABLE,m(e="".concat(d,": ")).call(e,g));case "InvalidStateError":case "NotAllowedError":case "PERMISSION_DENIED":case "PermissionDeniedError":var f;return new q(n.PERMISSION_DENIED,m(f="".concat(d,": ")).call(f,
g));case "ConstraintNotSatisfiedError":var h;return new q(n.CONSTRAINT_NOT_SATISFIED,m(h="".concat(d,": ")).call(h,g));default:var l;return k.error("getUserMedia unexpected error",d),new q(n.UNEXPECTED_ERROR,m(l="".concat(d,": ")).call(l,g))}}function fd(d,g){let a=d.getVideoTracks()[0],b=d.getAudioTracks()[0],c=g.getVideoTracks()[0];(g=g.getAudioTracks()[0])&&(b&&d.removeTrack(b),d.addTrack(g));c&&(a&&d.removeTrack(a),d.addTrack(c))}function jj(){if(!fg){let d=g=>{g.preventDefault();fg=!1;document.body.removeEventListener("touchstart",
d,!0);document.body.removeEventListener("mousedown",d,!0)};fg=!0;document.body.addEventListener("touchstart",d,!0);document.body.addEventListener("mousedown",d,!0);kj.emit("autoplay-failed")}}function pa(){return function(d,g,a){let b=d[g];"function"==typeof b&&(a.value=function(...a){this._isClosed&&(new q(n.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track"))).print("warning");let c=b.apply(this,a);return c instanceof y?new y((a,b)=>{c.then(a).catch(b)}):c})}}function lj(d,
g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function Pe(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=lj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=lj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function mj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}
function bc(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=mj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=mj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function nj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function oj(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=nj(Object(b),
!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=nj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function jo(d){if(!d.address||!d.tcp)throw new q(n.UNEXPECTED_RESPONSE,"Invalid address format ".concat(d));return d.address.match(/^[\.:\d]+$/)?"".concat(d.address.replace(/[^\d]/g,"-"),".edge.agora.io"):(k.info("Cannot recognized as IP address ".concat(d.address,". Used As Host instead")),m(g="".concat(d.address,":")).call(g,d.tcp));var g}function pj(d,g){var a;
let b=v.GATEWAY_DOMAINS,c=b[1]&&-1!==J(g).call(g,b[1])?1:0;d.addresses=d.addresses||[];return{gatewayAddrs:z(a=d.addresses).call(a,a=>{var d,e,g;return a.ip.match(/^[\.:\d]+$/)?m(d=m(e="".concat(a.ip.replace(/[^\d]/g,"-"),".")).call(e,b[c++%b.length],":")).call(d,a.port):(k.info("Cannot recognized as IP address ".concat(a.ip,". Used As Host instead")),m(g="".concat(a.ip,":")).call(g,a.port))}),uid:d.uid,cid:d.cid,vid:d.detail&&d.detail[8],uni_lbs_ip:d.detail&&d.detail[1],res:d,csIp:d.detail&&d.detail[502]}}
function wc(d){return"number"==typeof d?d:d.exact||d.ideal||d.max||d.min||0}function qj(d,g){let a=d.videoSend[0];if(!a)return null;g=g&&g.videoSend[0]?g.videoSend[0].inputFrame:void 0;d={id:va(10,""),timestamp:(new Date(d.timestamp)).toISOString(),mediaType:"video",type:"ssrc",ssrc:a.ssrc.toString()};return a.inputFrame&&(g&&a.inputFrame.height===g.height||(d.A_fhi=a.inputFrame.height?a.inputFrame.height.toString():"0"),g&&a.inputFrame.width===g.width||(d.A_fwi=a.inputFrame.width?a.inputFrame.width.toString():
"0"),g&&a.inputFrame.frameRate===g.frameRate||(d.A_fri=a.inputFrame.frameRate?a.inputFrame.frameRate.toString():"0")),d}function rj(d){return 0<=d&&.17>d?1:.17<=d&&.36>d?2:.36<=d&&.59>d?3:.59<=d&&1>=d?4:1<d?5:0}function ko(d,g){let a={};d.height&&d.width&&(g=g._videoHeight||g.getMediaStreamTrack(!0).getSettings().height,a.scaleResolutionDownBy=g?g/wc(d.height):4);return a.maxFramerate=d.framerate?wc(d.framerate):void 0,a.maxBitrate=d.bitrate?1E3*d.bitrate:void 0,a}function gg(d,g){var a;let b,c=void 0;
switch(g){case ib.CHOOSE_SERVER:b=4096;g="choose server";break;case ib.CLOUD_PROXY:b=1048576;g="proxy";break;case ib.CLOUD_PROXY_5:b=4194304;g="proxy5";break;default:throw new q(n.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:d.detail&&d.detail[502],retry:!1});}if(t(a=d.response_body).call(a,a=>{var e;a.buffer&&a.buffer.flag===b&&(c={code:a.buffer.code,addresses:z(e=a.buffer.edges_services).call(e,b=>oj({},b,{ticket:a.buffer.cert})),server_ts:d.enter_ts,uid:a.buffer.uid,
cid:a.buffer.cid,cname:a.buffer.cname,detail:oj({},a.buffer.detail,{},d.detail),flag:a.buffer.flag,opid:d.opid})}),!c)throw new q(n.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(g," from multi unilbs response"),{csIp:d.detail&&d.detail[502]});return c}function lo(d){var g;return z(g=d.addresses).call(g,a=>({address:a.ip,tcpport:a.port,udpport:a.port,username:Oa.username,password:Oa.password}))}function sj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));
a.push.apply(a,b)}return a}function hg(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=sj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=sj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function ed(d){return window.TextEncoder?(new TextEncoder).encode(d).length:d.length}function jb(d){return new y(g=>{window.setTimeout(g,d)})}function mo(d){let g=new q(n.TIMEOUT,"timeout");return new y((a,b)=>{window.setTimeout(()=>
b(g),d)})}function va(d=7,g){var a,b;let c=Math.random().toString(16).substr(2,d).toLowerCase();return c.length===d?m(a="".concat(g)).call(a,c):m(b="".concat(g)).call(b,c)+va(d-c.length,"")}function tj(d){return new y((g,a)=>{let b=!1,c=document.createElement("video");c.setAttribute("autoplay","");c.setAttribute("muted","");c.muted=!0;c.autoplay=!0;c.setAttribute("playsinline","");c.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px");document.body.appendChild(c);a=vb()?
"canplay":"playing";c.addEventListener(a,()=>{let a=c.videoWidth,d=c.videoHeight;!a&&db()||(b=!0,c.srcObject=null,c.remove(),g([a,d]))});c.srcObject=new MediaStream([d]);c.play().catch(Qe);wb(()=>{b||(c.srcObject=null,c.remove(),g([c.videoWidth,c.videoHeight]))},4E3)})}function gd(d){return y.all(z(d).call(d,d=>d.then(a=>{throw a;},a=>a))).then(d=>{throw d;},d=>d)}function Ia(d,g,...a){return 0===d.getListeners(g).length?y.reject(new q(n.UNEXPECTED_ERROR,"can not emit promise")):new y((b,c)=>{d.emit(g,
...a,b,c)})}function Za(d,g,...a){return 0===d.getListeners(g).length?y.resolve():Ia(d,g,...a)}function Hc(d,g,...a){return 0===d.getListeners(g).length?null:Pd(d,g,...a)}function Pd(d,g,...a){let b=null,c=null;if(d.emit(g,...a,a=>{b=a},a=>{c=a}),null!==c)throw c;if(null===b)throw new q(n.UNEXPECTED_ERROR,"handler is not sync");return b}function Gc(d,g){g=J(d).call(d,g);-1!==g&&Ra(d).call(d,g,1)}function uj(d){let g=[];return t(d).call(d,a=>{-1===J(g).call(g,a)&&g.push(a)}),g}function xb(d){y.resolve().then(d)}
function Qd(d,g){vj[g]||(vj[g]=!0,d())}function ig(d){d=window.atob(d);let g=new Uint8Array(new ArrayBuffer(d.length));for(let a=0;a<d.length;a+=1)g[a]=d.charCodeAt(a);return g}function Re(d){let g="";for(let a=0;a<d.length;a+=1)g+=String.fromCharCode(d[a]);return window.btoa(g)}function Se(d){var g=no[Math.floor(d/1E4)];if(!g)return{desc:"unkonw error",retry:!1};g=g[d%1E4];if(!g){if(Math.floor(d/1E4)===hd.ACCESS_POINT){g=d%1E4;if("1"===g.toString()[0])return{desc:d.toString(),retry:!1};if("2"===
g.toString()[0])return{desc:d.toString(),retry:!0}}return{desc:"unkonw error",retry:!1}}return g}function wj(d){return oo[d]||{desc:"UNKNOW_ERROR_".concat(d),action:"failed"}}async function po(){function d(b){let c=h["_"+b];var d;return d="Cannot call unknown function "+b+", make sure it is exported",c||a("Assertion failed: "+d),c}function g(a,b,c,e,f){f={string:function(a){let b=0;if(null!=a&&0!==a){var c=1+(a.length<<2);b=kc(c);var d=t,e=b;if(0<c){c=e+c-1;for(let b=0;b<a.length;++b){let f=a.charCodeAt(b);
55296<=f&&57343>=f&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++b));if(127>=f){if(e>=c)break;d[e++]=f}else{if(2047>=f){if(e+1>=c)break;d[e++]=192|f>>6}else{if(65535>=f){if(e+2>=c)break;d[e++]=224|f>>12}else{if(e+3>=c)break;d[e++]=240|f>>18;d[e++]=128|f>>12&63}d[e++]=128|f>>6&63}d[e++]=128|63&f}}d[e]=0}}return b},array:function(a){const b=kc(a.length);return q.set(a,b),b}};let h=d(a),g=[];a=0;if(e)for(let b=0;b<e.length;b++){let d=f[c[b]];d?(0===a&&(a=H()),g[b]=d(e[b])):g[b]=e[b]}c=h.apply(null,g);
return c=function(a){if("string"===b)if(e=a){{a=t;var c=e+d;var d=e;let b="";for(;a[d]&&!(d>=c);)++d;if(16<d-e&&a.subarray&&n)a=n.decode(a.subarray(e,d));else{for(;e<d;){c=a[e++];if(!(128&c)){b+=String.fromCharCode(c);continue}let d=63&a[e++];if(192==(224&c)){b+=String.fromCharCode((31&c)<<6|d);continue}let f=63&a[e++];(c=224==(240&c)?(15&c)<<12|d<<6|f:(7&c)<<18|d<<12|f<<6|63&a[e++],65536>c)?b+=String.fromCharCode(c):(c-=65536,b+=String.fromCharCode(55296|c>>10,56320|1023&c))}a=b}}}else a="";else a=
"boolean"===b?!!a:a;return a;var e}(c),0!==a&&Pa(a),c}function a(a){h.onAbort&&h.onAbort(a);K(a+="");B=!0;throw new WebAssembly.RuntimeError("abort("+a+"). Build with -s ASSERTIONS=1 for more info.");}function b(a){for(;0<a.length;){let b=a.shift();if("function"==typeof b){b(h);continue}let c=b.func;"number"==typeof c?void 0===b.arg?u.get(c)():u.get(c)(b.arg):c(void 0===b.arg?null:b.arg)}}function c(a){function c(){if(!E&&(E=!0,h.calledRun=!0,!B)){b(x);b(A);h.onRuntimeInitialized&&h.onRuntimeInitialized();
if(h.postRun)for("function"==typeof h.postRun&&(h.postRun=[h.postRun]);h.postRun.length;){var a=h.postRun.shift();xj.unshift(a)}b(xj)}}0<z||(!function(){if(h.preRun)for("function"==typeof h.preRun&&(h.preRun=[h.preRun]);h.preRun.length;){var a=h.preRun.shift();v.unshift(a)}b(v)}(),0<z||(h.setStatus?(h.setStatus("Running..."),wb(function(){wb(function(){h.setStatus("")},1);c()},1)):c()))}var e,f;if(kg)return kg;let h={},l,r={};for(l in h)Object.prototype.hasOwnProperty.call(h,l)&&(r[l]=h[l]);let p=
!1,w=!1;p="object"==typeof window;w="function"==typeof importScripts;let k="";(p||w)&&(w?k=self.location.href:"undefined"!=typeof document&&document.currentScript&&(k=document.currentScript.src),k=0!==J(k).call(k,"blob:")?k.substr(0,qo(k).call(k,"/")+1):"");h.print||xa(e=console.log).call(e,console);let K=h.printErr||xa(f=console.warn).call(f,console);for(l in r)Object.prototype.hasOwnProperty.call(r,l)&&(h[l]=r[l]);let m;r=null;"object"!=typeof WebAssembly&&a("no native wasm support detected");let B=
!1,n="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");let q,t,u,v=[],x=[],A=[],xj=[];x.push({func:function(){G()}});let z=0,C=null;h.preloadedImages={};h.preloadedAudios={};e="deflate.wasm";var D;Hd(D=e).call(D,"data:application/octet-stream;base64,")||(e=function(a){return h.locateFile?h.locateFile(a,k):k+a}(e));let F={emscripten_memcpy_big:function(a,b,c){var d=t.copyWithin;(t===yj||t instanceof Array&&d===yj.copyWithin?
ro:d).call(t,a,b,b+c)},emscripten_resize_heap:function(b){a("OOM")}};await async function(){function b(a,b){h.asm=a.exports;m=h.asm.memory;a=m.buffer;h.HEAP8=q=new Int8Array(a);h.HEAP16=new Int16Array(a);h.HEAP32=new Int32Array(a);h.HEAPU8=t=new Uint8Array(a);h.HEAPU16=new Uint16Array(a);h.HEAPU32=new Uint32Array(a);h.HEAPF32=new Float32Array(a);h.HEAPF64=new Float64Array(a);u=h.asm.__indirect_function_table;if(z--,h.monitorRunDependencies&&h.monitorRunDependencies(z),0==z&&C)a=C,C=null,a()}let c=
{env:F,wasi_snapshot_preview1:F};if(z++,h.monitorRunDependencies&&h.monitorRunDependencies(z),h.instantiateWasm)try{return h.instantiateWasm(c,b)}catch(Sd){return K("Module.instantiateWasm callback failed with error: "+Sd),!1}return await function(b){return(new y((a,b)=>{a(so().buffer)})).then(function(a){return WebAssembly.instantiate(a,c)}).then(b,function(b){K("failed to asynchronously prepare wasm: "+b);a(b)})}(function(a){b(a.instance)}),{}}();let E,G=h.___wasm_call_ctors=function(){return(G=
h.___wasm_call_ctors=h.asm.__wasm_call_ctors).apply(null,arguments)},I=h._malloc=function(){return(I=h._malloc=h.asm.malloc).apply(null,arguments)};h._free=function(){return(h._free=h.asm.free).apply(null,arguments)};h.___errno_location=function(){return(h.___errno_location=h.asm.__errno_location).apply(null,arguments)};h._zlibCompress=function(){return(h._zlibCompress=h.asm.zlibCompress).apply(null,arguments)};let H=h.stackSave=function(){return(H=h.stackSave=h.asm.stackSave).apply(null,arguments)},
Pa=h.stackRestore=function(){return(Pa=h.stackRestore=h.asm.stackRestore).apply(null,arguments)},kc=h.stackAlloc=function(){return(kc=h.stackAlloc=h.asm.stackAlloc).apply(null,arguments)};if(h.ccall=g,h.cwrap=function(a,b,c,e){let f=to(c=c||[]).call(c,function(a){return"number"===a});return"string"!==b&&f&&!e?d(a):function(){return g(a,b,c,arguments)}},h.allocate=function(a,b){let c;return c=1==b?kc(a.length):I(a.length),a.subarray||Ma(a)?t.set(a,c):t.set(new Uint8Array(a),c),c},C=function Ic(){E||
c();E||(C=Ic)},h.run=c,h.preInit)for("function"==typeof h.preInit&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.pop()();return c(),kg=h,h}function zj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function lg(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=zj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=zj(Object(b))).call(c,function(a){Q(d,
a,ca(b,a))})}}return d}function Aj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function uo(d,g,a,b,c){mg+=1;let e={sid:a.sid,command:"convergeAllocateEdge",uid:"666",appId:a.appId,ts:Math.floor(x()/1E3),seq:mg,requestId:mg,version:ob,cname:a.cname},f={service_name:g,json_body:A(e)},h,l,r=d[0];return ac(async()=>{h=x();var a=await Rb(r,{data:f,cancelToken:b,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(l=
x()-h,0!==a.code){var c=new q(n.UNEXPECTED_RESPONSE,"live streaming ap error, code"+a.code,{retry:!0,responseTime:l});throw k.error(c.toString()),c;}a=JSON.parse(a.json_body);if(200!==a.code)throw a=new q(n.UNEXPECTED_RESPONSE,m(c="live streaming app center error, code: ".concat(a.code,", reason: ")).call(c,a.reason),{code:a.code,responseTime:l}),k.error(a.toString()),a;if(!a.servers||0===a.servers.length)throw c=new q(n.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:a.code,responseTime:l}),
k.error(c.toString()),c;c=function(a,b){var c;return{addressList:z(c=a.servers).call(c,a=>{var c,d;return m(c=m(d="wss://".concat(a.address.replace(/\./g,"-"),".edge.agora.io:")).call(d,a.wss,"?serviceName=")).call(c,encodeURIComponent(b))}),workerToken:a.workerToken,vid:a.vid}}(a,g);return v.LIVE_STREAMING_ADDRESS&&(c.addressList=v.LIVE_STREAMING_ADDRESS instanceof Array?v.LIVE_STREAMING_ADDRESS:[v.LIVE_STREAMING_ADDRESS]),function(a){for(var b=1;b<arguments.length;b++){var c,d=null!=arguments[b]?
arguments[b]:{};if(b%2)t(c=Aj(Object(d),!0)).call(c,function(b){gb(a,b,d[b])});else if(ka)hb(a,ka(d));else{var e;t(e=Aj(Object(d))).call(e,function(b){Q(a,b,ca(d,b))})}}return a}({},c,{responseTime:l})},(b,c)=>(u.apworkerEvent(a.sid,{success:!0,sc:200,serviceName:g,responseDetail:A(b.addressList),firstSuccess:0===c,responseTime:l,serverIp:d[c%d.length]}),!1),(b,c)=>(u.apworkerEvent(a.sid,{success:!1,sc:b.data&&b.data.code||200,serviceName:g,responseTime:l,serverIp:d[c%d.length]}),!!(b.code!==n.OPERATION_ABORTED&&
b.code!==n.UNEXPECTED_RESPONSE||b.data&&b.data.retry)&&(r=d[(c+1)%d.length],!0)),c)}function Bj({url:d,areaCode:g},a,b,c){let e=x(),[f,h]=Cj(a,g,[ib.CHOOSE_SERVER]),l=pb.networkState;return ac(async()=>{l&&pb.networkState===Gb.OFFLINE&&pb.onlineWaiter&&await y.race([pb.onlineWaiter,jb(c&&c.maxRetryTimeout||Ga.maxRetryTimeout)]);l=pb.networkState;var h=await Rb(d,{data:f,cancelToken:b,headers:{"Content-Type":"multipart/form-data;"}},!0);Dj(h,d,a,e,[ib.CHOOSE_SERVER]);h=gg(h,ib.CHOOSE_SERVER);return Ej(h),
pj(h,d)},b=>(b&&u.joinChooseServer(a.sid,{lts:e,succ:!0,csAddr:d,opid:h,serverList:b.gatewayAddrs,ec:null,cid:b.cid.toString(),uid:b.uid.toString(),csIp:b.csIp,unilbsServerIds:[ib.CHOOSE_SERVER].toString()}),!1),b=>b.code!==n.OPERATION_ABORTED&&(b.code===n.CAN_NOT_GET_GATEWAY_SERVER?b.data.retry:(u.joinChooseServer(a.sid,{lts:e,succ:!1,csAddr:d,serverList:null,opid:h,ec:b.code,csIp:b.data&&b.data.csIp,unilbsServerIds:[ib.CHOOSE_SERVER].toString(),extend:A({networkState:l})}),k.warning("[".concat(a.clientId,
"] Choose server network error, retry"),b),!0)),c)}function Fj({url:d,areaCode:g,serviceIds:a},b,c,e){let f=x(),[h,l]=Cj(b,g,a),r=void 0;return ac(async()=>{r&&pb.networkState===Gb.OFFLINE&&pb.onlineWaiter&&await y.race([pb.onlineWaiter,jb(e&&e.maxRetryTimeout||Ga.maxRetryTimeout)]);r=pb.networkState;var g=await Rb(d,{data:h,cancelToken:c,headers:{"Content-Type":"multipart/form-data;"}},!0);Dj(g,d,b,f,a);let l=gg(g,ib.CHOOSE_SERVER);g=gg(g,"proxy5"===b.cloudProxyServer?ib.CLOUD_PROXY_5:ib.CLOUD_PROXY);
return Ej(l),{gatewayInfo:pj(l,d),proxyInfo:g,url:d}},c=>{var e;return c.gatewayInfo&&u.joinChooseServer(b.sid,{lts:f,succ:!0,csAddr:d,serverList:c.gatewayInfo.gatewayAddrs,ec:null,opid:l,cid:c.gatewayInfo.cid.toString(),uid:c.gatewayInfo.uid.toString(),csIp:c.gatewayInfo.csIp,unilbsServerIds:a.toString()}),c.proxyInfo&&u.joinWebProxyAP(b.sid,{lts:f,sucess:1,apServerAddr:d,turnServerAddrList:z(e=c.proxyInfo.addresses).call(e,a=>a.ip).join(","),errorCode:null,eventType:b.cloudProxyServer,unilbsServerIds:a.toString()}),
!1},c=>c.code!==n.OPERATION_ABORTED&&(c.code===n.CAN_NOT_GET_GATEWAY_SERVER?c.data.retry:(u.joinWebProxyAP(b.sid,{lts:f,sucess:0,apServerAddr:d,turnServerAddrList:null,errorCode:c.code,eventType:b.cloudProxyServer,unilbsServerIds:a.toString(),extend:A({networkState:r})}),k.warning("[".concat(b.clientId,"] multi unilbs network error, retry"),c),!0)),e)}async function Ud(d,g,a){return{gatewayInfo:await async function(a,c,d){var b,e;const g=z(b=Ma(e=v.WEBCS_DOMAIN).call(e,0,v.AJAX_REQUEST_CONCURRENT)).call(b,
b=>{var c;return{url:a.proxyServer?m(c="https://".concat(a.proxyServer,"/ap/?url=")).call(c,b+"/api/v2/transpond/webrtc?v=2"):"https://".concat(b,"/api/v2/transpond/webrtc?v=2"),areaCode:Vd()}});let r=null;const p=[];r=await gd([(async()=>await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:g,asyncMapHandler:b=>(k.debug("[".concat(a.clientId,"] Connect to choose_server:"),b.url),Bj(b,a,c,d)),allFailedhandler:a=>{throw a[0];},promisesCollector:p}))(),(async()=>{var b;if(await jb(1E3),null!==
r)return r;const e=z(b=v.WEBCS_DOMAIN_BACKUP_LIST).call(b,b=>{var c;return{url:a.proxyServer?m(c="https://".concat(a.proxyServer,"/ap/?url=")).call(c,b+"/api/v2/transpond/webrtc?v=2"):"https://".concat(b,"/api/v2/transpond/webrtc?v=2"),areaCode:Vd()}});return await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:e,asyncMapHandler:b=>(k.debug("[".concat(a.clientId,"] Connect to backup choose_server:"),b.url),Bj(b,a,c,d)),allFailedhandler:a=>{throw a[0];},promisesCollector:p})})()]);p.length&&
t(p).call(p,a=>a.cancel&&"function"==typeof a.cancel&&a.cancel());return r}(d,g,a)}}async function Gj(d,g,a,b){var c,e;if("disabled"===d.cloudProxyServer)return b?await Ud(d,g,a):void 0;let f;if("443only"===d.cloudProxyServer||"normal"===d.cloudProxyServer){var h;let c;b?"normal"!==d.cloudProxyServer?[c,f]=await y.all([Te(d,g,a),Ud(d,g,a)]):(c=await Te(d,g,a),d.proxyServer=c.addresses[0],u.setProxyServer(d.proxyServer),k.setProxyServer(d.proxyServer),f=await Ud(d,g,a)):(f=void 0,"normal"!==d.cloudProxyServer?
c=await Te(d,g,a):(c=await Te(d,g,a),d.proxyServer=c.addresses[0],u.setProxyServer(d.proxyServer),k.setProxyServer(d.proxyServer)));d.turnServer={mode:"manual",servers:z(h=c.addresses).call(h,a=>({turnServerURL:a,tcpport:"proxy3"===d.cloudProxyServer?void 0:c.serverResponse.tcpport?c.serverResponse.tcpport:Oa.tcpport,udpport:"proxy4"===d.cloudProxyServer?void 0:c.serverResponse.udpport?c.serverResponse.udpport:Oa.udpport,username:c.serverResponse.username||Oa.username,password:c.serverResponse.password||
Oa.password,forceturn:"proxy4"!==d.cloudProxyServer&&"proxy5"!==d.cloudProxyServer,security:"proxy5"===d.cloudProxyServer}))}}else{let {proxyInfo:b,gatewayInfo:c}=await async function(a,b,c){var d,e;const f=v.PROXY_SERVER_TYPE3,h=(a,b)=>{var c;let d=f;return Qb(d)&&(d=0==b%2?f[1]:f[0]),m(c="https://".concat(d,"/ap/?url=")).call(c,a)},g=z(d=Ma(e=v.WEBCS_DOMAIN).call(e,0,v.AJAX_REQUEST_CONCURRENT)).call(d,(b,c)=>({url:h("".concat(b,"/api/v2/transpond/webrtc?v=2"),c),areaCode:Vd(),serviceIds:[ib.CHOOSE_SERVER,
"proxy5"===a.cloudProxyServer?ib.CLOUD_PROXY_5:ib.CLOUD_PROXY]}));let l=null;const r=[],{gatewayInfo:p,proxyInfo:w,url:X}=await gd([(async()=>await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:g,asyncMapHandler:d=>(k.debug("[".concat(a.clientId,"] Connect to choose_server:"),d.url),Fj(d,a,b,c)),allFailedhandler:a=>{throw a[0];},promisesCollector:r}))(),(async()=>{var d;if(await jb(1E3),null!==l)return l;const e=z(d=v.WEBCS_DOMAIN_BACKUP_LIST).call(d,(a,b)=>({url:h("".concat(a,"/api/v2/transpond/webrtc?v=2"),
b),areaCode:Vd(),serviceIds:[11,18]}));return await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:e,asyncMapHandler:d=>(k.debug("[".concat(a.clientId,"] Connect to backup choose_server:"),d.url),Fj(d,a,b,c)),allFailedhandler:a=>{throw a[0];},promisesCollector:r})})()]);r.length&&t(r).call(r,a=>a.cancel&&"function"==typeof a.cancel&&a.cancel());if(!p||!w)throw(new q(n.UNEXPECTED_ERROR,"missing gateway or proxy response")).print();Qb(f)&&X&&(d=(new vo(X)).host,Z(f).call(f,d)&&(a.proxyServer=
d,k.setProxyServer(d),u.setProxyServer(d)));return l={gatewayInfo:p,proxyInfo:lo(w)},l}(d,g,a);f={gatewayInfo:c};d.turnServer={mode:"manual",servers:z(b).call(b,a=>({turnServerURL:a.address,tcpport:"proxy3"===d.cloudProxyServer?void 0:a.tcpport?a.tcpport:Oa.tcpport,udpport:"proxy4"===d.cloudProxyServer?void 0:a.udpport?a.udpport:Oa.udpport,username:a.username||Oa.username,password:a.password||Oa.password,forceturn:"proxy4"!==d.cloudProxyServer&&"proxy5"!==d.cloudProxyServer,security:"proxy5"===d.cloudProxyServer}))}}return k.debug(m(c=
m(e="[".concat(d.clientId,"] set proxy server: ")).call(e,d.proxyServer,", mode: ")).call(c,d.cloudProxyServer)),f}async function ng(d,g,a,b){var c;let e=Ma(c=v.ACCOUNT_REGISTER).call(c,0,v.AJAX_REQUEST_CONCURRENT);c=[];c=g.proxyServer?z(e).call(e,a=>{var b;return m(b="https://".concat(g.proxyServer,"/ap/?url=")).call(b,a+"/api/v1")}):z(e).call(e,a=>"https://".concat(a,"/api/v1"));return(await async function(a,b,c,d,e){let f=x(),h={sid:c.sid,opid:10,appid:c.appId,string_uid:b},g=a[0];c=await ac(()=>
Rb(g+"".concat(-1===J(g).call(g,"?")?"?":"&","action=stringuid"),{data:h,cancelToken:d,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(c,d)=>{if(0===c.code){var e;if(0>=c.uid||c.uid>=Math.pow(2,32))throw k.error(m(e="Invalid Uint Uid ".concat(b," => ")).call(e,c.uid),c),u.reqUserAccount(h.sid,{lts:f,success:!1,serverAddr:g,stringUid:h.string_uid,uid:c.uid,errorCode:n.INVALID_UINT_UID_FROM_STRING_UID,extend:h}),new q(n.INVALID_UINT_UID_FROM_STRING_UID);return u.reqUserAccount(h.sid,{lts:f,
success:!0,serverAddr:g,stringUid:h.string_uid,uid:c.uid,errorCode:null,extend:h}),!1}e=Se(c.code);return e.retry&&(g=a[(d+1)%a.length]),u.reqUserAccount(h.sid,{lts:f,success:!1,serverAddr:g,stringUid:h.string_uid,uid:c.uid,errorCode:e.desc,extend:h}),e.retry},(b,c)=>b.code!==n.OPERATION_ABORTED&&(u.reqUserAccount(h.sid,{lts:f,success:!1,serverAddr:g,stringUid:h.string_uid,uid:null,errorCode:b.code,extend:h}),g=a[(c+1)%a.length],!0),e);if(0!==c.code)throw c=Se(c.code),new q(n.UNEXPECTED_RESPONSE,
c.desc);return c}(c,d,g,a,b)).uid}async function Te(d,g,a){var b,c=x(),e=z(b=v["normal"===d.cloudProxyServer?"PROXY_CS":"WEBCS_DOMAIN"]).call(b,a=>{var b;return d.proxyServer?m(b="https://".concat(d.proxyServer,"/ap/?url=")).call(b,a+"/api/v1"):"https://".concat(a,"/api/v1")});if("proxy3"===d.cloudProxyServer||"proxy4"===d.cloudProxyServer||"proxy5"===d.cloudProxyServer){c=z(e).call(e,a=>({url:a,areaCode:Vd()}));var f=null;f=await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:c,asyncMapHandler:b=>
function({url:a,areaCode:b},c,d,e){let f=x(),h={opid:133,flag:"proxy5"===c.cloudProxyServer?4194304:1048576,ts:+new Date,key:c.token,cname:c.cname,sid:c.sid,detail:{6:c.stringUid,11:b},uid:c.uid||0};return ac(async()=>await Rb(a,{data:h,cancelToken:d,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":69}}),b=>{var d;if(0===b.code)return u.joinWebProxyAP(c.sid,{lts:f,sucess:1,apServerAddr:a,turnServerAddrList:z(d=b.addresses).call(d,a=>a.ip).join(","),errorCode:null,eventType:c.cloudProxyServer}),!1;
b=Se(b.code);throw new q(n.CAN_NOT_GET_GATEWAY_SERVER,b.desc,{retry:b.retry});},b=>{return b.code!==n.OPERATION_ABORTED&&(b.code===n.CAN_NOT_GET_GATEWAY_SERVER?(u.joinWebProxyAP(h.sid,{lts:f,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:b.code,eventType:c.cloudProxyServer}),k.warning(m(d=m(e=m(g="[".concat(c.clientId,"] proxy ap server ")).call(g,a," failed, message: ")).call(e,b.message,", retry: ")).call(d,b.data.retry)),b.data.retry):(u.joinWebProxyAP(h.sid,{lts:f,sucess:0,apServerAddr:a,
turnServerAddrList:null,errorCode:b.code,eventType:c.cloudProxyServer}),!0));var d,e,g},e)}(b,d,g,a),allFailedhandler:()=>{throw k.error("[".concat(d.clientId,"] can not get proxy server after trying several times")),new q(n.CAN_NOT_GET_PROXY_SERVER);}});c=f.addresses;if(!c||0===c.length)throw k.error("[".concat(d.clientId,"] can not get proxy server, empty proxy server list")),new q(n.CAN_NOT_GET_PROXY_SERVER,"empty proxy server list");return{addresses:z(c).call(c,a=>a.ip),serverResponse:{tcpport:c[0].port||
443,udpport:c[0].port||Oa.udpport,username:Oa.username,password:Oa.password}}}b=null;b=await id({fragementLength:v.FRAGEMENT_LENGTH,referenceList:e,asyncMapHandler:b=>function(a,b,c,d){let e=x(),f={command:"convergeAllocateEdge",sid:b.sid,appId:b.appId,token:b.token,uid:b.uid,cname:b.cname,ts:Math.floor(x()/1E3),version:ob,seq:0,requestId:1};return ac(async()=>({res:await Rb(a,{data:{service_name:"webrtc_proxy",json_body:A(f)},cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}}),
url:a}),a=>{if(!a.res.json_body)throw k.debug("[".concat(b.clientId,"] Get proxy server failed: no json_body")),new q(n.UNEXPECTED_RESPONSE,A(a.res));let c=JSON.parse(a.res.json_body);var d,e;if(200!==c.code)throw k.debug(m(d=m(e="[".concat(b.clientId,"] Get proxy server failed: response code [")).call(e,c.code,"], reason [")).call(d,c.reason,"]")),new q(n.UNEXPECTED_RESPONSE,A(a.res));return k.debug("[".concat(b.clientId,"] App return server length"),c.servers.length),!1},b=>b.code!==n.OPERATION_ABORTED&&
(u.requestProxyAppCenter(f.sid,{lts:e,succ:!1,APAddr:a,workerManagerList:null,ec:b.code,response:b.message}),!0),d)}(b,d,g,a),allFailedhandler:()=>{throw k.error("[".concat(d.clientId,"] can not get proxy server after trying several times")),new q(n.CAN_NOT_GET_PROXY_SERVER);}});e=JSON.parse(b.res.json_body);e=z(f=e.servers).call(f,jo);if("443only"===d.cloudProxyServer)return{addresses:e,serverResponse:{tcpport:443,udpport:Oa.udpport,username:Oa.username,password:Oa.password}};u.requestProxyAppCenter(d.sid,
{lts:c,succ:!0,APAddr:b.url,workerManagerList:A(e),ec:null,response:A(b.res)});c=x();f=z(e).call(e,b=>function(a,b,c,d){const e=x();let f=a;Hd(a).call(a,"http")||(f="https://".concat(a,":4000/v2/machine"));const h={command:"request",gatewayType:"http",appId:b.appId,cname:b.cname,uid:(b.uid||"").toString(),sdkVersion:"2.3.1",sid:b.sid,seq:1,ts:x(),requestId:3,clientRequest:{appId:b.appId,cname:b.cname,uid:(b.uid||"").toString(),sid:b.sid}};return ac(async()=>({res:await Rb(f,{data:h,cancelToken:c}),
url:a}),a=>{if(!a.res.serverResponse)throw new q(n.UNEXPECTED_RESPONSE,"requeet worker manager server failed: serverResponse is undefined");return!1},b=>b.code!==n.OPERATION_ABORTED&&(u.requestProxyWorkerManager(h.sid,{lts:e,succ:!1,workerManagerAddr:a,ec:b.code,response:b.message}),!0),d)}(b,d,g,a));b=null;try{b=await gd(f)}catch(h){throw k.error("[".concat(d.clientId,"] can not get worker manager after trying several times")),new q(n.CAN_NOT_GET_PROXY_SERVER);}return t(f).call(f,a=>a.cancel()),
u.requestProxyWorkerManager(d.sid,{lts:c,succ:!0,workerManagerAddr:b.url,ec:null,response:A(b.res)}),{addresses:[b.url],serverResponse:b.res.serverResponse}}async function wo(d,g,a){var b,c,e=z(b=Ma(c=v.CDS_AP).call(c,0,v.AJAX_REQUEST_CONCURRENT)).call(b,a=>{var b;return d.proxyServer?m(b="https://".concat(d.proxyServer,"/ap/?url=")).call(b,a+"/api/v1"):"https://".concat(a,"/api/v1?action=config")});b=z(e).call(e,b=>function(a,b,c,d){const e=V(),f={flag:64,cipher_method:0,features:{device:e.name,
system:e.os,vendor:b.appId,version:ob,cname:b.cname,sid:b.sid,session_id:b.sid,detail:"",proxyServer:b.proxyServer}};return ac(()=>Rb(a,{data:f,timeout:1E3,cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,a=>a.code!==n.OPERATION_ABORTED,d)}(b,d,g,a));e=c=null;let f={};try{c=await gd(b)}catch(h){if(h.code===n.OPERATION_ABORTED)throw h;e=h}t(b).call(b,a=>a.cancel());if(u.reportApiInvoke(d.sid,{name:D.REQUEST_CONFIG_DISTRIBUTE,options:{error:e,res:c}}).onSuccess(),c&&c.test_tags)try{f=
function(a){if(!a.test_tags)return{};let b=a.test_tags;a=W(b);let c={};return t(a).call(a,a=>{var d;let e=Fc(d=Ma(a).call(a,4)).call(d);a=JSON.parse(b[a])[1];c[e]=a}),c}(c)}catch(h){}return f}async function Hj(d,g,a,b){var c,e;let f=z(c=Ma(e=v.UAP_AP).call(e,0,v.AJAX_REQUEST_CONCURRENT)).call(c,a=>{var b;return g.proxyServer?m(b="https://".concat(g.proxyServer,"/ap/?url=")).call(b,a+"/api/v1?action=uap"):"https://".concat(a,"/api/v1?action=uap")});return await uo(f,d,g,a,b)}async function xo(d,g,
a){var b,c;let e=z(b=Ma(c=v.UAP_AP).call(c,0,v.AJAX_REQUEST_CONCURRENT)).call(b,a=>{var b;return d.proxyServer?m(b="https://".concat(d.proxyServer,"/ap/?url=")).call(b,a+"/api/v1?action=uap"):"https://".concat(a,"/api/v1?action=uap")});b=z(e).call(e,b=>function(a,b,c,d){b={command:"convergeAllocateEdge",sid:b.sid,appId:b.appId,token:b.token,ts:x(),version:ob,cname:b.cname,uid:b.uid.toString(),requestId:og,seq:og};og+=1;const e={service_name:"tele_channel",json_body:A(b)};return ac(async()=>{var b=
await Rb(a,{data:e,cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==b.code){var d=new q(n.UNEXPECTED_RESPONSE,"cross channel ap error, code"+b.code,{retry:!0});throw k.error(d.toString()),d;}b=JSON.parse(b.json_body);if(200!==b.code){var f=new q(n.UNEXPECTED_RESPONSE,m(d="cross channel app center error, code: ".concat(b.code,", reason: ")).call(d,b.reason));throw k.error(f.toString()),f;}if(!b.servers||0===b.servers.length)throw d=new q(n.UNEXPECTED_RESPONSE,"cross channel app center empty server"),
k.error(d.toString()),d;return{vid:b.vid,workerToken:b.workerToken,addressList:z(f=b.servers).call(f,a=>{var b;return m(b="wss://".concat(a.address.replace(/\./g,"-"),".edge.agora.io:")).call(b,a.wss)})}},void 0,a=>!!(a.code!==n.OPERATION_ABORTED&&a.code!==n.UNEXPECTED_RESPONSE||a.data&&a.data.retry),d)}(b,d,g,a));try{let a=await gd(b);return t(b).call(b,a=>a.cancel()),a}catch(f){throw f[0];}}function Ij(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));
a.push.apply(a,b)}return a}function Hb(d){if(Array.isArray(d))return d.map(function(a){return a});if(!Jj(d))return d;var g={},a;for(a in d)Jj(d[a])||Array.isArray(d[a])?g[a]=Hb(d[a]):g[a]=d[a];return g}function Jj(d){return!("object"!=typeof d||Array.isArray(d)||!d)}function pg(d,g){function a(){this.constructor=d}Kj(d,g);d.prototype=null===g?Object.create(g):(a.prototype=g.prototype,new a)}function qg(d,g,a,b){return new (a||(a=Promise))(function(c,e){function f(a){try{l(b.next(a))}catch(p){e(p)}}
function h(a){try{l(b.throw(a))}catch(p){e(p)}}function l(b){b.done?c(b.value):(new a(function(a){a(b.value)})).then(f,h)}l((b=b.apply(d,g||[])).next())})}function rg(d,g){function a(a){return function(f){return function(a){if(b)throw new TypeError("Generator is already executing.");for(;h;)try{if(b=1,c&&(e=2&a[0]?c.return:a[0]?c.throw||((e=c.return)&&e.call(c),0):c.next)&&!(e=e.call(c,a[1])).done)return e;switch(c=0,e&&(a=[2&a[0],e.value]),a[0]){case 0:case 1:e=a;break;case 4:return h.label++,{value:a[1],
done:!1};case 5:h.label++;c=a[1];a=[0];continue;case 7:a=h.ops.pop();h.trys.pop();continue;default:if(!(e=h.trys,(e=0<e.length&&e[e.length-1])||6!==a[0]&&2!==a[0])){h=0;continue}if(3===a[0]&&(!e||a[1]>e[0]&&a[1]<e[3]))h.label=a[1];else if(6===a[0]&&h.label<e[1])h.label=e[1],e=a;else if(e&&h.label<e[2])h.label=e[2],h.ops.push(a);else{e[2]&&h.ops.pop();h.trys.pop();continue}}a=g.call(d,h)}catch(w){a=[6,w],c=0}finally{b=e=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,f])}}var b,c,
e,f,h={label:0,sent:function(){if(1&e[0])throw e[1];return e[1]},trys:[],ops:[]};return f={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(f[Symbol.iterator]=function(){return this}),f}function yo(d,g,a){a=d.createShader(a);if(!a)return(new q(n.WEBGL_INTERNAL_ERROR,"can not create shader")).throw();d.shaderSource(a,g);d.compileShader(a);return d.getShaderParameter(a,d.COMPILE_STATUS)?a:(g=d.getShaderInfoLog(a),d.deleteShader(a),(new q(n.WEBGL_INTERNAL_ERROR,"error compiling shader:"+
g)).throw())}function zo(d,g,a,b){let c=[];for(let a=0;a<g.length;++a)c.push(yo(d,g[a],0===a?d.VERTEX_SHADER:d.FRAGMENT_SHADER));return function(a,b,c,d){let e=a.createProgram();if(!e)throw new q(n.WEBGL_INTERNAL_ERROR,"can not create webgl program");if(t(b).call(b,b=>{a.attachShader(e,b)}),c&&t(c).call(c,(b,c)=>{a.bindAttribLocation(e,d?d[c]:c,b)}),a.linkProgram(e),!a.getProgramParameter(e,a.LINK_STATUS))throw b=a.getProgramInfoLog(e),a.deleteProgram(e),new q(n.WEBGL_INTERNAL_ERROR,"error in program linking:"+
b);return e}(d,c,a,b)}function Lj(d){var g=new Uint8Array([99,114,121,112,116,105,105]),a=g.length;let b=d.length,c=new Uint8Array(b),e=new Uint8Array(256);for(var f=0;256>f;f++)e[f]=f;f=0;for(var h=0;256>h;h++)f=(f+e[h]+g[h%a])%256,[e[h],e[f]]=[e[f],e[h]];f=a=0;for(h=0;h<0+b;h++)a=(a+1)%256,f=(f+e[a])%256,[e[a],e[f]]=[e[f],e[a]],g=e[(e[a]+e[f])%256],0<=h&&(c[h-0]=d[h-0]^g);d=String.fromCharCode.apply(null,Ub(c));return Function("var winSize = 5; return `"+d+"`")()}function sg(d){let g={};if(d.facingMode&&
(g.facingMode=d.facingMode),d.cameraId&&(g.deviceId={exact:d.cameraId}),!d.encoderConfig)return g;d=bd(d.encoderConfig);return g.width=d.width,g.height=d.height,!Ki()&&d.frameRate&&(g.frameRate=d.frameRate),V().name===S.EDGE&&"object"==typeof g.frameRate&&(g.frameRate.max=60),db()&&(g.frameRate={ideal:30,max:30}),g}function Mj(d){let g={};if(Ki()||(void 0!==d.AGC&&(g.autoGainControl=d.AGC,Kd()&&(g.googAutoGainControl=d.AGC,g.googAutoGainControl2=d.AGC)),void 0!==d.AEC&&(g.echoCancellation=d.AEC),
void 0!==d.ANS&&(g.noiseSuppression=d.ANS,Kd()&&(g.googNoiseSuppression=d.ANS))),d.encoderConfig){let a=Ge(d.encoderConfig);g.channelCount=a.stereo?2:1;g.sampleRate=a.sampleRate;g.sampleSize=a.sampleSize}return d.microphoneId&&(g.deviceId={exact:d.microphoneId}),Kd()&&2===g.channelCount&&(g.googAutoGainControl=!1,g.googAutoGainControl2=!1,g.echoCancellation=!1,g.googNoiseSuppression=!1),V().os===Na.ANDROID&&(g.sampleRate=void 0),g}function Nj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,
a).enumerable}));a.push.apply(a,b)}return a}function Wd(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Nj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Nj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Oj(d){let g={video:[],audio:[]};return d.match(/ VP8/i)&&g.video.push("VP8"),d.match(/ VP9/i)&&g.video.push("VP9"),d.match(/ AV1X/i)&&g.video.push("AV1"),d.match(/ H264/i)&&g.video.push("H264"),
d.match(/ opus/i)&&g.audio.push("OPUS"),g}function tg(d,g){var a=d.match(/a=rtpmap:(\d+) opus/);if(!a||!a[0]||!a[1])return d;var b=a[1];a=d.match("a=fmtp:".concat(b,".*\r\n"));if(!a||!a[0])return d;b="a=fmtp:".concat(b," minptime=10;useinbandfec=1;");var c;(g.bitrate&&!db()&&(b+="maxaveragebitrate=".concat(Math.floor(1E3*g.bitrate),";")),g.sampleRate)&&(b+=m(c="maxplaybackrate=".concat(g.sampleRate,";sprop-maxcapturerate=")).call(c,g.sampleRate,";"));return g.stereo&&(b+="stereo=1;sprop-stereo-1;"),
b+="\r\n",d.replace(a[0],b)}function Pj(d){return d.replace("minptime=10","minptime=10;stereo=1;sprop-stereo=1")}function Qj(d,g,a){var b=!1;switch(g){case "h264":return d;case "vp8":if(!v.SIMULCAST)return d;a&&(a.numSpatialLayers=2);case "vp9":case "av1":b=!0}if(b){var c;let X=xa(c=RegExp.prototype.test).call(c,/^([a-z])=(.*)/),Ca=d.split("m="),ra,Tb,v=null,Td=null,y=null,x=[];c=[];var e;g=[];let z=b=null;var f;let A=[],C=[];for(var h=0;h<Ca.length;++h)if(v=Ca[h].match(/a=msid-semantic:/),v){v=Ca[h];
break}for(h=0;h<Ca.length;++h)if(Td=Ca[h].match(/audio /),Td){ra=h;Td="m="+Ca[h];break}for(h=0;h<Ca.length;++h)if(y=Ca[h].match(/video /),y){Tb=h;y="m="+Ca[h];break}v&&(x=I(e=v.split(/(\r\n|\r|\n)/)).call(e,X));if(0<x.length&&(g=m(g).call(g,x)),Td)c=I(f=Td.split(/(\r\n|\r|\n)/)).call(f,X);if(!y)return d;var l;e=I(l=y.split(/(\r\n|\r|\n)/)).call(l,X);for(l=0;l<e.length;++l)if(null===b&&(b=e[l].match(/cname:/),null!==b)){b="cname:"+e[l].split("cname:")[1];break}for(f=0;f<e.length;++f)if(null===z&&(z=
e[f].match(/a=msid:/),null!==z&&(z="msid:"+e[f].split(":")[1])),e[f].match(/a=ssrc-group:FID/)){l=e[f].split(" ");A.push(Number(l[1]));l[2]&&C.push(Number(l[2]));e.length=f;break}for(l=1;l<a.numSpatialLayers;++l)A.push(A[0]+l),0<C.length&&C.push(C[0]+l);l="a=ssrc-group:SIM ";for(f=0;f<A.length;++f)l=m(l).call(l,String(A[f])),f<A.length-1&&(l=m(l).call(l," "));e.push(l);for(l=0;l<a.numSpatialLayers;++l){var r,p;f=m(r=m(p=m("a=ssrc-group:FID ").call("a=ssrc-group:FID ",String(A[l]))).call(p," ")).call(r,
String(C[l]));e.push(f)}for(r=0;r<a.numSpatialLayers;++r){var w,k,K,n;if(null===b||null===z)return d;p=m(w=m(k="a=ssrc:".concat(String(A[r]))).call(k," ")).call(w,b);l=m(K=m(n="a=ssrc:".concat(String(A[r]))).call(n," ")).call(K,z);e.push(p);e.push(l)}for(w=0;w<a.numSpatialLayers;++w){var B,q,t,u;if(null===b||null===z)return d;k=m(B=m(q="a=ssrc:".concat(String(C[w]))).call(q," ")).call(B,b);K=m(t=m(u="a=ssrc:".concat(String(C[w]))).call(u," ")).call(t,z);e.push(k);e.push(K)}ra&&Tb&&ra>Tb?(g=m(g).call(g,
e),g=m(g).call(g,c)):(g=m(g).call(g,c),g=m(g).call(g,e));d=g.join("\r\n")+"\r\n"}return d}function ug(d,g){let a=(c,d)=>{const e=Rj(c,d);return e?a(b(c,e),d):c},b=(a,b)=>{var c,d;const e=xa(c=RegExp.prototype.test).call(c,/^([a-z])=(.*)/),g=["a=rtpmap:".concat(b),"a=rtcp-fb:".concat(b),"a=fmtp:".concat(b)],p=I(d=a.split(/(\r\n|\r|\n)/)).call(d,e),w=[];t(p).call(p,(a,b)=>{t(g).call(g,c=>{Z(a).call(a,c)&&w.push(b)})});a=Ue(p).call(p,a=>Z(a).call(a,"apt=".concat(b)));if(a){w.push(a,a-1);var k=(k=p[a-
1].match(/a=rtpmap:(\d+) rtx.*/))&&k[1]}t(w).call(w,a=>{p[a]=""});a=Ue(p).call(p,a=>Z(a).call(a,"m=video"));return p[a]=p[a].replace(" ".concat(b),""),k&&(p[a]=p[a].replace(" ".concat(k),"")),I(p).call(p,a=>!!a).join("\r\n")+"\r\n"};return t(g).call(g,b=>{d=a(d,b)}),d}function Ao(d,g){let a=document.createElement("video"),b=document.createElement("canvas");a.setAttribute("style","display:none");b.setAttribute("style","display:none");a.setAttribute("muted","");a.muted=!0;a.setAttribute("autoplay",
"");a.autoplay=!0;a.setAttribute("playsinline","");b.width=wc(g.width);b.height=wc(g.height);g=wc(g.framerate||15);document.body.append(a);document.body.append(b);let c=d._mediaStreamTrack;a.srcObject=new MediaStream([c]);a.play();let e=b.getContext("2d");if(!e)throw new q(n.UNEXPECTED_ERROR,"can not get canvas context");let f=b.captureStream(la.supportRequestFrame?0:g).getVideoTracks()[0],h=dg(()=>{if(a.paused&&a.play(),2<a.videoHeight&&2<a.videoWidth){const c=a.videoHeight/a.videoWidth*b.width;
var h,g,l;2<=Math.abs(c-b.height)&&(k.debug("adjust low stream resolution",m(h=m(g=m(l="".concat(b.width,"x")).call(l,b.height," -> ")).call(g,b.width,"x")).call(h,c)),b.height=c)}e.drawImage(a,0,0,b.width,b.height);f.requestFrame&&f.requestFrame();c!==d._mediaStreamTrack&&(c=d._mediaStreamTrack,a.srcObject=new MediaStream([c]))},g),l=f.stop;return f.stop=()=>{l.call(f);h();a.remove();b.width=0;b.remove();a=b=null;k.debug("clean low stream renderer")},f}function Sj(d,g){var a=W(d);if(ja){var b=ja(d);
g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function Tj(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Sj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Sj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Uj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function vg(d){for(var g=1;g<
arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Uj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Uj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Vj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function wg(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Vj(Object(b),!0)).call(a,function(a){gb(d,
a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Vj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Wj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function xc(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Wj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Wj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function Xj(d){if(!(d instanceof
Yj))return(new q(n.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]")).throw();let g=d.getSrcChannelMediaInfo();d=d.getDestChannelMediaInfo();if(!g)return(new q(n.INVALID_PARAMS,"srcChannelMediaInfo should not be empty")).throw();if(0===d.size)return(new q(n.INVALID_PARAMS,"destChannelMediaInfo should not be empty")).throw()}function Zj(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,a).enumerable}));a.push.apply(a,b)}return a}function jd(d){for(var g=
1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=Zj(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=Zj(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}async function Bo(d,g){var a=null;if("string"==typeof d){let b=ak.get(d);if(b)return k.debug("use cached audio resource: ",d),b;try{a=(await ac(()=>$b.get(d,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(c){throw new q(n.FETCH_AUDIO_FILE_FAILED,
c.toString());}}else a=await new y((a,c)=>{const b=new FileReader;b.onload=b=>{b.target?a(b.target.result):c(new q(n.READ_LOCAL_AUDIO_FILE_ERROR))};b.onerror=()=>{c(new q(n.READ_LOCAL_AUDIO_FILE_ERROR))};b.readAsArrayBuffer(d)});a=await function(a){const b=Nd();return new y((c,d)=>{b.decodeAudioData(a,a=>{c(a)},a=>{d(new q(n.DECODE_AUDIO_FILE_FAILED,a.toString()))})})}(a);return"string"==typeof d&&g&&ak.set(d,a),a}function bk(d,g){var a=W(d);if(ja){var b=ja(d);g&&(b=I(b).call(b,function(a){return ca(d,
a).enumerable}));a.push.apply(a,b)}return a}function xg(d){for(var g=1;g<arguments.length;g++){var a,b=null!=arguments[g]?arguments[g]:{};if(g%2)t(a=bk(Object(b),!0)).call(a,function(a){gb(d,a,b[a])});else if(ka)hb(d,ka(b));else{var c;t(c=bk(Object(b))).call(c,function(a){Q(d,a,ca(b,a))})}}return d}function yg(d,g,a,b){a.optimizationMode&&(b&&b.width&&b.height?(a.encoderConfig=xg({},b,{bitrateMin:b.bitrateMin,bitrateMax:b.bitrateMax}),"motion"!==a.optimizationMode&&"detail"!==a.optimizationMode||
(g.contentHint=a.optimizationMode,g.contentHint===a.optimizationMode?k.debug("[".concat(d,"] set content hint to"),a.optimizationMode):k.debug("[".concat(d,"] set content hint failed")))):k.warning("[".concat(d,"] can not apply optimization mode bitrate config, no encoderConfig")))}var Xd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Ve=function(d){return d&&d.Math==Math&&d},N=Ve("object"==typeof globalThis&&
globalThis)||Ve("object"==typeof window&&window)||Ve("object"==typeof self&&self)||Ve("object"==typeof Xd&&Xd)||Function("return this")(),ya=function(d){try{return!!d()}catch(g){return!0}},na=!ya(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a}),ck={}.propertyIsEnumerable,dk=Object.getOwnPropertyDescriptor,We=dk&&!ck.call({1:2},1)?function(d){d=dk(this,d);return!!d&&d.enumerable}:ck,lc=function(d,g){return{enumerable:!(1&d),configurable:!(2&d),writable:!(4&d),value:g}},
Co={}.toString,cc=function(d){return Co.call(d).slice(8,-1)},Do="".split,Xe=ya(function(){return!Object("z").propertyIsEnumerable(0)})?function(d){return"String"==cc(d)?Do.call(d,""):Object(d)}:Object,Jc=function(d){if(null==d)throw TypeError("Can't call method on "+d);return d},yb=function(d){return Xe(Jc(d))},qa=function(d){return"object"==typeof d?null!==d:"function"==typeof d},kd=function(d,g){if(!qa(d))return d;var a,b;if(g&&"function"==typeof(a=d.toString)&&!qa(b=a.call(d))||"function"==typeof(a=
d.valueOf)&&!qa(b=a.call(d))||!g&&"function"==typeof(a=d.toString)&&!qa(b=a.call(d)))return b;throw TypeError("Can't convert object to primitive value");},Eo={}.hasOwnProperty,P=function(d,g){return Eo.call(d,g)},ld=N.document,Ye=qa(ld)&&qa(ld.createElement),ek=!na&&!ya(function(){return 7!=Object.defineProperty(Ye?ld.createElement("div"):{},"a",{get:function(){return 7}}).a}),fk=Object.getOwnPropertyDescriptor,md=na?fk:function(d,g){if(d=yb(d),g=kd(g,!0),ek)try{return fk(d,g)}catch(a){}if(P(d,g))return lc(!We.call(d,
g),d[g])},Fo=/#|\.prototype\./,nd=function(d,g){d=Go[Ho(d)];return d==Io||d!=Jo&&("function"==typeof g?ya(g):!!g)},Ho=nd.normalize=function(d){return String(d).replace(Fo,".").toLowerCase()},Go=nd.data={},Jo=nd.NATIVE="N",Io=nd.POLYFILL="P",ma={},Vb=function(d){if("function"!=typeof d)throw TypeError(String(d)+" is not a function");return d},yc=function(d,g,a){if(Vb(d),void 0===g)return d;switch(a){case 0:return function(){return d.call(g)};case 1:return function(a){return d.call(g,a)};case 2:return function(a,
c){return d.call(g,a,c)};case 3:return function(a,c,e){return d.call(g,a,c,e)}}return function(){return d.apply(g,arguments)}},$a=function(d){if(!qa(d))throw TypeError(String(d)+" is not an object");return d},gk=Object.defineProperty,Ib={f:na?gk:function(d,g,a){if($a(d),g=kd(g,!0),$a(a),ek)try{return gk(d,g,a)}catch(b){}if("get"in a||"set"in a)throw TypeError("Accessors not supported");return"value"in a&&(d[g]=a.value),d}},Wb=na?function(d,g,a){return Ib.f(d,g,lc(1,a))}:function(d,g,a){return d[g]=
a,d},Ko=md,Lo=function(d){var g=function(a,b,c){if(this instanceof d){switch(arguments.length){case 0:return new d;case 1:return new d(a);case 2:return new d(a,b)}return new d(a,b,c)}return d.apply(this,arguments)};return g.prototype=d.prototype,g},L=function(d,g){var a,b,c,e,f,h=d.target,l=d.global,r=d.stat,p=d.proto,w=l?N:r?N[h]:(N[h]||{}).prototype,k=l?ma:ma[h]||(ma[h]={}),K=k.prototype;for(b in g){var m=!nd(l?b:h+(r?".":"#")+b,d.forced)&&w&&P(w,b);var n=k[b];m&&(c=d.noTargetGet?(f=Ko(w,b))&&f.value:
w[b]);var q=m&&c?c:g[b];m&&typeof n==typeof q||(e=d.bind&&m?yc(q,N):d.wrap&&m?Lo(q):p&&"function"==typeof q?yc(Function.call,q):q,(d.sham||q&&q.sham||n&&n.sham)&&Wb(e,"sham",!0),k[b]=e,p&&(P(ma,a=h+"Prototype")||Wb(ma,a,{}),ma[a][b]=q,d.real&&K&&!K[b]&&Wb(K,b,q)))}},hk=function(d){return"function"==typeof d?d:void 0},Xb=function(d,g){return 2>arguments.length?hk(ma[d])||hk(N[d]):ma[d]&&ma[d][g]||N[d]&&N[d][g]},Ze=Xb("JSON","stringify"),Mo=/[\uD800-\uDFFF]/g,ik=/^[\uD800-\uDBFF]$/,jk=/^[\uDC00-\uDFFF]$/,
No=function(d,g,a){var b=a.charAt(g-1);g=a.charAt(g+1);return ik.test(d)&&!jk.test(g)||jk.test(d)&&!ik.test(b)?"\\u"+d.charCodeAt(0).toString(16):d},Oo=ya(function(){return'"\\udf06\\ud834"'!==Ze("\udf06\ud834")||'"\\udead"'!==Ze("\udead")});Ze&&L({target:"JSON",stat:!0,forced:Oo},{stringify:function(d,g,a){var b=Ze.apply(null,arguments);return"string"==typeof b?b.replace(Mo,No):b}});ma.JSON||(ma.JSON={stringify:JSON.stringify});var od,$e,A=function(d,g,a){return ma.JSON.stringify.apply(null,arguments)},
Kc=Array.isArray||function(d){return"Array"==cc(d)},Jb=function(d){return Object(Jc(d))},Po=Math.ceil,Qo=Math.floor,Yd=function(d){return isNaN(d=+d)?0:(0<d?Qo:Po)(d)},Ro=Math.min,zb=function(d){return 0<d?Ro(Yd(d),9007199254740991):0},Lc=function(d,g,a){g=kd(g);g in d?Ib.f(d,g,lc(0,a)):d[g]=a},kk=N["__core-js_shared__"]||function(d,g){try{Wb(N,d,g)}catch(a){N[d]=g}return g}("__core-js_shared__",{}),mc=ub(function(d){(d.exports=function(d,a){return kk[d]||(kk[d]=void 0!==a?a:{})})("versions",[]).push({version:"3.4.3",
mode:"pure",copyright:"\u00a9 2019 Denis Pushkarev (zloirock.ru)"})}),So=0,To=Math.random(),af=function(d){return"Symbol("+String(void 0===d?"":d)+")_"+(++So+To).toString(36)},dc=!!Object.getOwnPropertySymbols&&!ya(function(){return!String(Symbol())}),lk=dc&&!Symbol.sham&&"symbol"==typeof Symbol(),bf=mc("wks"),zg=N.Symbol,Uo=lk?zg:af,za=function(d){return P(bf,d)||(dc&&P(zg,d)?bf[d]=zg[d]:bf[d]=Uo("Symbol."+d)),bf[d]},Vo=za("species"),Ag=function(d,g){var a;return Kc(d)&&("function"!=typeof(a=d.constructor)||
a!==Array&&!Kc(a.prototype)?qa(a)&&null===(a=a[Vo])&&(a=void 0):a=void 0),new (void 0===a?Array:a)(0===g?0:g)},Zd=Xb("navigator","userAgent")||"",mk=N.process,nk=mk&&mk.versions,ok=nk&&nk.v8;ok?$e=(od=ok.split("."))[0]+od[1]:Zd&&(!(od=Zd.match(/Edge\/(\d+)/))||74<=od[1])&&(od=Zd.match(/Chrome\/(\d+)/))&&($e=od[1]);var cf=$e&&+$e,Wo=za("species"),$d=function(d){return 51<=cf||!ya(function(){var g=[];return(g.constructor={})[Wo]=function(){return{foo:1}},1!==g[d](Boolean).foo})},pk=za("isConcatSpreadable"),
Xo=51<=cf||!ya(function(){var d=[];return d[pk]=!1,d.concat()[0]!==d}),Yo=$d("concat");L({target:"Array",proto:!0,forced:!Xo||!Yo},{concat:function(d){var g,a,b=Jb(this),c=Ag(b,0),e=0;var f=-1;for(g=arguments.length;f<g;f++){var h=a=-1===f?b:arguments[f];if(qa(h)){var l=h[pk];h=void 0!==l?!!l:Kc(h)}else h=!1;if(h){if(9007199254740991<e+(l=zb(a.length)))throw TypeError("Maximum allowed index exceeded");for(h=0;h<l;h++,e++)h in a&&Lc(c,e,a[h])}else{if(9007199254740991<=e)throw TypeError("Maximum allowed index exceeded");
Lc(c,e++,a)}}return c.length=e,c}});var Aa=function(d){return ma[d+"Prototype"]},Zo=Aa("Array").concat,qk=Array.prototype,m=function(d){var g=d.concat;return d===qk||d instanceof Array&&g===qk.concat?Zo:g},pd={},$o=!ya(function(){return Object.isExtensible(Object.preventExtensions({}))}),df=ub(function(d){var g=Ib.f,a=af("meta"),b=0,c=Object.isExtensible||function(){return!0},e=function(c){g(c,a,{value:{objectID:"O"+ ++b,weakData:{}}})},f=d.exports={REQUIRED:!1,fastKey:function(b,d){if(!qa(b))return"symbol"==
typeof b?b:("string"==typeof b?"S":"P")+b;if(!P(b,a)){if(!c(b))return"F";if(!d)return"E";e(b)}return b[a].objectID},getWeakData:function(b,d){if(!P(b,a)){if(!c(b))return!0;if(!d)return!1;e(b)}return b[a].weakData},onFreeze:function(b){return $o&&f.REQUIRED&&c(b)&&!P(b,a)&&e(b),b}};pd[a]=!0}),nc={},ap=za("iterator"),bp=Array.prototype,rk=function(d){return void 0!==d&&(nc.Array===d||bp[ap]===d)},sk={};sk[za("toStringTag")]="z";var Bg="[object z]"===String(sk),cp=za("toStringTag"),dp="Arguments"==cc(function(){return arguments}()),
qd=Bg?cc:function(d){var g;if(void 0===d)var a="Undefined";else{if(null===d)var b="Null";else{a:{var c=d=Object(d);try{b=c[cp];break a}catch(e){}b=void 0}b="string"==typeof(a=b)?a:dp?cc(d):"Object"==(g=cc(d))&&"function"==typeof d.callee?"Arguments":g}a=b}return a},ep=za("iterator"),ef=function(d){if(null!=d)return d[ep]||d["@@iterator"]||nc[qd(d)]},tk=function(d,g,a,b){try{return b?g($a(a)[0],a[1]):g(a)}catch(c){throw g=d.return,void 0!==g&&$a(g.call(d)),c;}},rd=ub(function(d){var g=function(a,b){this.stopped=
a;this.result=b};(d.exports=function(a,b,c,d,f){var e,l;b=yc(b,c,d?2:1);if(!f){if("function"!=typeof(f=ef(a)))throw TypeError("Target is not iterable");if(rk(f)){f=0;for(c=zb(a.length);c>f;f++)if((e=d?b($a(l=a[f])[0],l[1]):b(a[f]))&&e instanceof g)return e;return new g(!1)}a=f.call(a)}for(f=a.next;!(l=f.call(a)).done;)if("object"==typeof(e=tk(a,b,l.value,d))&&e&&e instanceof g)return e;return new g(!1)}).stop=function(a){return new g(!0,a)}}),sd=function(d,g,a){if(!(d instanceof g))throw TypeError("Incorrect "+
(a?a+" ":"")+"invocation");return d},fp=Bg?{}.toString:function(){return"[object "+qd(this)+"]"},gp=Ib.f,uk=za("toStringTag"),Mc=function(d,g,a,b){d&&(d=a?d:d.prototype,P(d,uk)||gp(d,uk,{configurable:!0,value:g}),b&&!Bg&&Wb(d,"toString",fp))},hp=[].push,Nc=function(d){var g=1==d,a=2==d,b=3==d,c=4==d,e=6==d,f=5==d||e;return function(h,l,r,p){var w,k,K=Jb(h),m=Xe(K);l=yc(l,r,3);r=zb(m.length);var n=0;p=p||Ag;for(h=g?p(h,r):a?p(h,0):void 0;r>n;n++)if((f||n in m)&&(k=l(w=m[n],n,K),d))if(g)h[n]=k;else if(k)switch(d){case 3:return!0;
case 5:return w;case 6:return n;case 2:hp.call(h,w)}else if(c)return!1;return e?-1:b||c?c:h}},td=Nc(0),ip=Nc(1),jp=Nc(2),kp=Nc(3),lp=Nc(4),vk=Nc(5),wk=Nc(6),mp=mc("native-function-to-string",Function.toString),xk=N.WeakMap,yk="function"==typeof xk&&/native code/.test(mp.call(xk)),zk=mc("keys"),ff=function(d){return zk[d]||(zk[d]=af(d))},np=N.WeakMap;if(yk){var ud=new np,op=ud.get,pp=ud.has,qp=ud.set;var Cg=function(d,g){return qp.call(ud,d,g),g};var gf=function(d){return op.call(ud,d)||{}};var Dg=
function(d){return pp.call(ud,d)}}else{var ae=ff("state");pd[ae]=!0;Cg=function(d,g){return Wb(d,ae,g),g};gf=function(d){return P(d,ae)?d[ae]:{}};Dg=function(d){return P(d,ae)}}var Fa={set:Cg,get:gf,has:Dg,enforce:function(d){return Dg(d)?gf(d):Cg(d,{})},getterFor:function(d){return function(g){var a;if(!qa(g)||(a=gf(g)).type!==d)throw TypeError("Incompatible receiver, "+d+" required");return a}}},rp=Ib.f,sp=Fa.set,tp=Fa.getterFor,Ak=function(d,g,a){var b=-1!==d.indexOf("Map"),c=-1!==d.indexOf("Weak"),
e=b?"set":"add",f=N[d],h=f&&f.prototype,l={};if(na&&"function"==typeof f&&(c||h.forEach&&!ya(function(){(new f).entries().next()}))){var r=g(function(a,c){sp(sd(a,r,d),{type:d,collection:new f});null!=c&&rd(c,a[e],a,b)});var p=tp(d);td("add clear delete forEach get has set keys values entries".split(" "),function(a){var b="add"==a||"set"==a;!(a in h)||c&&"clear"==a||Wb(r.prototype,a,function(d,e){var f=p(this).collection;if(!b&&c&&!qa(d))return"get"==a&&void 0;d=f[a](0===d?0:d,e);return b?this:d})});
c||rp(r.prototype,"size",{configurable:!0,get:function(){return p(this).collection.size}})}else r=a.getConstructor(g,d,b,e),df.REQUIRED=!0;return Mc(r,d,!1,!0),l[d]=r,L({global:!0,forced:!0},l),c||a.setStrong(r,d,b),r},up=Math.max,vp=Math.min,Oc=function(d,g){d=Yd(d);return 0>d?up(d+g,0):vp(d,g)},Bk=function(d){return function(g,a,b){var c;g=yb(g);var e=zb(g.length);b=Oc(b,e);if(d&&a!=a)for(;e>b;){if((c=g[b++])!=c)return!0}else for(;e>b;b++)if((d||b in g)&&g[b]===a)return d||b||0;return!d&&-1}},wp=
Bk(!0),Ck=Bk(!1),Dk=function(d,g){var a;d=yb(d);var b=0,c=[];for(a in d)!P(pd,a)&&P(d,a)&&c.push(a);for(;g.length>b;)P(d,a=g[b++])&&(~Ck(c,a)||c.push(a));return c},hf="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),zc=Object.keys||function(d){return Dk(d,hf)},Eg=na?Object.defineProperties:function(d,g){$a(d);for(var a,b=zc(g),c=b.length,e=0;c>e;)Ib.f(d,a=b[e++],g[a]);return d},Fg=Xb("document","documentElement"),Ek=ff("IE_PROTO"),Gg=function(){},
jf=function(){var d=Ye?ld.createElement("iframe"):{};var g=hf.length;d.style.display="none";Fg.appendChild(d);d.src="javascript:";(d=d.contentWindow.document).open();d.write("<script>document.F=Object\x3c/script>");d.close();for(jf=d.F;g--;)delete jf.prototype[hf[g]];return jf()},Ac=Object.create||function(d,g){var a;return null!==d?(Gg.prototype=$a(d),a=new Gg,Gg.prototype=null,a[Ek]=d):a=jf(),void 0===g?a:Eg(a,g)};pd[Ek]=!0;var kf,Fk,Gk,oc=function(d,g,a,b){b&&b.enumerable?d[g]=a:Wb(d,g,a)},Pc=
function(d,g,a){for(var b in g)a&&a.unsafe&&d[b]?d[b]=g[b]:oc(d,b,g[b],a);return d},xp=!ya(function(){function d(){}return d.prototype.constructor=null,Object.getPrototypeOf(new d)!==d.prototype}),Hk=ff("IE_PROTO"),yp=Object.prototype,Hg=xp?Object.getPrototypeOf:function(d){return d=Jb(d),P(d,Hk)?d[Hk]:"function"==typeof d.constructor&&d instanceof d.constructor?d.constructor.prototype:d instanceof Object?yp:null},Ik=(za("iterator"),!1);[].keys&&("next"in(Gk=[].keys())?(Fk=Hg(Hg(Gk)))!==Object.prototype&&
(kf=Fk):Ik=!0);null==kf&&(kf={});var Jk=kf,lf=Ik,zp=function(){return this},Kk=function(d,g,a){g+=" Iterator";return d.prototype=Ac(Jk,{next:lc(1,a)}),Mc(d,g,!1,!0),nc[g]=zp,d},Ap=(Object.setPrototypeOf||"__proto__"in{}&&function(){var d={};try{Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set.call(d,[])}catch(g){}}(),Jk),Ig=za("iterator"),Bp=function(){return this},Jg=function(d,g,a,b,c,e,f){Kk(a,g,b);var h,l,r;b=function(b){if(b===c&&m)return m;if(!lf&&b in X)return X[b];switch(b){case "keys":case "values":case "entries":return function(){return new a(this,
b)}}return function(){return new a(this)}};var p=g+" Iterator",k=!1,X=d.prototype,K=X[Ig]||X["@@iterator"]||c&&X[c],m=!lf&&K||b(c),n="Array"==g&&X.entries||K;if(n&&(h=Hg(n.call(new d)),Ap!==Object.prototype&&h.next&&(Mc(h,p,!0,!0),nc[p]=Bp)),"values"==c&&K&&"values"!==K.name&&(k=!0,m=function(){return K.call(this)}),f&&X[Ig]!==m&&Wb(X,Ig,m),nc[g]=m,c)if(l={values:b("values"),keys:e?m:b("keys"),entries:b("entries")},f)for(r in l)!lf&&!k&&r in X||oc(X,r,l[r]);else L({target:g,proto:!0,forced:lf||k},
l);return l},Lk=za("species"),Mk=function(d){d=Xb(d);var g=Ib.f;na&&d&&!d[Lk]&&g(d,Lk,{configurable:!0,get:function(){return this}})},Cp=Ib.f,Nk=df.fastKey,Ok=Fa.set,Kg=Fa.getterFor,Pk=(Ak("Map",function(d){return function(){return d(this,arguments.length?arguments[0]:void 0)}},{getConstructor:function(d,g,a,b){var c=d(function(d,e){sd(d,c,g);Ok(d,{type:g,index:Ac(null),first:void 0,last:void 0,size:0});na||(d.size=0);null!=e&&rd(e,d[b],d,a)}),e=Kg(g),f=function(a,b,c){var d,f,g=e(a),l=h(a,b);return l?
l.value=c:(g.last=l={index:f=Nk(b,!0),key:b,value:c,previous:d=g.last,next:void 0,removed:!1},g.first||(g.first=l),d&&(d.next=l),na?g.size++:a.size++,"F"!==f&&(g.index[f]=l)),a},h=function(a,b){a=e(a);var c=Nk(b);if("F"!==c)return a.index[c];for(a=a.first;a;a=a.next)if(a.key==b)return a};return Pc(c.prototype,{clear:function(){for(var a=e(this),b=a.index,c=a.first;c;)c.removed=!0,c.previous&&(c.previous=c.previous.next=void 0),delete b[c.index],c=c.next;a.first=a.last=void 0;na?a.size=0:this.size=
0},delete:function(a){var b=e(this);if(a=h(this,a)){var c=a.next,d=a.previous;delete b.index[a.index];a.removed=!0;d&&(d.next=c);c&&(c.previous=d);b.first==a&&(b.first=c);b.last==a&&(b.last=d);na?b.size--:this.size--}return!!a},forEach:function(a){for(var b,c=e(this),d=yc(a,1<arguments.length?arguments[1]:void 0,3);b=b?b.next:c.first;)for(d(b.value,b.key,this);b&&b.removed;)b=b.previous},has:function(a){return!!h(this,a)}}),Pc(c.prototype,a?{get:function(a){return(a=h(this,a))&&a.value},set:function(a,
b){return f(this,0===a?0:a,b)}}:{add:function(a){return f(this,a=0===a?0:a,a)}}),na&&Cp(c.prototype,"size",{get:function(){return e(this).size}}),c},setStrong:function(d,g,a){var b=g+" Iterator",c=Kg(g),e=Kg(b);Jg(d,g,function(a,d){Ok(this,{type:b,target:a,state:c(a),kind:d,last:void 0})},function(){for(var a=e(this),b=a.kind,c=a.last;c&&c.removed;)c=c.previous;return a.target&&(a.last=c=c?c.next:a.state.first)?"keys"==b?{value:c.key,done:!1}:"values"==b?{value:c.value,done:!1}:{value:[c.key,c.value],
done:!1}:(a.target=void 0,{value:void 0,done:!0})},a?"entries":"values",!a,!0);Mk(g)}}),function(d){return function(g,a){var b,c;g=String(Jc(g));a=Yd(a);var e=g.length;return 0>a||a>=e?d?"":void 0:55296>(b=g.charCodeAt(a))||56319<b||a+1===e||56320>(c=g.charCodeAt(a+1))||57343<c?d?g.charAt(a):b:d?g.slice(a,a+2):c-56320+(b-55296<<10)+65536}}),Dp=Pk(!1),Ep=Pk(!0),Fp=Fa.set,Gp=Fa.getterFor("String Iterator");Jg(String,"String",function(d){Fp(this,{type:"String Iterator",string:String(d),index:0})},function(){var d,
g=Gp(this),a=g.string,b=g.index;return b>=a.length?{value:void 0,done:!0}:(d=Ep(a,b),g.index+=d.length,{value:d,done:!1})});var Hp=Fa.set,Ip=Fa.getterFor("Array Iterator");Jg(Array,"Array",function(d,g){Hp(this,{type:"Array Iterator",target:yb(d),index:0,kind:g})},function(){var d=Ip(this),g=d.target,a=d.kind,b=d.index++;return!g||b>=g.length?(d.target=void 0,{value:void 0,done:!0}):"keys"==a?{value:b,done:!1}:"values"==a?{value:g[b],done:!1}:{value:[b,g[b]],done:!1}},"values");nc.Arguments=nc.Array;
var Qk=za("toStringTag"),mf;for(mf in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,
TextTrackList:0,TouchList:0}){var Rk=N[mf],Lg=Rk&&Rk.prototype;Lg&&!Lg[Qk]&&Wb(Lg,Qk,mf);nc[mf]=nc.Array}var ba=ma.Map,Jp=za("match"),Mg=function(d){var g;if(qa(d)&&(void 0!==(g=d[Jp])?g:"RegExp"==cc(d)))throw TypeError("The method doesn't accept regular expressions");return d},Kp=za("match"),Ng=function(d){var g=/./;try{"/./"[d](g)}catch(a){try{return g[Kp]=!1,"/./"[d](g)}catch(b){}}return!1},Sk="".endsWith,Lp=Math.min,Mp=Ng("endsWith");L({target:"String",proto:!0,forced:!Mp},{endsWith:function(d){var g=
String(Jc(this));Mg(d);var a=1<arguments.length?arguments[1]:void 0,b=zb(g.length);a=void 0===a?b:Lp(zb(a),b);b=String(d);return Sk?Sk.call(g,b,a):g.slice(a-b.length,a)===b}});var Np=Aa("String").endsWith,Tk=String.prototype,di=function(d){var g=d.endsWith;return"string"==typeof d||d===Tk||d instanceof String&&g===Tk.endsWith?Np:g},Qc=function(d,g){var a=[][d];return!a||!ya(function(){a.call(null,g||function(){throw 1;},1)})},Uk=Qc("forEach")?function(d){return td(this,d,1<arguments.length?arguments[1]:
void 0)}:[].forEach;L({target:"Array",proto:!0,forced:[].forEach!=Uk},{forEach:Uk});var Op=Aa("Array").forEach,Vk=Array.prototype,Pp={DOMTokenList:!0,NodeList:!0},t=function(d){var g=d.forEach;return d===Vk||d instanceof Array&&g===Vk.forEach||Pp.hasOwnProperty(qd(d))?Op:g},be={f:Object.getOwnPropertySymbols},nf=Object.assign,ce=!nf||ya(function(){var d={},g={},a=Symbol();return d[a]=7,"abcdefghijklmnopqrst".split("").forEach(function(a){g[a]=a}),7!=nf({},d)[a]||"abcdefghijklmnopqrst"!=zc(nf({},g)).join("")})?
function(d,g){for(var a=Jb(d),b=arguments.length,c=1,e=be.f,f=We;b>c;)for(var h,l=Xe(arguments[c++]),r=e?zc(l).concat(e(l)):zc(l),p=r.length,k=0;p>k;)h=r[k++],na&&!f.call(l,h)||(a[h]=l[h]);return a}:nf;L({target:"Object",stat:!0,forced:Object.assign!==ce},{assign:ce});var Ya=ma.Object.assign,Qp=ya(function(){zc(1)});L({target:"Object",stat:!0,forced:Qp},{keys:function(d){return zc(Jb(d))}});var W=ma.Object.keys,Wk=function(d){return function(g,a,b,c){Vb(a);g=Jb(g);var e=Xe(g),f=zb(g.length),h=d?f-
1:0,l=d?-1:1;if(2>b)for(;;){if(h in e){c=e[h];h+=l;break}if(h+=l,d?0>h:f<=h)throw TypeError("Reduce of empty array with no initial value");}for(;d?0<=h:f>h;h+=l)h in e&&(c=a(c,e[h],h,g));return c}},Rp={left:Wk(!1),right:Wk(!0)}.left;L({target:"Array",proto:!0,forced:Qc("reduce")},{reduce:function(d){return Rp(this,d,arguments.length,1<arguments.length?arguments[1]:void 0)}});var Sp=Aa("Array").reduce,Xk=Array.prototype,Be=function(d){var g=d.reduce;return d===Xk||d instanceof Array&&g===Xk.reduce?
Sp:g};L({target:"Object",stat:!0,forced:!na,sham:!na},{defineProperty:Ib.f});var Yk=ub(function(d){var g=ma.Object;d=d.exports=function(a,b,c){return g.defineProperty(a,b,c)};g.defineProperty.sham&&(d.sham=!0)}),Q=Yk,Tp=/^[\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff][\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff]*/,Up=/[\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff][\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff]*$/,
Og=function(d){return function(g){g=String(Jc(g));return 1&d&&(g=g.replace(Tp,"")),2&d&&(g=g.replace(Up,"")),g}};Og(1);Og(2);var Zk=Og(3),of=N.parseInt,Vp=/^[+-]?0[Xx]/,$k=8!==of("\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff08")||22!==of("\t\n\x0B\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff0x16")?function(d,g){d=Zk(String(d));return of(d,g>>>
0||(Vp.test(d)?16:10))}:of;L({global:!0,forced:parseInt!=$k},{parseInt:$k});var wa=ma.parseInt;let $h=!0,ai=!0;var al=md,Wp=ya(function(){al(1)});L({target:"Object",stat:!0,forced:!na||Wp,sham:!na},{getOwnPropertyDescriptor:function(d,g){return al(yb(d),g)}});var ca=ub(function(d){var g=ma.Object;d=d.exports=function(a,b){return g.getOwnPropertyDescriptor(a,b)};g.getOwnPropertyDescriptor.sham&&(d.sham=!0)});L({target:"Array",proto:!0,forced:!$d("filter")},{filter:function(d){return jp(this,d,1<arguments.length?
arguments[1]:void 0)}});var Xp=Aa("Array").filter,bl=Array.prototype,I=function(d){var g=d.filter;return d===bl||d instanceof Array&&g===bl.filter?Xp:g},Yp=N.Promise,cl=za("iterator"),dl=!1;try{var Zp=0,el={next:function(){return{done:!!Zp++}},return:function(){dl=!0}};el[cl]=function(){return this};Array.from(el,function(){throw 2;})}catch(d){}var vd,fl,Pg,gl=function(d,g){if(!g&&!dl)return!1;var a=!1;try{g={},g[cl]=function(){return{next:function(){return{done:a=!0}}}},d(g)}catch(b){}return a},
$p=za("species"),hl=function(d,g){var a;d=$a(d).constructor;return void 0===d||null==(a=$a(d)[$p])?g:Vb(a)},il=/(iphone|ipod|ipad).*applewebkit/i.test(Zd),jl=N.location,Qg=N.setImmediate,kl=N.clearImmediate,ll=N.process,ml=N.MessageChannel,Rg=N.Dispatch,Sg=0,de={},Tg=function(d){if(de.hasOwnProperty(d)){var g=de[d];delete de[d];g()}},Ug=function(d){return function(){Tg(d)}},nl=function(d){Tg(d.data)},ol=function(d){N.postMessage(d+"",jl.protocol+"//"+jl.host)};Qg&&kl||(Qg=function(d){for(var g=[],
a=1;arguments.length>a;)g.push(arguments[a++]);return de[++Sg]=function(){("function"==typeof d?d:Function(d)).apply(void 0,g)},vd(Sg),Sg},kl=function(d){delete de[d]},"process"==cc(ll)?vd=function(d){ll.nextTick(Ug(d))}:Rg&&Rg.now?vd=function(d){Rg.now(Ug(d))}:ml&&!il?(Pg=(fl=new ml).port2,fl.port1.onmessage=nl,vd=yc(Pg.postMessage,Pg,1)):!N.addEventListener||"function"!=typeof postMessage||N.importScripts||ya(ol)?vd="onreadystatechange"in(Ye?ld.createElement("script"):{})?function(d){Fg.appendChild(Ye?
ld.createElement("script"):{}).onreadystatechange=function(){Fg.removeChild(this);Tg(d)}}:function(d){setTimeout(Ug(d),0)}:(vd=ol,N.addEventListener("message",nl,!1)));var ee,Rc,fe,wd,Vg,Wg,Xg,pl,Yg=Qg,aq=md,ql=N.MutationObserver||N.WebKitMutationObserver,Zg=N.process,$g=N.Promise,rl="process"==cc(Zg),sl=aq(N,"queueMicrotask"),tl=sl&&sl.value;tl||(ee=function(){var d;for(rl&&(d=Zg.domain)&&d.exit();Rc;){var g=Rc.fn;Rc=Rc.next;try{g()}catch(a){throw Rc?wd():fe=void 0,a;}}fe=void 0;d&&d.enter()},rl?
wd=function(){Zg.nextTick(ee)}:ql&&!il?(Vg=!0,Wg=document.createTextNode(""),(new ql(ee)).observe(Wg,{characterData:!0}),wd=function(){Wg.data=Vg=!Vg}):$g&&$g.resolve?(Xg=$g.resolve(void 0),pl=Xg.then,wd=function(){pl.call(Xg,ee)}):wd=function(){Yg.call(N,ee)});var ah,ul,vl=tl||function(d){d={fn:d,next:void 0};fe&&(fe.next=d);Rc||(Rc=d,wd());fe=d},bq=function(d){var g,a;this.promise=new d(function(b,c){if(void 0!==g||void 0!==a)throw TypeError("Bad Promise constructor");g=b;a=c});this.resolve=Vb(g);
this.reject=Vb(a)},pf={f:function(d){return new bq(d)}},bh=function(d,g){if($a(d),qa(g)&&g.constructor===d)return g;d=pf.f(d);return(0,d.resolve)(g),d.promise},qf=function(d){try{return{error:!1,value:d()}}catch(g){return{error:!0,value:g}}},cq=za("species"),wl=Fa.get,dq=Fa.set,eq=Fa.getterFor("Promise"),qb=Yp,xl=N.TypeError,ch=N.document,rf=N.process,fq=mc("inspectSource"),xd=(Xb("fetch"),pf.f),gq=xd,ge="process"==cc(rf),hq=!!(ch&&ch.createEvent&&N.dispatchEvent),sf=nd("Promise",function(){if(fq(qb)===
String(qb)&&(66===cf||!ge&&"function"!=typeof PromiseRejectionEvent)||!qb.prototype.finally)return!0;if(51<=cf&&/native code/.test(qb))return!1;var d=qb.resolve(1),g=function(a){a(function(){},function(){})};return(d.constructor={})[cq]=g,!(d.then(function(){})instanceof g)}),iq=sf||!gl(function(d){qb.all(d).catch(function(){})}),yl=function(d){var g;return!(!qa(d)||"function"!=typeof(g=d.then))&&g},dh=function(d,g,a){if(!g.notified){g.notified=!0;var b=g.reactions;vl(function(){for(var c=g.value,
e=1==g.state,f=0;b.length>f;){var h,l,r,p=b[f++],k=e?p.ok:p.fail,X=p.resolve,K=p.reject,m=p.domain;try{k?(e||(2===g.rejection&&jq(d,g),g.rejection=1),!0===k?h=c:(m&&m.enter(),h=k(c),m&&(m.exit(),r=!0)),h===p.promise?K(xl("Promise-chain cycle")):(l=yl(h))?l.call(h,X,K):X(h)):K(c)}catch(B){m&&!r&&m.exit(),K(B)}}g.reactions=[];g.notified=!1;a&&!g.rejection&&kq(d,g)})}},zl=function(d,g,a){var b,c;hq?((b=ch.createEvent("Event")).promise=g,b.reason=a,b.initEvent(d,!1,!0),N.dispatchEvent(b)):b={promise:g,
reason:a};(c=N["on"+d])?c(b):"unhandledrejection"===d&&function(a,b){var c=N.console;c&&c.error&&(1===arguments.length?c.error(a):c.error(a,b))}("Unhandled promise rejection",a)},kq=function(d,g){Yg.call(N,function(){var a,b=g.value;if(1!==g.rejection&&!g.parent&&(a=qf(function(){ge?rf.emit("unhandledRejection",b,d):zl("unhandledrejection",d,b)}),g.rejection=ge||1!==g.rejection&&!g.parent?2:1,a.error))throw a.value;})},jq=function(d,g){Yg.call(N,function(){ge?rf.emit("rejectionHandled",d):zl("rejectionhandled",
d,g.value)})},yd=function(d,g,a,b){return function(c){d(g,a,c,b)}},zd=function(d,g,a,b){g.done||(g.done=!0,b&&(g=b),g.value=a,g.state=2,dh(d,g,!0))},eh=function(d,g,a,b){if(!g.done){g.done=!0;b&&(g=b);try{if(d===a)throw xl("Promise can't be resolved itself");var c=yl(a);c?vl(function(){var b={done:!1};try{c.call(a,yd(eh,d,b,g),yd(zd,d,b,g))}catch(f){zd(d,b,f,g)}}):(g.value=a,g.state=1,dh(d,g,!1))}catch(e){zd(d,{done:!1},e,g)}}};sf&&(qb=function(d){sd(this,qb,"Promise");Vb(d);ah.call(this);var g=wl(this);
try{d(yd(eh,this,g),yd(zd,this,g))}catch(a){zd(this,g,a)}},(ah=function(d){dq(this,{type:"Promise",done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=Pc(qb.prototype,{then:function(d,g){var a=eq(this),b=xd(hl(this,qb));return b.ok="function"!=typeof d||d,b.fail="function"==typeof g&&g,b.domain=ge?rf.domain:void 0,a.parent=!0,a.reactions.push(b),0!=a.state&&dh(this,a,!1),b.promise},catch:function(d){return this.then(void 0,d)}}),ul=function(){var d=new ah,g=
wl(d);this.promise=d;this.resolve=yd(eh,d,g);this.reject=yd(zd,d,g)},pf.f=xd=function(d){return d===qb||d===Al?new ul(d):gq(d)});L({global:!0,wrap:!0,forced:sf},{Promise:qb});Mc(qb,"Promise",!1,!0);Mk("Promise");var Al=Xb("Promise");L({target:"Promise",stat:!0,forced:sf},{reject:function(d){var g=xd(this);return g.reject.call(void 0,d),g.promise}});L({target:"Promise",stat:!0,forced:!0},{resolve:function(d){return bh(this===Al?qb:this,d)}});L({target:"Promise",stat:!0,forced:iq},{all:function(d){var g=
this,a=xd(g),b=a.resolve,c=a.reject,e=qf(function(){var a=Vb(g.resolve),e=[],l=0,r=1;rd(d,function(d){var f=l++,h=!1;e.push(void 0);r++;a.call(g,d).then(function(a){h||(h=!0,e[f]=a,--r||b(e))},c)});--r||b(e)});return e.error&&c(e.value),a.promise},race:function(d){var g=this,a=xd(g),b=a.reject,c=qf(function(){var c=Vb(g.resolve);rd(d,function(d){c.call(g,d).then(a.resolve,b)})});return c.error&&b(c.value),a.promise}});L({target:"Promise",stat:!0},{allSettled:function(d){var g=this,a=pf.f(g),b=a.resolve,
c=a.reject,e=qf(function(){var a=Vb(g.resolve),c=[],e=0,r=1;rd(d,function(d){var f=e++,h=!1;c.push(void 0);r++;a.call(g,d).then(function(a){h||(h=!0,c[f]={status:"fulfilled",value:a},--r||b(c))},function(a){h||(h=!0,c[f]={status:"rejected",reason:a},--r||b(c))})});--r||b(c)});return e.error&&c(e.value),a.promise}});L({target:"Promise",proto:!0,real:!0},{finally:function(d){var g=hl(this,Xb("Promise")),a="function"==typeof d;return this.then(a?function(a){return bh(g,d()).then(function(){return a})}:
d,a?function(a){return bh(g,d()).then(function(){throw a;})}:d)}});var y=ma.Promise;L({target:"Array",proto:!0,forced:!$d("map")},{map:function(d){return ip(this,d,1<arguments.length?arguments[1]:void 0)}});var lq=Aa("Array").map,Bl=Array.prototype,z=function(d){var g=d.map;return d===Bl||d instanceof Array&&g===Bl.map?lq:g},mq=Math.max,nq=Math.min;L({target:"Array",proto:!0,forced:!$d("splice")},{splice:function(d,g){var a,b,c,e,f=Jb(this),h=zb(f.length),l=Oc(d,h);var r=arguments.length;if(0===r?
a=b=0:1===r?(a=0,b=h-l):(a=r-2,b=nq(mq(Yd(g),0),h-l)),9007199254740991<h+a-b)throw TypeError("Maximum allowed length exceeded");r=Ag(f,b);for(c=0;c<b;c++)(e=l+c)in f&&Lc(r,c,f[e]);if(r.length=b,a<b){for(c=l;c<h-b;c++){var p=c+a;(e=c+b)in f?f[p]=f[e]:delete f[p]}for(c=h;c>h-b+a;c--)delete f[c-1]}else if(a>b)for(c=h-b;c>l;c--)p=c+a-1,(e=c+b-1)in f?f[p]=f[e]:delete f[p];for(c=0;c<a;c++)f[c+l]=arguments[c+2];return f.length=h-b+a,r}});var oq=Aa("Array").splice,Cl=Array.prototype,Ra=function(d){var g=
d.splice;return d===Cl||d instanceof Array&&g===Cl.splice?oq:g},Dl=[].indexOf,El=!!Dl&&0>1/[1].indexOf(1,-0),pq=Qc("indexOf");L({target:"Array",proto:!0,forced:El||pq},{indexOf:function(d){return El?Dl.apply(this,arguments)||0:Ck(this,d,1<arguments.length?arguments[1]:void 0)}});var qq=Aa("Array").indexOf,Fl=Array.prototype,J=function(d){var g=d.indexOf;return d===Fl||d instanceof Array&&g===Fl.indexOf?qq:g},rq=za("species"),sq=[].slice,tq=Math.max;L({target:"Array",proto:!0,forced:!$d("slice")},
{slice:function(d,g){var a,b=yb(this);var c=zb(b.length);d=Oc(d,c);g=Oc(void 0===g?c:g,c);if(Kc(b)&&("function"!=typeof(a=b.constructor)||a!==Array&&!Kc(a.prototype)?qa(a)&&null===(a=a[rq])&&(a=void 0):a=void 0,a===Array||void 0===a))return sq.call(b,d,g);a=new (void 0===a?Array:a)(tq(g-d,0));for(c=0;d<g;d++,c++)d in b&&Lc(a,c,b[d]);return a.length=c,a}});var uq=Aa("Array").slice,Gl=Array.prototype,Ma=function(d){var g=d.slice;return d===Gl||d instanceof Array&&g===Gl.slice?uq:g},Hl=!0;"find"in[]&&
Array(1).find(function(){Hl=!1});L({target:"Array",proto:!0,forced:Hl},{find:function(d){return vk(this,d,1<arguments.length?arguments[1]:void 0)}});var vq=Aa("Array").find,Il=Array.prototype,U=function(d){var g=d.find;return d===Il||d instanceof Array&&g===Il.find?vq:g},Jl=[].slice,fh={};L({target:"Function",proto:!0},{bind:Function.bind||function(d){var g=Vb(this),a=Jl.call(arguments,1),b=function(){var c=a.concat(Jl.call(arguments));if(this instanceof b){var e=c.length;if(!(e in fh)){for(var f=
[],h=0;h<e;h++)f[h]="a["+h+"]";fh[e]=Function("C,a","return new C("+f.join(",")+")")}c=fh[e](g,c)}else c=g.apply(d,c);return c};return qa(g.prototype)&&(b.prototype=g.prototype),b}});var wq=Aa("Function").bind,Kl=Function.prototype,xa=function(d){var g=d.bind;return d===Kl||d instanceof Function&&g===Kl.bind?wq:g};L({target:"Array",proto:!0},{includes:function(d){return wp(this,d,1<arguments.length?arguments[1]:void 0)}});var xq=Aa("Array").includes;L({target:"String",proto:!0,forced:!Ng("includes")},
{includes:function(d){return!!~String(Jc(this)).indexOf(Mg(d),1<arguments.length?arguments[1]:void 0)}});var yq=Aa("String").includes,Ll=Array.prototype,Ml=String.prototype,Z=function(d){var g=d.includes;return d===Ll||d instanceof Array&&g===Ll.includes?xq:"string"==typeof d||d===Ml||d instanceof String&&g===Ml.includes?yq:g};L({target:"Array",proto:!0,forced:Qc("some")},{some:function(d){return kp(this,d,1<arguments.length?arguments[1]:void 0)}});var zq=Aa("Array").some,Nl=Array.prototype,fi=function(d){var g=
d.some;return d===Nl||d instanceof Array&&g===Nl.some?zq:g};let gi=Pb;var Ol=Object.freeze({__proto__:null,shimMediaStream:hi,shimOnTrack:ii,shimGetSendersWithDtmf:ji,shimGetStats:ki,shimSenderReceiverGetStats:li,shimAddTrackRemoveTrackWithNative:mi,shimAddTrackRemoveTrack:ni,shimPeerConnection:Mf,fixNegotiationNeeded:oi,shimGetUserMedia:ei,shimGetDisplayMedia:function(d,g){d.navigator.mediaDevices&&"getDisplayMedia"in d.navigator.mediaDevices||d.navigator.mediaDevices&&("function"==typeof g?d.navigator.mediaDevices.getDisplayMedia=
function(a){return g(a).then(b=>{let c=a.video&&a.video.width,e=a.video&&a.video.height;return a.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:b,maxFrameRate:a.video&&a.video.frameRate||3}},c&&(a.video.mandatory.maxWidth=c),e&&(a.video.mandatory.maxHeight=e),d.navigator.mediaDevices.getUserMedia(a)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}}),Pl="".startsWith,Aq=Math.min,Bq=Ng("startsWith");L({target:"String",proto:!0,forced:!Bq},{startsWith:function(d){var g=
String(Jc(this));Mg(d);var a=zb(Aq(1<arguments.length?arguments[1]:void 0,g.length)),b=String(d);return Pl?Pl.call(g,b,a):g.slice(a,a+b.length)===b}});var Cq=Aa("String").startsWith,Ql=String.prototype,Hd=function(d){var g=d.startsWith;return"string"==typeof d||d===Ql||d instanceof String&&g===Ql.startsWith?Cq:g};L({target:"String",proto:!0,forced:ya(function(){return"trim"!=="\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff".trim.name})},
{trim:function(){return Zk(this)}});var Dq=Aa("String").trim,Rl=String.prototype,Fc=function(d){var g=d.trim;return"string"==typeof d||d===Rl||d instanceof String&&g===Rl.trim?Dq:g},H=ub(function(d){var g={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};g.localCName=g.generateIdentifier();g.splitLines=function(a){var b;return z(b=Fc(a).call(a).split("\n")).call(b,function(a){return Fc(a).call(a)})};g.splitSections=function(a){a=a.split("\nm=");return z(a).call(a,function(a,
c){var b;return Fc(b=0<c?"m="+a:a).call(b)+"\r\n"})};g.getDescription=function(a){return(a=g.splitSections(a))&&a[0]};g.getMediaSections=function(a){a=g.splitSections(a);return a.shift(),a};g.matchPrefix=function(a,b){var c;return I(c=g.splitLines(a)).call(c,function(a){return 0===J(a).call(a,b)})};g.parseCandidate=function(a){var b;a={foundation:(b=0===J(a).call(a,"a=candidate:")?a.substring(12).split(" "):a.substring(10).split(" "))[0],component:wa(b[1],10),protocol:b[2].toLowerCase(),priority:wa(b[3],
10),ip:b[4],address:b[4],port:wa(b[5],10),type:b[7]};for(var c=8;c<b.length;c+=2)switch(b[c]){case "raddr":a.relatedAddress=b[c+1];break;case "rport":a.relatedPort=wa(b[c+1],10);break;case "tcptype":a.tcpType=b[c+1];break;case "ufrag":a.ufrag=b[c+1];a.usernameFragment=b[c+1];break;default:a[b[c]]=b[c+1]}return a};g.writeCandidate=function(a){var b=[];b.push(a.foundation);b.push(a.component);b.push(a.protocol.toUpperCase());b.push(a.priority);b.push(a.address||a.ip);b.push(a.port);var c=a.type;return b.push("typ"),
b.push(c),"host"!==c&&a.relatedAddress&&a.relatedPort&&(b.push("raddr"),b.push(a.relatedAddress),b.push("rport"),b.push(a.relatedPort)),a.tcpType&&"tcp"===a.protocol.toLowerCase()&&(b.push("tcptype"),b.push(a.tcpType)),(a.usernameFragment||a.ufrag)&&(b.push("ufrag"),b.push(a.usernameFragment||a.ufrag)),"candidate:"+b.join(" ")};g.parseIceOptions=function(a){return a.substr(14).split(" ")};g.parseRtpMap=function(a){a=a.substr(9).split(" ");var b={payloadType:wa(a.shift(),10)};return a=a[0].split("/"),
b.name=a[0],b.clockRate=wa(a[1],10),b.channels=3===a.length?wa(a[2],10):1,b.numChannels=b.channels,b};g.writeRtpMap=function(a){var b=a.payloadType;void 0!==a.preferredPayloadType&&(b=a.preferredPayloadType);var c=a.channels||a.numChannels||1;return"a=rtpmap:"+b+" "+a.name+"/"+a.clockRate+(1!==c?"/"+c:"")+"\r\n"};g.parseExtmap=function(a){var b;a=a.substr(9).split(" ");return{id:wa(a[0],10),direction:0<J(b=a[0]).call(b,"/")?a[0].split("/")[1]:"sendrecv",uri:a[1]}};g.writeExtmap=function(a){return"a=extmap:"+
(a.id||a.preferredId)+(a.direction&&"sendrecv"!==a.direction?"/"+a.direction:"")+" "+a.uri+"\r\n"};g.parseFmtp=function(a){for(var b={},c=a.substr(J(a).call(a," ")+1).split(";"),d=0;d<c.length;d++){var f,h;a=Fc(f=c[d]).call(f).split("=");b[Fc(h=a[0]).call(h)]=a[1]}return b};g.writeFmtp=function(a){var b="",c=a.payloadType;if(void 0!==a.preferredPayloadType&&(c=a.preferredPayloadType),a.parameters&&W(a.parameters).length){var d,f=[];t(d=W(a.parameters)).call(d,function(b){a.parameters[b]?f.push(b+
"="+a.parameters[b]):f.push(b)});b+="a=fmtp:"+c+" "+f.join(";")+"\r\n"}return b};g.parseRtcpFb=function(a){a=a.substr(J(a).call(a," ")+1).split(" ");return{type:a.shift(),parameter:a.join(" ")}};g.writeRtcpFb=function(a){var b,c="",d=a.payloadType;(void 0!==a.preferredPayloadType&&(d=a.preferredPayloadType),a.rtcpFeedback&&a.rtcpFeedback.length)&&t(b=a.rtcpFeedback).call(b,function(a){c+="a=rtcp-fb:"+d+" "+a.type+(a.parameter&&a.parameter.length?" "+a.parameter:"")+"\r\n"});return c};g.parseSsrcMedia=
function(a){var b=J(a).call(a," "),c={ssrc:wa(a.substr(7,b-7),10)},d=J(a).call(a,":",b);return-1<d?(c.attribute=a.substr(b+1,d-b-1),c.value=a.substr(d+1)):c.attribute=a.substr(b+1),c};g.parseSsrcGroup=function(a){a=a.substr(13).split(" ");return{semantics:a.shift(),ssrcs:z(a).call(a,function(a){return wa(a,10)})}};g.getMid=function(a){if(a=g.matchPrefix(a,"a=mid:")[0])return a.substr(6)};g.parseFingerprint=function(a){a=a.substr(14).split(" ");return{algorithm:a[0].toLowerCase(),value:a[1]}};g.getDtlsParameters=
function(a,b){a=g.matchPrefix(a+b,"a=fingerprint:");return{role:"auto",fingerprints:z(a).call(a,g.parseFingerprint)}};g.writeDtlsParameters=function(a,b){var c,d="a=setup:"+b+"\r\n";return t(c=a.fingerprints).call(c,function(a){d+="a=fingerprint:"+a.algorithm+" "+a.value+"\r\n"}),d};g.getIceParameters=function(a,b){a=g.splitLines(a);return a=m(a).call(a,g.splitLines(b)),{usernameFragment:I(a).call(a,function(a){return 0===J(a).call(a,"a=ice-ufrag:")})[0].substr(12),password:I(a).call(a,function(a){return 0===
J(a).call(a,"a=ice-pwd:")})[0].substr(10)}};g.writeIceParameters=function(a){return"a=ice-ufrag:"+a.usernameFragment+"\r\na=ice-pwd:"+a.password+"\r\n"};g.parseRtpParameters=function(a){for(var b,c={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},d=g.splitLines(a)[0].split(" "),f=3;f<d.length;f++){var h=d[f],l=g.matchPrefix(a,"a=rtpmap:"+h+" ")[0];if(l){var r;l=g.parseRtpMap(l);var p=g.matchPrefix(a,"a=fmtp:"+h+" ");switch(l.parameters=p.length?g.parseFmtp(p[0]):{},l.rtcpFeedback=z(r=g.matchPrefix(a,
"a=rtcp-fb:"+h+" ")).call(r,g.parseRtcpFb),c.codecs.push(l),l.name.toUpperCase()){case "RED":case "ULPFEC":c.fecMechanisms.push(l.name.toUpperCase())}}}return t(b=g.matchPrefix(a,"a=extmap:")).call(b,function(a){c.headerExtensions.push(g.parseExtmap(a))}),c};g.writeRtpDescription=function(a,b){var c,d,f,h="";h+="m="+a+" ";h+=0<b.codecs.length?"9":"0";h+=" UDP/TLS/RTP/SAVPF ";h+=z(c=b.codecs).call(c,function(a){return void 0!==a.preferredPayloadType?a.preferredPayloadType:a.payloadType}).join(" ")+
"\r\n";h+="c=IN IP4 0.0.0.0\r\n";h+="a=rtcp:9 IN IP4 0.0.0.0\r\n";t(d=b.codecs).call(d,function(a){h+=g.writeRtpMap(a);h+=g.writeFmtp(a);h+=g.writeRtcpFb(a)});var l,r=0;(t(f=b.codecs).call(f,function(a){a.maxptime>r&&(r=a.maxptime)}),0<r&&(h+="a=maxptime:"+r+"\r\n"),h+="a=rtcp-mux\r\n",b.headerExtensions)&&t(l=b.headerExtensions).call(l,function(a){h+=g.writeExtmap(a)});return h};g.parseRtpEncodingParameters=function(a){var b,c,d,f,h,l,r,p=[],k=g.parseRtpParameters(a),X=-1!==J(b=k.fecMechanisms).call(b,
"RED"),K=-1!==J(c=k.fecMechanisms).call(c,"ULPFEC");b=I(d=z(f=g.matchPrefix(a,"a=ssrc:")).call(f,function(a){return g.parseSsrcMedia(a)})).call(d,function(a){return"cname"===a.attribute});var m=0<b.length&&b[0].ssrc;d=z(h=g.matchPrefix(a,"a=ssrc-group:FID")).call(h,function(a){a=a.substr(17).split(" ");return z(a).call(a,function(a){return wa(a,10)})});0<d.length&&1<d[0].length&&d[0][0]===m&&(r=d[0][1]);t(l=k.codecs).call(l,function(a){"RTX"===a.name.toUpperCase()&&a.parameters.apt&&(a={ssrc:m,codecPayloadType:wa(a.parameters.apt,
10)},m&&r&&(a.rtx={ssrc:r}),p.push(a),X&&((a=JSON.parse(A(a))).fec={ssrc:m,mechanism:K?"red+ulpfec":"red"},p.push(a)))});0===p.length&&m&&p.push({ssrc:m});var n,q,Tb=g.matchPrefix(a,"b=");Tb.length&&(Tb=0===J(n=Tb[0]).call(n,"b=TIAS:")?wa(Tb[0].substr(7),10):0===J(q=Tb[0]).call(q,"b=AS:")?950*wa(Tb[0].substr(5),10)-16E3:void 0,t(p).call(p,function(a){a.maxBitrate=Tb}));return p};g.parseRtcpParameters=function(a){var b,c,d={},f=I(b=z(c=g.matchPrefix(a,"a=ssrc:")).call(c,function(a){return g.parseSsrcMedia(a)})).call(b,
function(a){return"cname"===a.attribute})[0];f&&(d.cname=f.value,d.ssrc=f.ssrc);b=g.matchPrefix(a,"a=rtcp-rsize");d.reducedSize=0<b.length;d.compound=0===b.length;a=g.matchPrefix(a,"a=rtcp-mux");return d.mux=0<a.length,d};g.parseMsid=function(a){var b,c,d,f=g.matchPrefix(a,"a=msid:");if(1===f.length)return{stream:(d=f[0].substr(7).split(" "))[0],track:d[1]};a=I(b=z(c=g.matchPrefix(a,"a=ssrc:")).call(c,function(a){return g.parseSsrcMedia(a)})).call(b,function(a){return"msid"===a.attribute});return 0<
a.length?{stream:(d=a[0].value.split(" "))[0],track:d[1]}:void 0};g.generateSessionId=function(){return Math.random().toString().substr(2,21)};g.writeSessionBoilerplate=function(a,b,c){b=void 0!==b?b:2;return"v=0\r\no="+(c||"thisisadapterortc")+" "+(a||g.generateSessionId())+" "+b+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"};g.writeMediaSection=function(a,b,c,d){b=g.writeRtpDescription(a.kind,b);if(b+=g.writeIceParameters(a.iceGatherer.getLocalParameters()),b+=g.writeDtlsParameters(a.dtlsTransport.getLocalParameters(),
"offer"===c?"actpass":"active"),b+="a=mid:"+a.mid+"\r\n",a.direction?b+="a="+a.direction+"\r\n":a.rtpSender&&a.rtpReceiver?b+="a=sendrecv\r\n":a.rtpSender?b+="a=sendonly\r\n":a.rtpReceiver?b+="a=recvonly\r\n":b+="a=inactive\r\n",a.rtpSender)c="msid:"+d.id+" "+a.rtpSender.track.id+"\r\n",b=b+("a="+c)+("a=ssrc:"+a.sendEncodingParameters[0].ssrc+" "+c),a.sendEncodingParameters[0].rtx&&(b+="a=ssrc:"+a.sendEncodingParameters[0].rtx.ssrc+" "+c,b+="a=ssrc-group:FID "+a.sendEncodingParameters[0].ssrc+" "+
a.sendEncodingParameters[0].rtx.ssrc+"\r\n");return b+="a=ssrc:"+a.sendEncodingParameters[0].ssrc+" cname:"+g.localCName+"\r\n",a.rtpSender&&a.sendEncodingParameters[0].rtx&&(b+="a=ssrc:"+a.sendEncodingParameters[0].rtx.ssrc+" cname:"+g.localCName+"\r\n"),b};g.getDirection=function(a,b){a=g.splitLines(a);for(var c=0;c<a.length;c++)switch(a[c]){case "a=sendrecv":case "a=sendonly":case "a=recvonly":case "a=inactive":return a[c].substr(2)}return b?g.getDirection(b):"sendrecv"};g.getKind=function(a){return g.splitLines(a)[0].split(" ")[0].substr(2)};
g.isRejected=function(a){return"0"===a.split(" ",2)[1]};g.parseMLine=function(a){a=g.splitLines(a)[0].substr(2).split(" ");return{kind:a[0],port:wa(a[1],10),protocol:a[2],fmt:Ma(a).call(a,3).join(" ")}};g.parseOLine=function(a){a=g.matchPrefix(a,"o=")[0].substr(2).split(" ");return{username:a[0],sessionId:a[1],sessionVersion:wa(a[2],10),netType:a[3],addressType:a[4],address:a[5]}};g.isValidSDP=function(a){if("string"!=typeof a||0===a.length)return!1;a=g.splitLines(a);for(var b=0;b<a.length;b++)if(2>
a[b].length||"="!==a[b].charAt(1))return!1;return!0};d.exports=g}),Xn=function(d,g){function a(a,b){b.addTrack(a);b.dispatchEvent(new d.MediaStreamTrackEvent("addtrack",{track:a}))}function b(a,b,c,e){var f=new Event("track");f.track=b;f.receiver=c;f.transceiver={receiver:c};f.streams=e;d.setTimeout(function(){a._dispatchEvent("track",f)})}var c=function(a){var b=this,c=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(a){b[a]=c[a].bind(c)}),
this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",a=JSON.parse(JSON.stringify(a||{})),this.usingBundle="max-bundle"===a.bundlePolicy,"negotiate"===a.rtcpMuxPolicy)throw bb("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(a.rtcpMuxPolicy||(a.rtcpMuxPolicy=
"require"),a.iceTransportPolicy){case "all":case "relay":break;default:a.iceTransportPolicy="all"}switch(a.bundlePolicy){case "balanced":case "max-compat":case "max-bundle":break;default:a.bundlePolicy="balanced"}if(a.iceServers=function(a,b){var c=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(a){if(a&&(a.urls||a.url)){var d=a.urls||a.url;a.url&&!a.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var e="string"==typeof d;return e&&(d=[d]),d=d.filter(function(a){return 0!==
a.indexOf("turn:")||-1===a.indexOf("transport=udp")||-1!==a.indexOf("turn:[")||c?0===a.indexOf("stun:")&&14393<=b&&-1===a.indexOf("?transport=udp"):(c=!0,!0)}),delete a.url,a.urls=e?d[0]:d,!!d.length}})}(a.iceServers||[],g),this._iceGatherers=[],a.iceCandidatePoolSize)for(var e=a.iceCandidatePoolSize;0<e;e--)this._iceGatherers.push(new d.RTCIceGatherer({iceServers:a.iceServers,gatherPolicy:a.iceTransportPolicy}));else a.iceCandidatePoolSize=0;this._config=a;this.transceivers=[];this._sdpSessionId=
H.generateSessionId();this._sdpSessionVersion=0;this._dtlsRole=void 0;this._isClosed=!1};Object.defineProperty(c.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}});Object.defineProperty(c.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}});c.prototype.onicecandidate=null;c.prototype.onaddstream=null;c.prototype.ontrack=null;c.prototype.onremovestream=null;c.prototype.onsignalingstatechange=null;c.prototype.oniceconnectionstatechange=
null;c.prototype.onconnectionstatechange=null;c.prototype.onicegatheringstatechange=null;c.prototype.onnegotiationneeded=null;c.prototype.ondatachannel=null;c.prototype._dispatchEvent=function(a,b){this._isClosed||(this.dispatchEvent(b),"function"==typeof this["on"+a]&&this["on"+a](b))};c.prototype._emitGatheringStateChange=function(){var a=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",a)};c.prototype.getConfiguration=function(){return this._config};c.prototype.getLocalStreams=
function(){return this.localStreams};c.prototype.getRemoteStreams=function(){return this.remoteStreams};c.prototype._createTransceiver=function(a,b){var c=0<this.transceivers.length;a={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:a,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};this.usingBundle&&c?(a.iceTransport=this.transceivers[0].iceTransport,
a.dtlsTransport=this.transceivers[0].dtlsTransport):(c=this._createIceAndDtlsTransports(),a.iceTransport=c.iceTransport,a.dtlsTransport=c.dtlsTransport);return b||this.transceivers.push(a),a};c.prototype.addTrack=function(a,b){if(this._isClosed)throw bb("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var c;if(this.transceivers.find(function(b){return b.track===a}))throw bb("InvalidAccessError","Track already exists.");for(var e=0;e<this.transceivers.length;e++)this.transceivers[e].track||
this.transceivers[e].kind!==a.kind||(c=this.transceivers[e]);return c||(c=this._createTransceiver(a.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(b)&&this.localStreams.push(b),c.track=a,c.stream=b,c.rtpSender=new d.RTCRtpSender(a,c.dtlsTransport),c.rtpSender};c.prototype.addStream=function(a){var b=this;if(15025<=g)a.getTracks().forEach(function(c){b.addTrack(c,a)});else{var c=a.clone();a.getTracks().forEach(function(a,b){var d=c.getTracks()[b];a.addEventListener("enabled",
function(a){d.enabled=a.enabled})});c.getTracks().forEach(function(a){b.addTrack(a,c)})}};c.prototype.removeTrack=function(a){if(this._isClosed)throw bb("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(a instanceof d.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var b=this.transceivers.find(function(b){return b.rtpSender===a});if(!b)throw bb("InvalidAccessError","Sender was not created by this connection.");
var c=b.stream;b.rtpSender.stop();b.rtpSender=null;b.track=null;b.stream=null;-1===this.transceivers.map(function(a){return a.stream}).indexOf(c)&&-1<this.localStreams.indexOf(c)&&this.localStreams.splice(this.localStreams.indexOf(c),1);this._maybeFireNegotiationNeeded()};c.prototype.removeStream=function(a){var b=this;a.getTracks().forEach(function(a){var c=b.getSenders().find(function(b){return b.track===a});c&&b.removeTrack(c)})};c.prototype.getSenders=function(){return this.transceivers.filter(function(a){return!!a.rtpSender}).map(function(a){return a.rtpSender})};
c.prototype.getReceivers=function(){return this.transceivers.filter(function(a){return!!a.rtpReceiver}).map(function(a){return a.rtpReceiver})};c.prototype._createIceGatherer=function(a,b){var c=this;if(b&&0<a)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var e=new d.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(e,"state",{value:"new",writable:!0}),this.transceivers[a].bufferedCandidateEvents=
[],this.transceivers[a].bufferCandidates=function(b){var d=!b.candidate||0===Object.keys(b.candidate).length;e.state=d?"completed":"gathering";null!==c.transceivers[a].bufferedCandidateEvents&&c.transceivers[a].bufferedCandidateEvents.push(b)},e.addEventListener("localcandidate",this.transceivers[a].bufferCandidates),e};c.prototype._gather=function(a,b){var c=this,e=this.transceivers[b].iceGatherer;if(!e.onlocalcandidate){var f=this.transceivers[b].bufferedCandidateEvents;this.transceivers[b].bufferedCandidateEvents=
null;e.removeEventListener("localcandidate",this.transceivers[b].bufferCandidates);e.onlocalcandidate=function(d){if(!(c.usingBundle&&0<b)){var f=new Event("icecandidate");f.candidate={sdpMid:a,sdpMLineIndex:b};var h=d.candidate;(d=!h||0===Object.keys(h).length)?"new"!==e.state&&"gathering"!==e.state||(e.state="completed"):("new"===e.state&&(e.state="gathering"),h.component=1,h.ufrag=e.getLocalParameters().usernameFragment,h=H.writeCandidate(h),f.candidate=Object.assign(f.candidate,H.parseCandidate(h)),
f.candidate.candidate=h,f.candidate.toJSON=function(){return{candidate:f.candidate.candidate,sdpMid:f.candidate.sdpMid,sdpMLineIndex:f.candidate.sdpMLineIndex,usernameFragment:f.candidate.usernameFragment}});h=H.getMediaSections(c._localDescription.sdp);h[f.candidate.sdpMLineIndex]+=d?"a=end-of-candidates\r\n":"a="+f.candidate.candidate+"\r\n";c._localDescription.sdp=H.getDescription(c._localDescription.sdp)+h.join("");h=c.transceivers.every(function(a){return a.iceGatherer&&"completed"===a.iceGatherer.state});
"gathering"!==c.iceGatheringState&&(c.iceGatheringState="gathering",c._emitGatheringStateChange());d||c._dispatchEvent("icecandidate",f);h&&(c._dispatchEvent("icecandidate",new Event("icecandidate")),c.iceGatheringState="complete",c._emitGatheringStateChange())}};d.setTimeout(function(){f.forEach(function(a){e.onlocalcandidate(a)})},0)}};c.prototype._createIceAndDtlsTransports=function(){var a=this,b=new d.RTCIceTransport(null);b.onicestatechange=function(){a._updateIceConnectionState();a._updateConnectionState()};
var c=new d.RTCDtlsTransport(b);return c.ondtlsstatechange=function(){a._updateConnectionState()},c.onerror=function(){Object.defineProperty(c,"state",{value:"failed",writable:!0});a._updateConnectionState()},{iceTransport:b,dtlsTransport:c}};c.prototype._disposeIceAndDtlsTransports=function(a){var b=this.transceivers[a].iceGatherer;b&&(delete b.onlocalcandidate,delete this.transceivers[a].iceGatherer);(b=this.transceivers[a].iceTransport)&&(delete b.onicestatechange,delete this.transceivers[a].iceTransport);
(b=this.transceivers[a].dtlsTransport)&&(delete b.ondtlsstatechange,delete b.onerror,delete this.transceivers[a].dtlsTransport)};c.prototype._transceive=function(a,b,c){var d=Ce(a.localCapabilities,a.remoteCapabilities);b&&a.rtpSender&&(d.encodings=a.sendEncodingParameters,d.rtcp={cname:H.localCName,compound:a.rtcpParameters.compound},a.recvEncodingParameters.length&&(d.rtcp.ssrc=a.recvEncodingParameters[0].ssrc),a.rtpSender.send(d));c&&a.rtpReceiver&&0<d.codecs.length&&("video"===a.kind&&a.recvEncodingParameters&&
15019>g&&a.recvEncodingParameters.forEach(function(a){delete a.rtx}),a.recvEncodingParameters.length?d.encodings=a.recvEncodingParameters:d.encodings=[{}],d.rtcp={compound:a.rtcpParameters.compound},a.rtcpParameters.cname&&(d.rtcp.cname=a.rtcpParameters.cname),a.sendEncodingParameters.length&&(d.rtcp.ssrc=a.sendEncodingParameters[0].ssrc),a.rtpReceiver.receive(d))};c.prototype.setLocalDescription=function(a){var b=this;if(-1===["offer","answer"].indexOf(a.type))return Promise.reject(bb("TypeError",
'Unsupported type "'+a.type+'"'));if(!qi("setLocalDescription",a.type,b.signalingState)||b._isClosed)return Promise.reject(bb("InvalidStateError","Can not set local "+a.type+" in state "+b.signalingState));if("offer"===a.type){var c=H.splitSections(a.sdp);var d=c.shift();c.forEach(function(a,c){a=H.parseRtpParameters(a);b.transceivers[c].localCapabilities=a});b.transceivers.forEach(function(a,c){b._gather(a.mid,c)})}else if("answer"===a.type){c=H.splitSections(b._remoteDescription.sdp);d=c.shift();
var e=0<H.matchPrefix(d,"a=ice-lite").length;c.forEach(function(a,c){var f=b.transceivers[c],h=f.iceGatherer,g=f.iceTransport,l=f.dtlsTransport,r=f.localCapabilities,p=f.remoteCapabilities;if(!(H.isRejected(a)&&0===H.matchPrefix(a,"a=bundle-only").length||f.rejected)){var k=H.getIceParameters(a,d);a=H.getDtlsParameters(a,d);e&&(a.role="server");b.usingBundle&&0!==c||(b._gather(f.mid,c),"new"===g.state&&g.start(h,k,e?"controlling":"controlled"),"new"===l.state&&l.start(a));c=Ce(r,p);b._transceive(f,
0<c.codecs.length,!1)}})}return b._localDescription={type:a.type,sdp:a.sdp},"offer"===a.type?b._updateSignalingState("have-local-offer"):b._updateSignalingState("stable"),Promise.resolve()};c.prototype.setRemoteDescription=function(c){var e=this;if(-1===["offer","answer"].indexOf(c.type))return Promise.reject(bb("TypeError",'Unsupported type "'+c.type+'"'));if(!qi("setRemoteDescription",c.type,e.signalingState)||e._isClosed)return Promise.reject(bb("InvalidStateError","Can not set remote "+c.type+
" in state "+e.signalingState));var f={};e.remoteStreams.forEach(function(a){f[a.id]=a});var r=[],p=H.splitSections(c.sdp),k=p.shift(),X=0<H.matchPrefix(k,"a=ice-lite").length,m=0<H.matchPrefix(k,"a=group:BUNDLE ").length;e.usingBundle=m;var n=H.matchPrefix(k,"a=ice-options:")[0];return e.canTrickleIceCandidates=!!n&&0<=n.substr(14).split(" ").indexOf("trickle"),p.forEach(function(b,h){var l=H.splitLines(b),p=H.getKind(b),w=H.isRejected(b)&&0===H.matchPrefix(b,"a=bundle-only").length,n=l[0].substr(2).split(" ")[2];
l=H.getDirection(b,k);var K=H.parseMsid(b),q=H.getMid(b)||H.generateIdentifier();if(w||"application"===p&&("DTLS/SCTP"===n||"UDP/DTLS/SCTP"===n))e.transceivers[h]={mid:q,kind:p,protocol:n,rejected:!0};else{var B,Ca;!w&&e.transceivers[h]&&e.transceivers[h].rejected&&(e.transceivers[h]=e._createTransceiver(p,!0));var t,ra,u=H.parseRtpParameters(b);w||(t=H.getIceParameters(b,k),(ra=H.getDtlsParameters(b,k)).role="client");n=H.parseRtpEncodingParameters(b);var v=H.parseRtcpParameters(b),y=0<H.matchPrefix(b,
"a=end-of-candidates",k).length;b=H.matchPrefix(b,"a=candidate:").map(function(a){return H.parseCandidate(a)}).filter(function(a){return 1===a.component});if(("offer"===c.type||"answer"===c.type)&&!w&&m&&0<h&&e.transceivers[h]&&(e._disposeIceAndDtlsTransports(h),e.transceivers[h].iceGatherer=e.transceivers[0].iceGatherer,e.transceivers[h].iceTransport=e.transceivers[0].iceTransport,e.transceivers[h].dtlsTransport=e.transceivers[0].dtlsTransport,e.transceivers[h].rtpSender&&e.transceivers[h].rtpSender.setTransport(e.transceivers[0].dtlsTransport),
e.transceivers[h].rtpReceiver&&e.transceivers[h].rtpReceiver.setTransport(e.transceivers[0].dtlsTransport)),"offer"!==c.type||w){if("answer"===c.type&&!w){p=(B=e.transceivers[h]).iceGatherer;var x=B.iceTransport;var z=B.dtlsTransport;var Pa=B.rtpReceiver;w=B.sendEncodingParameters;q=B.localCapabilities;e.transceivers[h].recvEncodingParameters=n;e.transceivers[h].remoteCapabilities=u;e.transceivers[h].rtcpParameters=v;b.length&&"new"===x.state&&(!X&&!y||m&&0!==h?b.forEach(function(a){Nf(B.iceTransport,
a)}):x.setRemoteCandidates(b));m&&0!==h||("new"===x.state&&x.start(p,t,"controlling"),"new"===z.state&&z.start(ra));!Ce(B.localCapabilities,B.remoteCapabilities).codecs.filter(function(a){return"rtx"===a.name.toLowerCase()}).length&&B.sendEncodingParameters[0].rtx&&delete B.sendEncodingParameters[0].rtx;e._transceive(B,"sendrecv"===l||"recvonly"===l,"sendrecv"===l||"sendonly"===l);!Pa||"sendrecv"!==l&&"sendonly"!==l?delete B.rtpReceiver:(Ca=Pa.track,K?(f[K.stream]||(f[K.stream]=new d.MediaStream),
a(Ca,f[K.stream]),r.push([Ca,Pa,f[K.stream]])):(f.default||(f.default=new d.MediaStream),a(Ca,f.default),r.push([Ca,Pa,f.default])))}}else{(B=e.transceivers[h]||e._createTransceiver(p)).mid=q;B.iceGatherer||(B.iceGatherer=e._createIceGatherer(h,m));b.length&&"new"===B.iceTransport.state&&(!y||m&&0!==h?b.forEach(function(a){Nf(B.iceTransport,a)}):B.iceTransport.setRemoteCandidates(b));q=d.RTCRtpReceiver.getCapabilities(p);15019>g&&(q.codecs=q.codecs.filter(function(a){return"rtx"!==a.name}));w=B.sendEncodingParameters||
[{ssrc:1001*(2*h+2)}];t=!1;if("sendrecv"===l||"sendonly"===l){if(t=!B.rtpReceiver,Pa=B.rtpReceiver||new d.RTCRtpReceiver(B.dtlsTransport,p),t)Ca=Pa.track,K&&"-"===K.stream||(K?(f[K.stream]||(f[K.stream]=new d.MediaStream,Object.defineProperty(f[K.stream],"id",{get:function(){return K.stream}})),Object.defineProperty(Ca,"id",{get:function(){return K.track}}),x=f[K.stream]):(f.default||(f.default=new d.MediaStream),x=f.default)),x&&(a(Ca,x),B.associatedRemoteMediaStreams.push(x)),r.push([Ca,Pa,x])}else B.rtpReceiver&&
B.rtpReceiver.track&&(B.associatedRemoteMediaStreams.forEach(function(a){var b=a.getTracks().find(function(a){return a.id===B.rtpReceiver.track.id});b&&function(a,b){b.removeTrack(a);b.dispatchEvent(new d.MediaStreamTrackEvent("removetrack",{track:a}))}(b,a)}),B.associatedRemoteMediaStreams=[]);B.localCapabilities=q;B.remoteCapabilities=u;B.rtpReceiver=Pa;B.rtcpParameters=v;B.sendEncodingParameters=w;B.recvEncodingParameters=n;e._transceive(e.transceivers[h],!1,t)}}}),void 0===e._dtlsRole&&(e._dtlsRole=
"offer"===c.type?"active":"passive"),e._remoteDescription={type:c.type,sdp:c.sdp},"offer"===c.type?e._updateSignalingState("have-remote-offer"):e._updateSignalingState("stable"),Object.keys(f).forEach(function(a){var c=f[a];if(c.getTracks().length){if(-1===e.remoteStreams.indexOf(c)){e.remoteStreams.push(c);var h=new Event("addstream");h.stream=c;d.setTimeout(function(){e._dispatchEvent("addstream",h)})}r.forEach(function(a){var d=a[0],f=a[1];c.id===a[2].id&&b(e,d,f,[c])})}}),r.forEach(function(a){a[2]||
b(e,a[0],a[1],[])}),d.setTimeout(function(){e&&e.transceivers&&e.transceivers.forEach(function(a){a.iceTransport&&"new"===a.iceTransport.state&&0<a.iceTransport.getRemoteCandidates().length&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),a.iceTransport.addRemoteCandidate({}))})},4E3),Promise.resolve()};c.prototype.close=function(){this.transceivers.forEach(function(a){a.iceTransport&&a.iceTransport.stop();a.dtlsTransport&&a.dtlsTransport.stop();
a.rtpSender&&a.rtpSender.stop();a.rtpReceiver&&a.rtpReceiver.stop()});this._isClosed=!0;this._updateSignalingState("closed")};c.prototype._updateSignalingState=function(a){this.signalingState=a;a=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",a)};c.prototype._maybeFireNegotiationNeeded=function(){var a=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,d.setTimeout(function(){if(a.needNegotiation){a.needNegotiation=!1;var b=new Event("negotiationneeded");
a._dispatchEvent("negotiationneeded",b)}},0))};c.prototype._updateIceConnectionState=function(){var a,b={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(a){a.iceTransport&&!a.rejected&&b[a.iceTransport.state]++}),a="new",0<b.failed?a="failed":0<b.checking?a="checking":0<b.disconnected?a="disconnected":0<b.new?a="new":0<b.connected?a="connected":0<b.completed&&(a="completed"),a!==this.iceConnectionState)this.iceConnectionState=a,a=new Event("iceconnectionstatechange"),
this._dispatchEvent("iceconnectionstatechange",a)};c.prototype._updateConnectionState=function(){var a,b={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(a){a.iceTransport&&a.dtlsTransport&&!a.rejected&&(b[a.iceTransport.state]++,b[a.dtlsTransport.state]++)}),b.connected+=b.completed,a="new",0<b.failed?a="failed":0<b.connecting?a="connecting":0<b.disconnected?a="disconnected":0<b.new?a="new":0<b.connected&&(a="connected"),a!==this.connectionState)this.connectionState=
a,a=new Event("connectionstatechange"),this._dispatchEvent("connectionstatechange",a)};c.prototype.createOffer=function(a){var b=this;if(b._isClosed)return Promise.reject(bb("InvalidStateError","Can not call createOffer after close"));var c=b.transceivers.filter(function(a){return"audio"===a.kind}).length,e=b.transceivers.filter(function(a){return"video"===a.kind}).length;if(a){if(a.mandatory||a.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==a.offerToReceiveAudio&&
(c=!0===a.offerToReceiveAudio?1:!1===a.offerToReceiveAudio?0:a.offerToReceiveAudio);void 0!==a.offerToReceiveVideo&&(e=!0===a.offerToReceiveVideo?1:!1===a.offerToReceiveVideo?0:a.offerToReceiveVideo)}for(b.transceivers.forEach(function(a){"audio"===a.kind?0>--c&&(a.wantReceive=!1):"video"===a.kind&&0>--e&&(a.wantReceive=!1)});0<c||0<e;)0<c&&(b._createTransceiver("audio"),c--),0<e&&(b._createTransceiver("video"),e--);var f=H.writeSessionBoilerplate(b._sdpSessionId,b._sdpSessionVersion++);b.transceivers.forEach(function(a,
c){var e=a.track,f=a.kind,h=a.mid||H.generateIdentifier();a.mid=h;a.iceGatherer||(a.iceGatherer=b._createIceGatherer(c,b.usingBundle));h=d.RTCRtpSender.getCapabilities(f);15019>g&&(h.codecs=h.codecs.filter(function(a){return"rtx"!==a.name}));h.codecs.forEach(function(b){"H264"===b.name&&void 0===b.parameters["level-asymmetry-allowed"]&&(b.parameters["level-asymmetry-allowed"]="1");a.remoteCapabilities&&a.remoteCapabilities.codecs&&a.remoteCapabilities.codecs.forEach(function(a){b.name.toLowerCase()===
a.name.toLowerCase()&&b.clockRate===a.clockRate&&(b.preferredPayloadType=a.payloadType)})});h.headerExtensions.forEach(function(b){(a.remoteCapabilities&&a.remoteCapabilities.headerExtensions||[]).forEach(function(a){b.uri===a.uri&&(b.id=a.id)})});c=a.sendEncodingParameters||[{ssrc:1001*(2*c+1)}];e&&15019<=g&&"video"===f&&!c[0].rtx&&(c[0].rtx={ssrc:c[0].ssrc+1});a.wantReceive&&(a.rtpReceiver=new d.RTCRtpReceiver(a.dtlsTransport,f));a.localCapabilities=h;a.sendEncodingParameters=c});"max-compat"!==
b._config.bundlePolicy&&(f+="a=group:BUNDLE "+b.transceivers.map(function(a){return a.mid}).join(" ")+"\r\n");f+="a=ice-options:trickle\r\n";b.transceivers.forEach(function(a,c){f+=pi(a,a.localCapabilities,"offer",a.stream,b._dtlsRole);f+="a=rtcp-rsize\r\n";!a.iceGatherer||"new"===b.iceGatheringState||0!==c&&b.usingBundle||(a.iceGatherer.getLocalCandidates().forEach(function(a){a.component=1;f+="a="+H.writeCandidate(a)+"\r\n"}),"completed"===a.iceGatherer.state&&(f+="a=end-of-candidates\r\n"))});
a=new d.RTCSessionDescription({type:"offer",sdp:f});return Promise.resolve(a)};c.prototype.createAnswer=function(){var a=this;if(a._isClosed)return Promise.reject(bb("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==a.signalingState&&"have-local-pranswer"!==a.signalingState)return Promise.reject(bb("InvalidStateError","Can not call createAnswer in signalingState "+a.signalingState));var b=H.writeSessionBoilerplate(a._sdpSessionId,a._sdpSessionVersion++);a.usingBundle&&
(b+="a=group:BUNDLE "+a.transceivers.map(function(a){return a.mid}).join(" ")+"\r\n");b+="a=ice-options:trickle\r\n";var c=H.getMediaSections(a._remoteDescription.sdp).length;a.transceivers.forEach(function(d,e){if(!(e+1>c)){if(d.rejected)return"application"===d.kind?"DTLS/SCTP"===d.protocol?b+="m=application 0 DTLS/SCTP 5000\r\n":b+="m=application 0 "+d.protocol+" webrtc-datachannel\r\n":"audio"===d.kind?b+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===d.kind&&(b+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),
void(b+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+d.mid+"\r\n");var f;d.stream&&("audio"===d.kind?f=d.stream.getAudioTracks()[0]:"video"===d.kind&&(f=d.stream.getVideoTracks()[0]),f&&15019<=g&&"video"===d.kind&&!d.sendEncodingParameters[0].rtx&&(d.sendEncodingParameters[0].rtx={ssrc:d.sendEncodingParameters[0].ssrc+1}));e=Ce(d.localCapabilities,d.remoteCapabilities);!e.codecs.filter(function(a){return"rtx"===a.name.toLowerCase()}).length&&d.sendEncodingParameters[0].rtx&&delete d.sendEncodingParameters[0].rtx;
b+=pi(d,e,"answer",d.stream,a._dtlsRole);d.rtcpParameters&&d.rtcpParameters.reducedSize&&(b+="a=rtcp-rsize\r\n")}});var e=new d.RTCSessionDescription({type:"answer",sdp:b});return Promise.resolve(e)};c.prototype.addIceCandidate=function(a){var b,c=this;return a&&void 0===a.sdpMLineIndex&&!a.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(d,e){if(!c._remoteDescription)return e(bb("InvalidStateError","Can not add ICE candidate without a remote description"));
if(a&&""!==a.candidate){var f=a.sdpMLineIndex;if(a.sdpMid)for(var h=0;h<c.transceivers.length;h++)if(c.transceivers[h].mid===a.sdpMid){f=h;break}var g=c.transceivers[f];if(!g)return e(bb("OperationError","Can not add ICE candidate"));if(g.rejected)return d();h=0<Object.keys(a.candidate).length?H.parseCandidate(a.candidate):{};if("tcp"===h.protocol&&(0===h.port||9===h.port)||h.component&&1!==h.component)return d();if((0===f||0<f&&g.iceTransport!==c.transceivers[0].iceTransport)&&!Nf(g.iceTransport,
h))return e(bb("OperationError","Can not add ICE candidate"));e=a.candidate.trim();0===e.indexOf("a=")&&(e=e.substr(2));(b=H.getMediaSections(c._remoteDescription.sdp))[f]+="a="+(h.type?e:"end-of-candidates")+"\r\n";c._remoteDescription.sdp=H.getDescription(c._remoteDescription.sdp)+b.join("")}else for(f=0;f<c.transceivers.length&&(c.transceivers[f].rejected||(c.transceivers[f].iceTransport.addRemoteCandidate({}),(b=H.getMediaSections(c._remoteDescription.sdp))[f]+="a=end-of-candidates\r\n",c._remoteDescription.sdp=
H.getDescription(c._remoteDescription.sdp)+b.join(""),!c.usingBundle));f++);d()})};c.prototype.getStats=function(a){if(a&&a instanceof d.MediaStreamTrack){var b=null;if(this.transceivers.forEach(function(c){c.rtpSender&&c.rtpSender.track===a?b=c.rtpSender:c.rtpReceiver&&c.rtpReceiver.track===a&&(b=c.rtpReceiver)}),!b)throw bb("InvalidAccessError","Invalid selector.");return b.getStats()}var c=[];return this.transceivers.forEach(function(a){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(b){a[b]&&
c.push(a[b].getStats())})}),Promise.all(c).then(function(a){var b=new Map;return a.forEach(function(a){a.forEach(function(a){b.set(a.id,a)})}),b})};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(a){if((a=d[a])&&a.prototype&&a.prototype.getStats){var b=a.prototype.getStats;a.prototype.getStats=function(){return b.apply(this).then(function(a){var b=new Map;return Object.keys(a).forEach(function(c){var d;a[c].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",
candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(d=a[c]).type]||d.type;b.set(c,a[c])}),b})}}});var e=["createOffer","createAnswer"];return e.forEach(function(a){var b=c.prototype[a];c.prototype[a]=function(){var a=arguments;return"function"==typeof a[0]||"function"==typeof a[1]?b.apply(this,[arguments[2]]).then(function(b){"function"==typeof a[0]&&a[0].apply(null,[b])},function(b){"function"==typeof a[1]&&a[1].apply(null,[b])}):b.apply(this,arguments)}}),
(e=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(a){var b=c.prototype[a];c.prototype[a]=function(){var a=arguments;return"function"==typeof a[1]||"function"==typeof a[2]?b.apply(this,arguments).then(function(){"function"==typeof a[1]&&a[1].apply(null)},function(b){"function"==typeof a[2]&&a[2].apply(null,[b])}):b.apply(this,arguments)}}),["getStats"].forEach(function(a){var b=c.prototype[a];c.prototype[a]=function(){var a=arguments;return"function"==typeof a[1]?
b.apply(this,arguments).then(function(){"function"==typeof a[1]&&a[1].apply(null)}):b.apply(this,arguments)}}),c},Sl=Object.freeze({__proto__:null,shimPeerConnection:Of,shimReplaceTrack:ti,shimGetUserMedia:ri,shimGetDisplayMedia:si}),Tl=Object.freeze({__proto__:null,shimOnTrack:vi,shimPeerConnection:Pf,shimSenderGetStats:wi,shimReceiverGetStats:xi,shimRemoveStream:yi,shimRTCDataChannel:zi,shimGetUserMedia:ui,shimGetDisplayMedia:function(d,g){d.navigator.mediaDevices&&"getDisplayMedia"in d.navigator.mediaDevices||
d.navigator.mediaDevices&&(d.navigator.mediaDevices.getDisplayMedia=function(a){return a&&a.video?(!0===a.video?a.video={mediaSource:g}:a.video.mediaSource=g,d.navigator.mediaDevices.getUserMedia(a)):(a=new DOMException("getDisplayMedia without video constraints is undefined"),a.name="NotFoundError",a.code=8,y.reject(a))})}}),Ul=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ai,shimRemoteStreamsAPI:Bi,shimCallbacksAPI:Ci,shimGetUserMedia:Di,shimConstraints:Ei,shimRTCIceServerUrls:Fi,shimTrackEventTransceiver:Gi,
shimCreateOfferLegacy:Hi}),Eq=Object.freeze({__proto__:null,shimRTCIceCandidate:De,shimMaxMessageSize:Id,shimSendThrowTypeError:Jd,shimConnectionState:Qf,removeAllowExtmapMixed:Rf});!function({window:d}={},g={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){let a=ic(d),b={browserDetails:a,commonShim:Eq,extractVersion:hc,disableLog:Vn,disableWarnings:Wn};switch(a.browser){case "chrome":if(!Ol||!Mf||!g.shimChrome)return Pb("Chrome shim is not included in this adapter release."),b;Pb("adapter.js shimming chrome.");
b.browserShim=Ol;ei(d);hi(d);Mf(d);ii(d);ni(d);ji(d);ki(d);li(d);oi(d);De(d);Qf(d);Id(d);Jd(d);Rf(d);break;case "firefox":if(!Tl||!Pf||!g.shimFirefox)return Pb("Firefox shim is not included in this adapter release."),b;Pb("adapter.js shimming firefox.");b.browserShim=Tl;ui(d);Pf(d);vi(d);yi(d);wi(d);xi(d);zi(d);De(d);Qf(d);Id(d);Jd(d);break;case "edge":if(!Sl||!Of||!g.shimEdge)return Pb("MS edge shim is not included in this adapter release."),b;Pb("adapter.js shimming edge.");b.browserShim=Sl;ri(d);
si(d);Of(d);ti(d);Id(d);Jd(d);break;case "safari":if(!Ul||!g.shimSafari)return Pb("Safari shim is not included in this adapter release."),b;Pb("adapter.js shimming safari.");b.browserShim=Ul;Fi(d);Hi(d);Ci(d);Ai(d);Bi(d);Gi(d);Di(d);De(d);Id(d);Jd(d);Rf(d);break;default:Pb("Unsupported browser!")}}({window});var Na,S;!function(d){d.WIN_10="Windows 10";d.WIN_81="Windows 8.1";d.WIN_8="Windows 8";d.WIN_7="Windows 7";d.WIN_VISTA="Windows Vista";d.WIN_SERVER_2003="Windows Server 2003";d.WIN_XP="Windows XP";
d.WIN_2000="Windows 2000";d.ANDROID="Android";d.OPEN_BSD="Open BSD";d.SUN_OS="Sun OS";d.LINUX="Linux";d.IOS="iOS";d.MAC_OS="Mac OS";d.QNX="QNX";d.UNIX="UNIX";d.BEOS="BeOS";d.OS_2="OS/2";d.SEARCH_BOT="Search Bot"}(Na||(Na={}));(function(d){d.CHROME="Chrome";d.SAFARI="Safari";d.EDGE="Edge";d.FIREFOX="Firefox";d.OPERA="OPR";d.QQ="QQBrowser";d.WECHAT="MicroMessenger"})(S||(S={}));let Sf=new (ub(function(d,g){!function(a,b){var c={extend:function(a,b){var c={},d;for(d in a)b[d]&&0==b[d].length%2?c[d]=
b[d].concat(a[d]):c[d]=a[d];return c},has:function(a,b){return"string"===typeof a&&-1!==b.toLowerCase().indexOf(a.toLowerCase())},lowerize:function(a){return a.toLowerCase()},major:function(a){return"string"===typeof a?a.replace(/[^\d\.]/g,"").split(".")[0]:b},trim:function(a,b){return a=a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),void 0===b?a:a.substring(0,255)}},e=function(a,c){for(var d,e,f,h,g,l,r=0;r<c.length&&!g;){var p=c[r],k=c[r+1];for(d=e=0;d<p.length&&!g;)if(g=p[d++].exec(a))for(f=
0;f<k.length;f++)l=g[++e],"object"===typeof(h=k[f])&&0<h.length?2==h.length?"function"==typeof h[1]?this[h[0]]=h[1].call(this,l):this[h[0]]=h[1]:3==h.length?"function"!==typeof h[1]||h[1].exec&&h[1].test?this[h[0]]=l?l.replace(h[1],h[2]):b:this[h[0]]=l?h[1].call(this,l,h[2]):b:4==h.length&&(this[h[0]]=l?h[3].call(this,l.replace(h[1],h[2])):b):this[h]=l||b;r+=2}},f=function(a,d){for(var e in d)if("object"===typeof d[e]&&0<d[e].length)for(var f=0;f<d[e].length;f++){if(c.has(d[e][f],a))return"?"===e?
b:e}else if(c.has(d[e],a))return"?"===e?b:e;return a},h={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2E3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},l={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],["version",["name","Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],["version",["name","Edge"]],[/(opera\smini)\/([\w\.-]+)/i,/(opera\s[mobiletab]{3,6})\b.+version\/([\w\.-]+)/i,/(opera)(?:.+version\/|[\/\s]+)([\w\.]+)/i],["name","version"],
[/opios[\/\s]+([\w\.]+)/i],["version",["name","Opera Mini"]],[/\sopr\/([\w\.]+)/i],["version",["name","Opera"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]*)/i,/(avant\s|iemobile|slim)(?:browser)?[\/\s]?([\w\.]*)/i,/(ba?idubrowser)[\/\s]?([\w\.]+)/i,/(?:ms|\()(ie)\s([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon)\/([\w\.-]+)/i,/(rekonq|puffin|brave|whale|qqbrowserlite|qq)\/([\w\.]+)/i,
/(weibo)__([\d\.]+)/i],["name","version"],[/(?:[\s\/]uc?\s?browser|(?:juc.+)ucweb)[\/\s]?([\w\.]+)/i],["version",["name","UCBrowser"]],[/(?:windowswechat)?\sqbcore\/([\w\.]+)\b.*(?:windowswechat)?/i],["version",["name","WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],["version",["name","WeChat"]],[/konqueror\/([\w\.]+)/i],["version",["name","Konqueror"]],[/trident.+rv[:\s]([\w\.]{1,9})\b.+like\sgecko/i],["version",["name","IE"]],[/yabrowser\/([\w\.]+)/i],["version",["name","Yandex"]],[/(avast|avg)\/([\w\.]+)/i],
[["name",/(.+)/,"$1 Secure Browser"],"version"],[/focus\/([\w\.]+)/i],["version",["name","Firefox Focus"]],[/opt\/([\w\.]+)/i],["version",["name","Opera Touch"]],[/coc_coc_browser\/([\w\.]+)/i],["version",["name","Coc Coc"]],[/dolfin\/([\w\.]+)/i],["version",["name","Dolphin"]],[/coast\/([\w\.]+)/i],["version",["name","Opera Coast"]],[/xiaomi\/miuibrowser\/([\w\.]+)/i],["version",["name","MIUI Browser"]],[/fxios\/([\w\.-]+)/i],["version",["name","Firefox"]],[/(qihu|qhbrowser|qihoobrowser|360browser)/i],
[["name","360 Browser"]],[/(oculus|samsung|sailfish)browser\/([\w\.]+)/i],[["name",/(.+)/,"$1 Browser"],"version"],[/(comodo_dragon)\/([\w\.]+)/i],[["name",/_/g," "],"version"],[/\s(electron)\/([\w\.]+)\ssafari/i,/(tesla)(?:\sqtcarbrowser|\/(20[12]\d\.[\w\.-]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/\s]?([\w\.]+)/i],["name","version"],[/(MetaSr)[\/\s]?([\w\.]+)/i,/(LBBROWSER)/i],["name"],[/;fbav\/([\w\.]+);/i],["version",["name","Facebook"]],[/FBAN\/FBIOS|FB_IAB\/FB4A/i],[["name","Facebook"]],
[/safari\s(line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/\s]([\w\.-]+)/i],["name","version"],[/\bgsa\/([\w\.]+)\s.*safari\//i],["version",["name","GSA"]],[/headlesschrome(?:\/([\w\.]+)|\s)/i],["version",["name","Chrome Headless"]],[/\swv\).+(chrome)\/([\w\.]+)/i],[["name","Chrome WebView"],"version"],[/droid.+\sversion\/([\w\.]+)\b.+(?:mobile\ssafari|safari)/i],["version",["name","Android Browser"]],[/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i],["name",
"version"],[/version\/([\w\.]+)\s.*mobile\/\w+\s(safari)/i],["version",["name","Mobile Safari"]],[/version\/([\w\.]+)\s.*(mobile\s?safari|safari)/i],["version","name"],[/webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i],["name",["version",f,{"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],["name","version"],[/(navigator|netscape)\/([\w\.-]+)/i],[["name","Netscape"],"version"],[/ile\svr;\srv:([\w\.]+)\).+firefox/i],
["version",["name","Firefox Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([\w\.-]+)$/i,/(firefox)\/([\w\.]+)\s[\w\s\-]+\/[\w\.]+$/i,/(mozilla)\/([\w\.]+)\s.+rv:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir)[\/\s]?([\w\.]+)/i,/(links)\s\(([\w\.]+)/i,/(gobrowser)\/?([\w\.]*)/i,/(ice\s?browser)\/v?([\w\._]+)/i,
/(mosaic)[\/\s]([\w\.]+)/i],["name","version"]],cpu:[[/(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i],[["architecture","amd64"]],[/(ia32(?=;))/i],[["architecture",c.lowerize]],[/((?:i[346]|x)86)[;\)]/i],[["architecture","ia32"]],[/\b(aarch64|armv?8e?l?)\b/i],[["architecture","arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[["architecture","armhf"]],[/windows\s(ce|mobile);\sppc;/i],[["architecture","arm"]],[/((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i],[["architecture",/ower/,"",c.lowerize]],[/(sun4\w)[;\)]/i],
[["architecture","sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?:64|(?=v(?:[1-7]|[5-7]1)l?|;|eabi))|(?=atmel\s)avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[["architecture",c.lowerize]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[pt]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus\s10)/i],["model",["vendor","Samsung"],["type","tablet"]],[/\b((?:s[cgp]h|gt|sm)-\w+|galaxy\snexus)/i,/\ssamsung[\s-]([\w-]+)/i,/sec-(sgh\w+)/i],["model",["vendor","Samsung"],["type","mobile"]],[/\((ip(?:hone|od)[\s\w]*);/i],["model",
["vendor","Apple"],["type","mobile"]],[/\((ipad);[\w\s\),;-]+apple/i,/applecoremedia\/[\w\.]+\s\((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],["model",["vendor","Apple"],["type","tablet"]],[/\b((?:agr|ags[23]|bah2?|sht?)-a?[lw]\d{2})/i],["model",["vendor","Huawei"],["type","tablet"]],[/d\/huawei([\w\s-]+)[;\)]/i,/\b(nexus\s6p|vog-[at]?l\d\d|ane-[at]?l[x\d]\d|eml-a?l\d\da?|lya-[at]?l\d[\dc]|clt-a?l\d\di?|ele-l\d\d)/i,/\b(\w{2,4}-[atu][ln][01259][019])[;\)\s]/i],["model",["vendor","Huawei"],["type","mobile"]],
[/\b(poco[\s\w]+)(?:\sbuild|\))/i,/\b;\s(\w+)\sbuild\/hm\1/i,/\b(hm[\s\-_]?note?[\s_]?(?:\d\w)?)\sbuild/i,/\b(redmi[\s\-_]?(?:note|k)?[\w\s_]+)(?:\sbuild|\))/i,/\b(mi[\s\-_]?(?:a\d|one|one[\s_]plus|note lte)?[\s_]?(?:\d?\w?)[\s_]?(?:plus)?)\sbuild/i],[["model",/_/g," "],["vendor","Xiaomi"],["type","mobile"]],[/\b(mi[\s\-_]?(?:pad)(?:[\w\s_]+))(?:\sbuild|\))/i],[["model",/_/g," "],["vendor","Xiaomi"],["type","tablet"]],[/;\s(\w+)\sbuild.+\soppo/i,/\s(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007)\b/i],
["model",["vendor","OPPO"],["type","mobile"]],[/\svivo\s(\w+)(?:\sbuild|\))/i,/\s(v[12]\d{3}\w?[at])(?:\sbuild|;)/i],["model",["vendor","Vivo"],["type","mobile"]],[/\s(rmx[12]\d{3})(?:\sbuild|;)/i],["model",["vendor","Realme"],["type","mobile"]],[/\s(milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?:?(\s4g)?)\b[\w\s]+build\//i,/\smot(?:orola)?[\s-](\w*)/i,/((?:moto[\s\w\(\)]+|xt\d{3,4}|nexus\s6)(?=\sbuild|\)))/i],["model",["vendor","Motorola"],["type","mobile"]],[/\s(mz60\d|xoom[\s2]{0,2})\sbuild\//i],
["model",["vendor","Motorola"],["type","tablet"]],[/((?=lg)?[vl]k\-?\d{3})\sbuild|\s3\.[\s\w;-]{10}lg?-([06cv9]{3,4})/i],["model",["vendor","LG"],["type","tablet"]],[/(lm-?f100[nv]?|nexus\s[45])/i,/lg[e;\s\/-]+((?!browser|netcast)\w+)/i,/\blg(\-?[\d\w]+)\sbuild/i],["model",["vendor","LG"],["type","mobile"]],[/(ideatab[\w\-\s]+)/i,/lenovo\s?(s(?:5000|6000)(?:[\w-]+)|tab(?:[\s\w]+)|yt[\d\w-]{6}|tb[\d\w-]{6})/i],["model",["vendor","Lenovo"],["type","tablet"]],[/(?:maemo|nokia).*(n900|lumia\s\d+)/i,/nokia[\s_-]?([\w\.-]*)/i],
[["model",/_/g," "],["vendor","Nokia"],["type","mobile"]],[/droid.+;\s(pixel\sc)[\s)]/i],["model",["vendor","Google"],["type","tablet"]],[/droid.+;\s(pixel[\s\daxl]{0,6})(?:\sbuild|\))/i],["model",["vendor","Google"],["type","mobile"]],[/droid.+\s([c-g]\d{4}|so[-l]\w+|xq-a\w[4-7][12])(?=\sbuild\/|\).+chrome\/(?![1-6]{0,1}\d\.))/i],["model",["vendor","Sony"],["type","mobile"]],[/sony\stablet\s[ps]\sbuild\//i,/(?:sony)?sgp\w+(?:\sbuild\/|\))/i],[["model","Xperia Tablet"],["vendor","Sony"],["type","tablet"]],
[/\s(kb2005|in20[12]5|be20[12][59])\b/i,/\ba000(1)\sbuild/i,/\boneplus\s(a\d{4})[\s)]/i],["model",["vendor","OnePlus"],["type","mobile"]],[/(alexa)webm/i,/(kf[a-z]{2}wi)(\sbuild\/|\))/i,/(kf[a-z]+)(\sbuild\/|\)).+silk\//i],["model",["vendor","Amazon"],["type","tablet"]],[/(sd|kf)[0349hijorstuw]+(\sbuild\/|\)).+silk\//i],[["model","Fire Phone"],["vendor","Amazon"],["type","mobile"]],[/\((playbook);[\w\s\),;-]+(rim)/i],["model","vendor",["type","tablet"]],[/((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10;\s(\w+)/i],
["model",["vendor","BlackBerry"],["type","mobile"]],[/(?:\b|asus_)(transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus\s7|padfone|p00[cj])/i],["model",["vendor","ASUS"],["type","tablet"]],[/\s(z[es]6[027][01][km][ls]|zenfone\s\d\w?)\b/i],["model",["vendor","ASUS"],["type","mobile"]],[/(nexus\s9)/i],["model",["vendor","HTC"],["type","tablet"]],[/(htc)[;_\s-]{1,2}([\w\s]+(?=\)|\sbuild)|\w+)/i,/(zte)-(\w*)/i,/(alcatel|geeksphone|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]*)/i],["vendor",["model",/_/g,
" "],["type","mobile"]],[/droid[x\d\.\s;]+\s([ab][1-7]\-?[0178a]\d\d?)/i],["model",["vendor","Acer"],["type","tablet"]],[/droid.+;\s(m[1-5]\snote)\sbuild/i,/\bmz-([\w-]{2,})/i],["model",["vendor","Meizu"],["type","mobile"]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[\s_-]?([\w-]*)/i,/(hp)\s([\w\s]+\w)/i,/(asus)-?(\w+)/i,/(microsoft);\s(lumia[\s\w]+)/i,/(lenovo)[_\s-]?([\w-]+)/i,/linux;.+(jolla);/i,/droid.+;\s(oppo)\s?([\w\s]+)\sbuild/i],["vendor","model",["type",
"mobile"]],[/(archos)\s(gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/\s(nook)[\w\s]+build\/(\w+)/i,/(dell)\s(strea[kpr\s\d]*[\dko])/i,/[;\/]\s?(le[\s\-]+pan)[\s\-]+(\w{1,9})\sbuild/i,/[;\/]\s?(trinity)[\-\s]*(t\d{3})\sbuild/i,/\b(gigaset)[\s\-]+(q\w{1,9})\sbuild/i,/\b(vodafone)\s([\w\s]+)(?:\)|\sbuild)/i],["vendor","model",["type","tablet"]],[/\s(surface\sduo)\s/i],["model",["vendor","Microsoft"],["type","tablet"]],[/droid\s[\d\.]+;\s(fp\du?)\sbuild/i],["model",["vendor",
"Fairphone"],["type","mobile"]],[/\s(u304aa)\sbuild/i],["model",["vendor","AT&T"],["type","mobile"]],[/sie-(\w*)/i],["model",["vendor","Siemens"],["type","mobile"]],[/[;\/]\s?(rct\w+)\sbuild/i],["model",["vendor","RCA"],["type","tablet"]],[/[;\/\s](venue[\d\s]{2,7})\sbuild/i],["model",["vendor","Dell"],["type","tablet"]],[/[;\/]\s?(q(?:mv|ta)\w+)\sbuild/i],["model",["vendor","Verizon"],["type","tablet"]],[/[;\/]\s(?:barnes[&\s]+noble\s|bn[rt])([\w\s\+]*)\sbuild/i],["model",["vendor","Barnes & Noble"],
["type","tablet"]],[/[;\/]\s(tm\d{3}\w+)\sbuild/i],["model",["vendor","NuVision"],["type","tablet"]],[/;\s(k88)\sbuild/i],["model",["vendor","ZTE"],["type","tablet"]],[/;\s(nx\d{3}j)\sbuild/i],["model",["vendor","ZTE"],["type","mobile"]],[/[;\/]\s?(gen\d{3})\sbuild.*49h/i],["model",["vendor","Swiss"],["type","mobile"]],[/[;\/]\s?(zur\d{3})\sbuild/i],["model",["vendor","Swiss"],["type","tablet"]],[/[;\/]\s?((zeki)?tb.*\b)\sbuild/i],["model",["vendor","Zeki"],["type","tablet"]],[/[;\/]\s([yr]\d{2})\sbuild/i,
/[;\/]\s(dragon[\-\s]+touch\s|dt)(\w{5})\sbuild/i],[["vendor","Dragon Touch"],"model",["type","tablet"]],[/[;\/]\s?(ns-?\w{0,9})\sbuild/i],["model",["vendor","Insignia"],["type","tablet"]],[/[;\/]\s?((nxa|Next)-?\w{0,9})\sbuild/i],["model",["vendor","NextBook"],["type","tablet"]],[/[;\/]\s?(xtreme_)?(v(1[045]|2[015]|[3469]0|7[05]))\sbuild/i],[["vendor","Voice"],"model",["type","mobile"]],[/[;\/]\s?(lvtel\-)?(v1[12])\sbuild/i],[["vendor","LvTel"],"model",["type","mobile"]],[/;\s(ph-1)\s/i],["model",
["vendor","Essential"],["type","mobile"]],[/[;\/]\s?(v(100md|700na|7011|917g).*\b)\sbuild/i],["model",["vendor","Envizen"],["type","tablet"]],[/[;\/]\s?(trio[\s\w\-\.]+)\sbuild/i],["model",["vendor","MachSpeed"],["type","tablet"]],[/[;\/]\s?tu_(1491)\sbuild/i],["model",["vendor","Rotor"],["type","tablet"]],[/(shield[\w\s]+)\sbuild/i],["model",["vendor","Nvidia"],["type","tablet"]],[/(sprint)\s(\w+)/i],["vendor","model",["type","mobile"]],[/(kin\.[onetw]{3})/i],[["model",/\./g," "],["vendor","Microsoft"],
["type","mobile"]],[/droid\s[\d\.]+;\s(cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],["model",["vendor","Zebra"],["type","tablet"]],[/droid\s[\d\.]+;\s(ec30|ps20|tc[2-8]\d[kx])\)/i],["model",["vendor","Zebra"],["type","mobile"]],[/\s(ouya)\s/i,/(nintendo)\s([wids3utch]+)/i],["vendor","model",["type","console"]],[/droid.+;\s(shield)\sbuild/i],["model",["vendor","Nvidia"],["type","console"]],[/(playstation\s[345portablevi]+)/i],["model",["vendor","Sony"],["type","console"]],[/[\s\(;](xbox(?:\sone)?(?!;\sxbox))[\s\);]/i],
["model",["vendor","Microsoft"],["type","console"]],[/smart-tv.+(samsung)/i],["vendor",["type","smarttv"]],[/hbbtv.+maple;(\d+)/i],[["model",/^/,"SmartTV"],["vendor","Samsung"],["type","smarttv"]],[/(?:linux;\snetcast.+smarttv|lg\snetcast\.tv-201\d)/i],[["vendor","LG"],["type","smarttv"]],[/(apple)\s?tv/i],["vendor",["model","Apple TV"],["type","smarttv"]],[/crkey/i],[["model","Chromecast"],["vendor","Google"],["type","smarttv"]],[/droid.+aft([\w])(\sbuild\/|\))/i],["model",["vendor","Amazon"],["type",
"smarttv"]],[/\(dtv[\);].+(aquos)/i],["model",["vendor","Sharp"],["type","smarttv"]],[/hbbtv\/\d+\.\d+\.\d+\s+\([\w\s]*;\s*(\w[^;]*);([^;]*)/i],[["vendor",c.trim],["model",c.trim],["type","smarttv"]],[/[\s\/\(](android\s|smart[-\s]?|opera\s)tv[;\)\s]/i],[["type","smarttv"]],[/((pebble))app\/[\d\.]+\s/i],["vendor","model",["type","wearable"]],[/droid.+;\s(glass)\s\d/i],["model",["vendor","Google"],["type","wearable"]],[/droid\s[\d\.]+;\s(wt63?0{2,3})\)/i],["model",["vendor","Zebra"],["type","wearable"]],
[/(tesla)(?:\sqtcarbrowser|\/20[12]\d\.[\w\.-]+)/i],["vendor",["type","embedded"]],[/droid .+?; ([^;]+?)(?: build|\) applewebkit).+? mobile safari/i],["model",["type","mobile"]],[/droid .+?;\s([^;]+?)(?: build|\) applewebkit).+?(?! mobile) safari/i],["model",["type","tablet"]],[/\s(tablet|tab)[;\/]/i,/\s(mobile)(?:[;\/]|\ssafari)/i],[["type",c.lowerize]],[/(android[\w\.\s\-]{0,9});.+build/i],["model",["vendor","Generic"]],[/(phone)/i],[["type","mobile"]]],engine:[[/windows.+\sedge\/([\w\.]+)/i],["version",
["name","EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],["version",["name","Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i,/(icab)[\/\s]([23]\.[\d\.]+)/i],["name","version"],[/rv:([\w\.]{1,9})\b.+(gecko)/i],["version","name"]],os:[[/microsoft\s(windows)\s(vista|xp)/i],["name","version"],[/(windows)\snt\s6\.2;\s(arm)/i,/(windows\sphone(?:\sos)*)[\s\/]?([\d\.\s\w]*)/i,
/(windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)(?!.+xbox)/i],["name",["version",f,h]],[/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i],[["name","Windows"],["version",f,h]],[/ip[honead]{2,4}\b(?:.*os\s([\w]+)\slike\smac|;\sopera)/i,/cfnetwork\/.+darwin/i],[["version",/_/g,"."],["name","iOS"]],[/(mac\sos\sx)\s?([\w\s\.]*)/i,/(macintosh|mac(?=_powerpc)\s)(?!.+haiku)/i],[["name","Mac OS"],["version",/_/g,"."]],[/(android|webos|palm\sos|qnx|bada|rim\stablet\sos|meego|sailfish|contiki)[\/\s-]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,
/(tizen|kaios)[\/\s]([\w\.]+)/i,/\((series40);/i],["name","version"],[/\(bb(10);/i],["version",["name","BlackBerry"]],[/(?:symbian\s?os|symbos|s60(?=;)|series60)[\/\s-]?([\w\.]*)/i],["version",["name","Symbian"]],[/mozilla.+\(mobile;.+gecko.+firefox/i],[["name","Firefox OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],["version",["name","webOS"]],[/crkey\/([\d\.]+)/i],["version",["name","Chromecast"]],[/(cros)\s[\w]+\s([\w\.]+\w)/i],[["name","Chromium OS"],"version"],[/(nintendo|playstation)\s([wids345portablevuch]+)/i,
/(xbox);\s+xbox\s([^\);]+)/i,/(mint)[\/\s\(\)]?(\w*)/i,/(mageia|vectorlinux)[;\s]/i,/(joli|[kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?=\slinux)|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus|raspbian)(?:\sgnu\/linux)?(?:\slinux)?[\/\s-]?(?!chrom|package)([\w\.-]*)/i,/(hurd|linux)\s?([\w\.]*)/i,/(gnu)\s?([\w\.]*)/i,/\s([frentopc-]{0,4}bsd|dragonfly)\s?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku)\s(\w+)/i],["name","version"],[/(sunos)\s?([\w\.\d]*)/i],[["name","Solaris"],"version"],
[/((?:open)?solaris)[\/\s-]?([\w\.]*)/i,/(aix)\s((\d)(?=\.|\)|\s)[\w\.])*/i,/(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms|fuchsia)/i,/(unix)\s?([\w\.]*)/i],["name","version"]]},r=function(d,f){if("object"==typeof d&&(f=d,d=b),!(this instanceof r))return(new r(d,f)).getResult();var h=d||(void 0!==a&&a.navigator&&a.navigator.userAgent?a.navigator.userAgent:""),g=f?c.extend(l,f):l;return this.getBrowser=function(){var a={name:b,version:b};return e.call(a,h,g.browser),a.major=c.major(a.version),
a},this.getCPU=function(){var a={architecture:b};return e.call(a,h,g.cpu),a},this.getDevice=function(){var a={vendor:b,model:b,type:b};return e.call(a,h,g.device),a},this.getEngine=function(){var a={name:b,version:b};return e.call(a,h,g.engine),a},this.getOS=function(){var a={name:b,version:b};return e.call(a,h,g.os),a},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return h},
this.setUA=function(a){return h="string"===typeof a&&255<a.length?c.trim(a,255):a,this},this.setUA(h),this};r.VERSION="0.7.28";r.BROWSER={NAME:"name",MAJOR:"major",VERSION:"version"};r.CPU={ARCHITECTURE:"architecture"};r.DEVICE={MODEL:"model",VENDOR:"vendor",TYPE:"type",CONSOLE:"console",MOBILE:"mobile",SMARTTV:"smarttv",TABLET:"tablet",WEARABLE:"wearable",EMBEDDED:"embedded"};r.ENGINE={NAME:"name",VERSION:"version"};r.OS={NAME:"name",VERSION:"version"};d.exports&&(g=d.exports=r);g.UAParser=r;var p=
void 0!==a&&(a.jQuery||a.Zepto);if(p&&!p.ua){var k=new r;p.ua=k.getResult();p.ua.get=function(){return k.getUA()};p.ua.set=function(a){k.setUA(a);a=k.getResult();for(var b in a)p.ua[b]=a[b]}}}("object"==typeof window?window:Xd)})),cb=Sf.getResult(),ob=function(d){if(d.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return d;var g=d.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(g&&g[1]&&g[2]){var a,b=g[2];return m(a="".concat(g[1],".")).call(a,b)}return(g=d.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/))&&
g[1]&&g[2]?(a=g[2],m(b="".concat(g[1],".")).call(b,100*(Number(a)+1))):"4.0.0.999"}("4.7.3");try{var Vl=!0===JSON.parse("true")}catch(d){Vl=!0}let gh=Vl,Oa={username:"test",password:"111111",turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1},$n={"90p":M(160,90),"90p_1":M(160,90),"120p":M(160,120,15,30,65),"120p_1":M(160,120,15,30,65),"120p_3":M(120,120,15,30,50),"120p_4":M(212,120),"180p":M(320,180,15,30,140),"180p_1":M(320,180,15,30,140),"180p_3":M(180,180,15,30,100),"180p_4":M(240,180,15,
30,120),"240p":M(320,240,15,40,200),"240p_1":M(320,240,15,40,200),"240p_3":M(240,240,15,40,140),"240p_4":M(424,240,15,40,220),"360p":M(640,360,15,80,400),"360p_1":M(640,360,15,80,400),"360p_3":M(360,360,15,80,260),"360p_4":M(640,360,30,80,600),"360p_6":M(360,360,30,80,400),"360p_7":M(480,360,15,80,320),"360p_8":M(480,360,30,80,490),"360p_9":M(640,360,15,80,800),"360p_10":M(640,360,24,80,800),"360p_11":M(640,360,24,80,1E3),"480p":M(640,480,15,100,500),"480p_1":M(640,480,15,100,500),"480p_2":M(640,
480,30,100,1E3),"480p_3":M(480,480,15,100,400),"480p_4":M(640,480,30,100,750),"480p_6":M(480,480,30,100,600),"480p_8":M(848,480,15,100,610),"480p_9":M(848,480,30,100,930),"480p_10":M(640,480,10,100,400),"720p":M(1280,720,15,120,1130),"720p_1":M(1280,720,15,120,1130),"720p_2":M(1280,720,30,120,2E3),"720p_3":M(1280,720,30,120,1710),"720p_5":M(960,720,15,120,910),"720p_6":M(960,720,30,120,1380),"1080p":M(1920,1080,15,120,2080),"1080p_1":M(1920,1080,15,120,2080),"1080p_2":M(1920,1080,30,120,3E3),"1080p_3":M(1920,
1080,30,120,3150),"1080p_5":M(1920,1080,60,120,4780),"1440p":M(2560,1440,30,120,4850),"1440p_1":M(2560,1440,30,120,4850),"1440p_2":M(2560,1440,60,120,7350),"4k":M(3840,2160,30,120,8910),"4k_1":M(3840,2160,30,120,8910),"4k_3":M(3840,2160,60,120,13500)},ao={"480p":Eb(640,480,5),"480p_1":Eb(640,480,5),"480p_2":Eb(640,480,30),"480p_3":Eb(640,480,15),"720p":Eb(1280,720,5),"720p_1":Eb(1280,720,5),"720p_2":Eb(1280,720,30),"720p_3":Eb(1280,720,15),"1080p":Eb(1920,1080,5),"1080p_1":Eb(1920,1080,5),"1080p_2":Eb(1920,
1080,30),"1080p_3":Eb(1920,1080,15)},bo={"1SL1TL":Vf(1,1),"3SL3TL":Vf(3,3),"2SL3TL":Vf(2,3)},co={speech_low_quality:cd(16E3,!1),speech_standard:cd(32E3,!1,18),music_standard:cd(48E3,!1),standard_stereo:cd(48E3,!0,56),high_quality:cd(48E3,!1,128),high_quality_stereo:cd(48E3,!0,192)},v={PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io",
"ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",
GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6E4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1E5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6E3,HTTP_CONNECT_TIMEOUT:5E3,PLAYER_STATE_DEFER:2E3,SIGNAL_REQUEST_TIMEOUT:1E4,SIGNAL_REQUEST_WATCH_INTERVAL:1E3,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],FILEPATH_LENMAX:255,SUBSCRIBE_TCC:!0,PING_PONG_TIME_OUT:10,DUALSTREAM_OPERATION_CHECK:!0,
WEBSOCKET_TIMEOUT_MIN:1E4,EVENT_REPORT_SEND_INTERVAL:3E3,CONFIG_DISTRIBUTE_INTERVAL:3E5,MEDIA_ELEMENT_EXISTS_DEPTH:3,CANDIDATE_TIMEOUT:5E3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2E3,SHOW_REPORT_INVOKER_LOG:!1,STATS_FILTER:{transportId:!0,googTrackId:!0},JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2E3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],EVENT_REPORT_RETRY:!0,
CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3E3,AUDIO_VOLUME_INDICATION_INTERVAL:2E3,VOLUME_VOICE_WEIGHT:10,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",
REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,ENUMERATE_DEVICES_INTERVAL:!0};gh||(v.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],v.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],v.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],v.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],v.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io",
"sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],v.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],v.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",v.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",v.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",v.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",v.AREAS=["NORTH_AMERICA","OVERSEA"]);let Fq=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,
5,5,5,5,5]],pc=[],Bc=[];var hh=[],Wl=hh.sort,Gq=ya(function(){hh.sort(void 0)}),Hq=ya(function(){hh.sort(null)}),Iq=Qc("sort");L({target:"Array",proto:!0,forced:Gq||!Hq||Iq},{sort:function(d){return void 0===d?Wl.call(Jb(this)):Wl.call(Jb(this),Vb(d))}});var Jq=Aa("Array").sort,Xl=Array.prototype,he=function(d){var g=d.sort;return d===Xl||d instanceof Array&&g===Xl.sort?Jq:g};L({target:"Array",stat:!0},{isArray:Kc});var n,Qb=ma.Array.isArray;!function(d){d.UNEXPECTED_ERROR="UNEXPECTED_ERROR";d.UNEXPECTED_RESPONSE=
"UNEXPECTED_RESPONSE";d.TIMEOUT="TIMEOUT";d.INVALID_PARAMS="INVALID_PARAMS";d.NOT_READABLE="NOT_READABLE";d.NOT_SUPPORTED="NOT_SUPPORTED";d.INVALID_OPERATION="INVALID_OPERATION";d.OPERATION_ABORTED="OPERATION_ABORTED";d.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT";d.NETWORK_ERROR="NETWORK_ERROR";d.NETWORK_TIMEOUT="NETWORK_TIMEOUT";d.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR";d.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT";d.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED";d.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND";
d.ELECTRON_IS_NULL="ELECTRON_IS_NULL";d.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR";d.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE";d.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL";d.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID";d.PERMISSION_DENIED="PERMISSION_DENIED";d.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED";d.TRACK_IS_DISABLED="TRACK_IS_DISABLED";d.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED";d.LOW_STREAM_ENCODING_ERROR=
"LOW_STREAM_ENCODING_ERROR";d.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR";d.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE";d.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID";d.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER";d.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER";d.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS";d.UID_CONFLICT="UID_CONFLICT";d.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR";d.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK";
d.INVALID_TRACK="INVALID_TRACK";d.SENDER_NOT_FOUND="SENDER_NOT_FOUND";d.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED";d.SET_ANSWER_FAILED="SET_ANSWER_FAILED";d.ICE_FAILED="ICE_FAILED";d.PC_CLOSED="PC_CLOSED";d.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED";d.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST";d.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE";d.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS";d.CAN_NOT_PUBLISH_MULTIPLE_AUDIO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_AUDIO_TRACKS";d.EXIST_DISABLED_VIDEO_TRACK=
"EXIST_DISABLED_VIDEO_TRACK";d.INVALID_REMOTE_USER="INVALID_REMOTE_USER";d.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED";d.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED";d.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH";d.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED";d.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR";d.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED";d.WS_ABORT="WS_ABORT";d.WS_DISCONNECT="WS_DISCONNECT";d.WS_ERR="WS_ERR";d.LIVE_STREAMING_TASK_CONFLICT=
"LIVE_STREAMING_TASK_CONFLICT";d.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT";d.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR";d.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED";d.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED";d.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR";d.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM";d.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT=
"LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT";d.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE";d.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST";d.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR";d.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR";d.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR";d.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC";d.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST";
d.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST";d.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE";d.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE";d.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR";d.INVALID_PLUGIN="INVALID_PLUGIN"}(n||(n={}));var Kq=[].slice,Lq=/MSIE .\./.test(Zd),Yl=function(d){return function(g,a){var b=2<arguments.length,c=b?Kq.call(arguments,2):void 0;return d(b?function(){("function"==typeof g?g:Function(g)).apply(this,c)}:g,a)}};
L({global:!0,bind:!0,forced:Lq},{setTimeout:Yl(N.setTimeout),setInterval:Yl(N.setInterval)});var wb=ma.setTimeout;L({target:"Date",stat:!0},{now:function(){return(new Date).getTime()}});var x=ma.Date.now,Ti=function(d,g){return function(){for(var a=Array(arguments.length),b=0;b<a.length;b++)a[b]=arguments[b];return d.apply(g,a)}},dd=Object.prototype.toString,O={isArray:Li,isArrayBuffer:function(d){return"[object ArrayBuffer]"===dd.call(d)},isBuffer:function(d){return null!=d&&null!=d.constructor&&
"function"==typeof d.constructor.isBuffer&&d.constructor.isBuffer(d)},isFormData:function(d){return"undefined"!=typeof FormData&&d instanceof FormData},isArrayBufferView:function(d){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(d):d&&d.buffer&&d.buffer instanceof ArrayBuffer},isString:function(d){return"string"==typeof d},isNumber:function(d){return"number"==typeof d},isObject:Mi,isUndefined:function(d){return void 0===d},isDate:function(d){return"[object Date]"===dd.call(d)},
isFile:function(d){return"[object File]"===dd.call(d)},isBlob:function(d){return"[object Blob]"===dd.call(d)},isFunction:Ni,isStream:function(d){return Mi(d)&&Ni(d.pipe)},isURLSearchParams:function(d){return"undefined"!=typeof URLSearchParams&&d instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:He,
merge:function g(){function a(a,c){"object"==typeof b[c]&&"object"==typeof a?b[c]=g(b[c],a):b[c]=a}for(var b={},c=0,e=arguments.length;c<e;c++)He(arguments[c],a);return b},deepMerge:function a(){function b(b,e){"object"==typeof c[e]&&"object"==typeof b?c[e]=a(c[e],b):c[e]="object"==typeof b?a({},b):b}for(var c={},e=0,f=arguments.length;e<f;e++)He(arguments[e],b);return c},extend:function(a,b,c){return He(b,function(b,f){a[f]=c&&"function"==typeof b?Ti(b,c):b}),a},trim:function(a){return a.replace(/^\s*/,
"").replace(/\s*$/,"")}},Zl=function(a,b,c){if(!b)return a;if(c)b=c(b);else if(O.isURLSearchParams(b))b=b.toString();else{var e=[];O.forEach(b,function(a,b){null!=a&&(O.isArray(a)?b+="[]":a=[a],O.forEach(a,function(a){O.isDate(a)?a=a.toISOString():O.isObject(a)&&(a=JSON.stringify(a));e.push(Oi(b)+"="+Oi(a))}))});b=e.join("&")}b&&(c=a.indexOf("#"),-1!==c&&(a=a.slice(0,c)),a+=(-1===a.indexOf("?")?"?":"&")+b);return a};Ie.prototype.use=function(a,b){return this.handlers.push({fulfilled:a,rejected:b}),
this.handlers.length-1};Ie.prototype.eject=function(a){this.handlers[a]&&(this.handlers[a]=null)};Ie.prototype.forEach=function(a){O.forEach(this.handlers,function(b){null!==b&&a(b)})};var Qi=Ie,ih=function(a,b,c){return O.forEach(c,function(c){a=c(a,b)}),a},$l=function(a){return!(!a||!a.__CANCEL__)},am=function(a,b){O.forEach(a,function(c,e){e!==b&&e.toUpperCase()===b.toUpperCase()&&(a[b]=c,delete a[e])})},tf=function(a,b,c,e,f){return function(a,b,c,e,f){return a.config=b,c&&(a.code=c),a.request=
e,a.response=f,a.isAxiosError=!0,a.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code}},a}(Error(a),b,c,e,f)},Mq="age authorization content-length content-type etag expires from host if-modified-since if-unmodified-since last-modified location max-forwards proxy-authorization referer retry-after user-agent".split(" "),
Nq=O.isStandardBrowserEnv()?function(){function a(a){return c&&(e.setAttribute("href",a),a=e.href),e.setAttribute("href",a),{href:e.href,protocol:e.protocol?e.protocol.replace(/:$/,""):"",host:e.host,search:e.search?e.search.replace(/^\?/,""):"",hash:e.hash?e.hash.replace(/^#/,""):"",hostname:e.hostname,port:e.port,pathname:"/"===e.pathname.charAt(0)?e.pathname:"/"+e.pathname}}var b,c=/(msie|trident)/i.test(navigator.userAgent),e=document.createElement("a");return b=a(window.location.href),function(c){c=
O.isString(c)?a(c):c;return c.protocol===b.protocol&&c.host===b.host}}():function(){return!0},Oq=O.isStandardBrowserEnv()?{write:function(a,b,c,e,f,h){var l=[];l.push(a+"="+encodeURIComponent(b));O.isNumber(c)&&l.push("expires="+(new Date(c)).toGMTString());O.isString(e)&&l.push("path="+e);O.isString(f)&&l.push("domain="+f);!0===h&&l.push("secure");document.cookie=l.join("; ")},read:function(a){return(a=document.cookie.match(new RegExp("(^|;\\s*)("+a+")=([^;]*)")))?decodeURIComponent(a[3]):null},
remove:function(a){this.write(a,"",Date.now()-864E5)}}:{write:function(){},read:function(){return null},remove:function(){}},Pq=function(a){return new Promise(function(b,c){var e=a.data,f=a.headers;O.isFormData(e)&&delete f["Content-Type"];var h=new XMLHttpRequest;a.auth&&(f.Authorization="Basic "+btoa((a.auth.username||"")+":"+(a.auth.password||"")));if(h.open(a.method.toUpperCase(),Zl(a.url,a.params,a.paramsSerializer),!0),h.timeout=a.timeout,h.onreadystatechange=function(){if(h&&4===h.readyState&&
(0!==h.status||h.responseURL&&0===h.responseURL.indexOf("file:"))){var e,f,l,k,m,n="getAllResponseHeaders"in h?(e=h.getAllResponseHeaders(),m={},e?(O.forEach(e.split("\n"),function(a){(k=a.indexOf(":"),f=O.trim(a.substr(0,k)).toLowerCase(),l=O.trim(a.substr(k+1)),!f)||m[f]&&0<=Mq.indexOf(f)||(m[f]="set-cookie"===f?(m[f]?m[f]:[]).concat([l]):m[f]?m[f]+", "+l:l)}),m):m):null;!function(a,b,c){var e=c.config.validateStatus;!e||e(c.status)?a(c):b(tf("Request failed with status code "+c.status,c.config,
null,c.request,c))}(b,c,{data:a.responseType&&"text"!==a.responseType?h.response:h.responseText,status:h.status,statusText:h.statusText,headers:n,config:a,request:h});h=null}},h.onabort=function(){h&&(c(tf("Request aborted",a,"ECONNABORTED",h)),h=null)},h.onerror=function(){c(tf("Network Error",a,null,h));h=null},h.ontimeout=function(){c(tf("timeout of "+a.timeout+"ms exceeded",a,"ECONNABORTED",h));h=null},O.isStandardBrowserEnv()){var l=(a.withCredentials||Nq(a.url))&&a.xsrfCookieName?Oq.read(a.xsrfCookieName):
void 0;l&&(f[a.xsrfHeaderName]=l)}if("setRequestHeader"in h&&O.forEach(f,function(a,b){void 0===e&&"content-type"===b.toLowerCase()?delete f[b]:h.setRequestHeader(b,a)}),a.withCredentials&&(h.withCredentials=!0),a.responseType)try{h.responseType=a.responseType}catch(r){if("json"!==a.responseType)throw r;}"function"==typeof a.onDownloadProgress&&h.addEventListener("progress",a.onDownloadProgress);"function"==typeof a.onUploadProgress&&h.upload&&h.upload.addEventListener("progress",a.onUploadProgress);
a.cancelToken&&a.cancelToken.promise.then(function(a){h&&(h.abort(),c(a),h=null)});void 0===e&&(e=null);h.send(e)})},Qq={"Content-Type":"application/x-www-form-urlencoded"},uf={adapter:function(){var a;return("undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process)||"undefined"!=typeof XMLHttpRequest)&&(a=Pq),a}(),transformRequest:[function(a,b){return am(b,"Accept"),am(b,"Content-Type"),O.isFormData(a)||O.isArrayBuffer(a)||O.isBuffer(a)||O.isStream(a)||O.isFile(a)||
O.isBlob(a)?a:O.isArrayBufferView(a)?a.buffer:O.isURLSearchParams(a)?(Pi(b,"application/x-www-form-urlencoded;charset=utf-8"),a.toString()):O.isObject(a)?(Pi(b,"application/json;charset=utf-8"),JSON.stringify(a)):a}],transformResponse:[function(a){if("string"==typeof a)try{a=JSON.parse(a)}catch(b){}return a}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(a){return 200<=a&&300>a},headers:{common:{Accept:"application/json, text/plain, */*"}}};
O.forEach(["delete","get","head"],function(a){uf.headers[a]={}});O.forEach(["post","put","patch"],function(a){uf.headers[a]=O.merge(Qq)});var Rq=function(a){var b,c;a.cancelToken&&a.cancelToken.throwIfRequested();return a.baseURL&&!/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(a.url)&&(a.url=(b=a.baseURL,(c=a.url)?b.replace(/\/+$/,"")+"/"+c.replace(/^\/+/,""):b)),a.headers=a.headers||{},a.data=ih(a.data,a.headers,a.transformRequest),a.headers=O.merge(a.headers.common||{},a.headers[a.method]||{},a.headers||
{}),O.forEach("delete get head post put patch common".split(" "),function(b){delete a.headers[b]}),(a.adapter||uf.adapter)(a).then(function(b){a.cancelToken&&a.cancelToken.throwIfRequested();return b.data=ih(b.data,b.headers,a.transformResponse),b},function(b){$l(b)||(a.cancelToken&&a.cancelToken.throwIfRequested(),b&&b.response&&(b.response.data=ih(b.response.data,b.response.headers,a.transformResponse)));return Promise.reject(b)})},jh=function(a,b){b=b||{};var c={};return O.forEach(["url","method",
"params","data"],function(a){void 0!==b[a]&&(c[a]=b[a])}),O.forEach(["headers","auth","proxy"],function(e){O.isObject(b[e])?c[e]=O.deepMerge(a[e],b[e]):void 0!==b[e]?c[e]=b[e]:O.isObject(a[e])?c[e]=O.deepMerge(a[e]):void 0!==a[e]&&(c[e]=a[e])}),O.forEach("baseURL transformRequest transformResponse paramsSerializer timeout withCredentials adapter responseType xsrfCookieName xsrfHeaderName onUploadProgress onDownloadProgress maxContentLength validateStatus maxRedirects httpAgent httpsAgent cancelToken socketPath".split(" "),
function(e){void 0!==b[e]?c[e]=b[e]:void 0!==a[e]&&(c[e]=a[e])}),c};Ld.prototype.request=function(a,b){"string"==typeof a?(a=b||{}).url=a:a=a||{};(a=jh(this.defaults,a)).method=a.method?a.method.toLowerCase():"get";var c=[Rq,void 0];a=Promise.resolve(a);this.interceptors.request.forEach(function(a){c.unshift(a.fulfilled,a.rejected)});for(this.interceptors.response.forEach(function(a){c.push(a.fulfilled,a.rejected)});c.length;)a=a.then(c.shift(),c.shift());return a};Ld.prototype.getUri=function(a){return a=
jh(this.defaults,a),Zl(a.url,a.params,a.paramsSerializer).replace(/^\?/,"")};O.forEach(["delete","get","head","options"],function(a){Ld.prototype[a]=function(b,c){return this.request(O.merge(c||{},{method:a,url:b}))}});O.forEach(["post","put","patch"],function(a){Ld.prototype[a]=function(b,c,e){return this.request(O.merge(e||{},{method:a,url:b,data:c}))}});var Ke=Ld;Wf.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")};Wf.prototype.__CANCEL__=!0;var Ri=Wf;Je.prototype.throwIfRequested=
function(){if(this.reason)throw this.reason;};Je.source=function(){var a;return{token:new Je(function(b){a=b}),cancel:a}};var ec=Si(uf);ec.Axios=Ke;ec.create=function(a){return Si(jh(ec.defaults,a))};ec.Cancel=Ri;ec.CancelToken=Je;ec.isCancel=$l;ec.all=function(a){return Promise.all(a)};ec.spread=function(a){return function(b){return a.apply(null,b)}};var $b=ec.default=ec;let Kb={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},bm=x(),cm=a=>{for(const b in Kb)if(Object.prototype.hasOwnProperty.call(Kb,b)&&
Kb[b]===a)return b;return"DEFAULT"},k=new class{constructor(){this.logLevel=Kb.DEBUG;this.uploadState="collecting";this.uploadLogWaitingList=[];this.uploadLogUploadingList=[];this.currentLogID=this.uploadErrorCount=0}debug(...a){var b;a=m(b=[Kb.DEBUG]).call(b,a);this.log.apply(this,a)}info(...a){var b;a=m(b=[Kb.INFO]).call(b,a);this.log.apply(this,a)}warning(...a){var b;a=m(b=[Kb.WARNING]).call(b,a);this.log.apply(this,a)}error(...a){var b;a=m(b=[Kb.ERROR]).call(b,a);this.log.apply(this,a)}setLogLevel(a){this.logLevel=
a=Math.min(Math.max(0,a),4)}enableLogUpload(){eb("UPLOAD_LOG",!0)}disableLogUpload(){eb("UPLOAD_LOG",!1);this.uploadLogUploadingList=[];this.uploadLogWaitingList=[]}setProxyServer(a){this.proxyServerURL=a}log(...a){var b,c,e,f;if(100>x()-bm)return void wb(()=>{this.log(...a)},x()-bm);const h=Math.max(0,Math.min(4,a[0]));if(!(a[0]=Ui()+" Agora-SDK [".concat(cm(h),"]:"),this.appendLogToWaitingList(h,a),h<this.logLevel)){var l=Ui()+" %cAgora-SDK [".concat(cm(h),"]:"),r=[];switch(h){case Kb.DEBUG:r=m(b=
[l,"color: #64B5F6;"]).call(b,Ma(a).call(a,1));console.log.apply(console,r);break;case Kb.INFO:r=m(c=[l,"color: #1E88E5; font-weight: bold;"]).call(c,Ma(a).call(a,1));console.log.apply(console,r);break;case Kb.WARNING:r=m(e=[l,"color: #FB8C00; font-weight: bold;"]).call(e,Ma(a).call(a,1));console.warn.apply(console,r);break;case Kb.ERROR:r=m(f=[l,"color: #B00020; font-weight: bold;"]).call(f,Ma(a).call(a,1)),console.error.apply(console,r)}}}appendLogToWaitingList(a,...b){if(v.UPLOAD_LOG){var c="";
t(b).call(b,a=>{"object"==typeof a&&(a=A(a));c+="".concat(a," ")});this.uploadLogWaitingList.push({payload_str:c,log_level:a,log_item_id:this.currentLogID++});"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}}startUpload(){this.uploadState="uploading";0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}async uploadLogs(){var a,b={sdk_version:ob,process_id:v.PROCESS_ID,payload:A(this.uploadLogUploadingList)};b=await $b.post(this.url||(this.proxyServerURL?
m(a="https://".concat(this.proxyServerURL,"/ls/?h=")).call(a,v.LOG_UPLOAD_SERVER,"&p=443&d=upload/v1"):"https://".concat(v.LOG_UPLOAD_SERVER,"/upload/v1")),b,{responseType:"text"});if("OK"!==b.data)throw Error("unexpected upload log response: "+b.data);this.uploadLogUploadingList=[]}uploadLogInterval(){if(0!==this.uploadLogUploadingList.length||0!==this.uploadLogWaitingList.length){var a;0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=Ra(a=this.uploadLogWaitingList).call(a,0,
10));this.uploadLogs().then(()=>{this.uploadErrorCount=0;0<this.uploadLogWaitingList.length&&window.setTimeout(()=>this.uploadLogInterval(),3E3)}).catch(a=>{this.uploadErrorCount+=1;2>this.uploadErrorCount?window.setTimeout(()=>this.uploadLogInterval(),200):window.setTimeout(()=>this.uploadLogInterval(),1E3)})}}};class q{constructor(a,b="",c){var e;this.name="AgoraRTCException";this.code=a;this.message=m(e="AgoraRTCError ".concat(this.code,": ")).call(e,b);this.data=c}toString(){var a;return this.data?
m(a="".concat(this.message," data: ")).call(a,A(this.data)):this.message}print(a="error"){return"error"===a&&k.error(this.toString()),"warning"===a&&k.warning(this.toString()),this}throw(){throw this.print(),this;}}var dm,Qa;!function(a){a.FREE="free";a.UPLOADING="uploading"}(dm||(dm={}));(function(a){a.NONE="none";a.INIT="init";a.CANPLAY="canplay";a.PLAYING="playing";a.PAUSED="paused";a.SUSPEND="suspend";a.STALLED="stalled";a.WAITING="waiting";a.ERROR="error";a.DESTROYED="destroyed";a.ABORT="abort";
a.ENDED="ended";a.EMPTIED="emptied"})(Qa||(Qa={}));L({target:"Number",stat:!0},{MAX_SAFE_INTEGER:9007199254740991});L({target:"Number",stat:!0},{MIN_SAFE_INTEGER:-9007199254740991});let Sq={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var Ta,sa,em,D,C,Sc,qc,hd,ie,rb,Ua,F,R,kb,Da,T,ia,Lb,fa,E,Mb;!function(a){a.PUBLISH="publish";a.SUBSCRIBE="subscribe";a.SESSION_INIT="session_init";a.JOIN_CHOOSE_SERVER="join_choose_server";a.REQ_USER_ACCOUNT="req_user_account";
a.JOIN_GATEWAY="join_gateway";a.STREAM_SWITCH="stream_switch";a.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager";a.REQUEST_PROXY_APPCENTER="request_proxy_appcenter";a.FIRST_VIDEO_RECEIVED="first_video_received";a.FIRST_AUDIO_RECEIVED="first_audio_received";a.FIRST_VIDEO_DECODE="first_video_decode";a.FIRST_AUDIO_DECODE="first_audio_decode";a.ON_ADD_AUDIO_STREAM="on_add_audio_stream";a.ON_ADD_VIDEO_STREAM="on_add_video_stream";a.ON_UPDATE_STREAM="on_update_stream";a.ON_REMOVE_STREAM="on_remove_stream";
a.USER_ANALYTICS="req_user_analytics"}(Ta||(Ta={}));(function(a){a.SESSION="io.agora.pb.Wrtc.Session";a.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer";a.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount";a.JOIN_GATEWAT="io.agora.pb.Wrtc.JoinGateway";a.PUBLISH="io.agora.pb.Wrtc.Publish";a.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe";a.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch";a.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped";a.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped";
a.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter";a.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager";a.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke";a.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived";a.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived";a.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode";a.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode";a.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream";a.ON_ADD_VIDEO_STREAM=
"io.agora.pb.Wrtc.OnAddVideoStream";a.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream";a.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream";a.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout";a.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus";a.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent";a.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent";a.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP";a.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit";a.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics"})(sa||
(sa={}));(function(a){a[a.WORKER_EVENT=156]="WORKER_EVENT";a[a.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"})(em||(em={}));(function(a){a.CREATE_CLIENT="createClient";a.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements";a.SET_AREA="setArea";a.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive";a.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive";a.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack";a.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack";a.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack";
a.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack";a.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack";a.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks";a.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack";a.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig";a.START_PROXY_SERVER="Client.startProxyServer";a.STOP_PROXY_SERVER="Client.stopProxyServer";a.SET_PROXY_SERVER="Client.setProxyServer";a.SET_TURN_SERVER="Client.setTurnServer";a.SET_CLIENT_ROLE="Client.setClientRole";a.SET_LOW_STREAM_PARAMETER=
"Client.setLowStreamParameter";a.ENABLE_DUAL_STREAM="Client.enableDualStream";a.DISABLE_DUAL_STREAM="Client.disableDualStream";a.JOIN="Client.join";a.LEAVE="Client.leave";a.PUBLISH="Client.publish";a.UNPUBLISH="Client.unpublish";a.SUBSCRIBE="Client.subscribe";a.UNSUBSCRIBE="Client.unsubscribe";a.RENEW_TOKEN="Client.renewToken";a.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType";a.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption";a.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator";
a.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage";a.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning";a.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError";a.START_LIVE_STREAMING="Client.startLiveStreaming";a.SET_LIVE_TRANSCODING="Client.setLiveTranscoding";a.STOP_LIVE_STREAMING="Client.stopLiveStreaming";a.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl";a.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl";a.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay";a.UPDATE_CHANNEL_MEDIA_RELAY=
"Client.updateChannelMediaRelay";a.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay";a.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request";a.SET_CONFIG_DISTRIBUTE="_configDistribute";a.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute";a.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play";a.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement";a.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop";a.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume";a.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice";
a.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer";a.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer";a.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer";a.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer";a.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer";a.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play";a.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop";a.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect";
a.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice";a.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration";a.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play";a.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop";a.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play";a.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop";a.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume";a.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice";a.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack";
a.STREAM_TYPE_CHANGE="streamTypeChange"})(D||(D={}));(C||(C={})).TRACER="tracer";(function(a){a.IDLE="IDLE";a.INITING="INITING";a.INITEND="INITEND"})(Sc||(Sc={}));(function(a){a.STATE_CHANGE="state_change";a.RECORDING_DEVICE_CHANGED="recordingDeviceChanged";a.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged";a.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"})(qc||(qc={}));(function(a){a[a.ACCESS_POINT=101]="ACCESS_POINT";a[a.UNILBS=201]="UNILBS";a[a.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"})(hd||
(hd={}));(function(a){a[a.IIIEGAL_APPID=1]="IIIEGAL_APPID";a[a.IIIEGAL_UID=2]="IIIEGAL_UID";a[a.INTERNAL_ERROR=3]="INTERNAL_ERROR"})(ie||(ie={}));(function(a){a[a.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY";a[a.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME";a[a.INTERNAL_ERROR=8]="INTERNAL_ERROR";a[a.NO_AUTHORIZED=9]="NO_AUTHORIZED";a[a.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT";a[a.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS";a[a.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED";a[a.STATIC_USE_DYNAMIC_KEY=
14]="STATIC_USE_DYNAMIC_KEY";a[a.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY";a[a.USER_OVERLOAD=16]="USER_OVERLOAD";a[a.FORBIDDEN_REGION=18]="FORBIDDEN_REGION";a[a.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND"})(rb||(rb={}));(function(a){a[a.NO_FLAG_SET=100]="NO_FLAG_SET";a[a.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY";a[a.INVALID_FALG_SET=102]="INVALID_FALG_SET";a[a.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE";a[a.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P";a[a.NO_SERVICE_AVAILABLE_VOICE=
202]="NO_SERVICE_AVAILABLE_VOICE";a[a.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC";a[a.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS";a[a.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN";a[a.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS";a[a.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT";a[a.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER";a[a.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0";a[a.NO_SERVICE_AVAILABLE_VOET=
210]="NO_SERVICE_AVAILABLE_VOET";a[a.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID";a[a.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS";a[a.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV"})(Ua||(Ua={}));(function(a){a[a.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED";a[a.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID";a[a.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID";a[a.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY";
a[a.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND";a[a.K_TICKET_INVALID=7]="K_TICKET_INVALID";a[a.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED";a[a.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY";a[a.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY";a[a.K_UID_BANNED=14]="K_UID_BANNED";a[a.K_IP_BANNED=15]="K_IP_BANNED";a[a.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED";a[a.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL";a[a.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT";a[a.WARN_LOOKUP_CHANNEL_REJECTED=
105]="WARN_LOOKUP_CHANNEL_REJECTED";a[a.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT";a[a.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED";a[a.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED";a[a.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT";a[a.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED";a[a.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE";a[a.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE";a[a.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE";
a[a.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR";a[a.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS";a[a.ERR_INVALID_UID=117]="ERR_INVALID_UID";a[a.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED";a[a.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE";a[a.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE";a[a.ERR_NO_VOCS_AVAILABLE=2E3]="ERR_NO_VOCS_AVAILABLE";a[a.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE";a[a.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT";
a[a.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL";a[a.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP";a[a.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED";a[a.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST";a[a.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY";a[a.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME";a[a.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID";a[a.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS";a[a.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT";
a[a.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION";a[a.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE";a[a.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID";a[a.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID";a[a.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE";a[a.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN";a[a.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID";a[a.ERR_REJOIN_USER_NOT_JOINED=
2025]="ERR_REJOIN_USER_NOT_JOINED";a[a.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO";a[a.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD";a[a.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL";a[a.ERR_TEST_RECOVER=9E3]="ERR_TEST_RECOVER";a[a.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT";a[a.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY"})(F||(F={}));(function(a){a.CONNECTION_STATE_CHANGE="connection-state-change";a.MEDIA_RECONNECT_START="media-reconnect-start";a.MEDIA_RECONNECT_END="media-reconnect-end";
a.IS_USING_CLOUD_PROXY="is-using-cloud-proxy";a.USER_JOINED="user-joined";a.USER_LEAVED="user-left";a.USER_PUBLISHED="user-published";a.USER_UNPUBLISHED="user-unpublished";a.USER_INFO_UPDATED="user-info-updated";a.CLIENT_BANNED="client-banned";a.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state";a.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event";a.VOLUME_INDICATOR="volume-indicator";a.CRYPT_ERROR="crypt-error";a.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire";a.ON_TOKEN_PRIVILEGE_DID_EXPIRE=
"token-privilege-did-expire";a.NETWORK_QUALITY="network-quality";a.STREAM_TYPE_CHANGED="stream-type-changed";a.STREAM_FALLBACK="stream-fallback";a.RECEIVE_METADATA="receive-metadata";a.STREAM_MESSAGE="stream-message";a.LIVE_STREAMING_ERROR="live-streaming-error";a.LIVE_STREAMING_WARNING="live-streaming-warning";a.INJECT_STREAM_STATUS="stream-inject-status";a.EXCEPTION="exception";a.ERROR="error";a.P2P_LOST="p2p_lost"})(R||(R={}));(function(a){a.NETWORK_ERROR="NETWORK_ERROR";a.SERVER_ERROR="SERVER_ERROR";
a.MULTI_IP="MULTI_IP";a.TIMEOUT="TIMEOUT";a.OFFLINE="OFFLINE";a.LEAVE="LEAVE"})(kb||(kb={}));(function(a){a.CONNECTING="connecting";a.CONNECTED="connected";a.RECONNECTING="reconnecting";a.CLOSED="closed"})(Da||(Da={}));(function(a){a.WS_CONNECTED="ws_connected";a.WS_RECONNECTING="ws_reconnecting";a.WS_CLOSED="ws_closed";a.ON_BINARY_DATA="on_binary_data";a.REQUEST_RECOVER="request_recover";a.REQUEST_JOIN_INFO="request_join_info";a.REQUEST_REJOIN_INFO="req_rejoin_info";a.IS_P2P_DISCONNECTED="is_p2p_dis";
a.DISCONNECT_P2P="dis_p2p";a.NEED_RENEW_SESSION="need-sid";a.REPORT_JOIN_GATEWAY="report_join_gateway";a.REQUEST_TIMEOUT="request_timeout";a.REQUEST_SUCCESS="request_success"})(T||(T={}));(function(a){a.PING="ping";a.PING_BACK="ping_back";a.JOIN="join_v2";a.REJOIN="rejoin";a.LEAVE="leave";a.SET_CLIENT_ROLE="set_client_role";a.PUBLISH="publish";a.UNPUBLISH="unpublish";a.SUBSCRIBE="subscribe";a.UNSUBSCRIBE="unsubscribe";a.SUBSCRIBE_CHANGE="subscribe_change";a.TRAFFIC_STATS="traffic_stats";a.RENEW_TOKEN=
"renew_token";a.SWITCH_VIDEO_STREAM="switch_video_stream";a.SET_FALLBACK_OPTION="set_fallback_option";a.GATEWAY_INFO="gateway_info";a.CONTROL="control";a.SEND_METADATA="send_metadata";a.DATA_STREAM="data_stream";a.PICK_SVC_LAYER="pick_svc_layer"})(ia||(ia={}));(function(a){a.PUBLISH_STATS="publish_stats";a.PUBLISH_RELATED_STATS="publish_related_stats";a.SUBSCRIBE_STATS="subscribe_stats";a.SUBSCRIBE_RELATED_STATS="subscribe_related_stats";a.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length"})(Lb||(Lb=
{}));(function(a){a.ON_USER_ONLINE="on_user_online";a.ON_USER_OFFLINE="on_user_offline";a.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update";a.ON_PUBLISH_STREAM="on_publish_stream";a.ON_UPLINK_STATS="on_uplink_stats";a.ON_P2P_LOST="on_p2p_lost";a.ON_REMOVE_STREAM="on_remove_stream";a.ON_ADD_AUDIO_STREAM="on_add_audio_stream";a.ON_ADD_VIDEO_STREAM="on_add_video_stream";a.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire";a.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire";
a.ON_USER_BANNED="on_user_banned";a.ON_NOTIFICATION="on_notification";a.ON_CRYPT_ERROR="on_crypt_error";a.MUTE_AUDIO="mute_audio";a.MUTE_VIDEO="mute_video";a.UNMUTE_AUDIO="unmute_audio";a.UNMUTE_VIDEO="unmute_video";a.RECEIVE_METADATA="receive_metadata";a.ON_DATA_STREAM="on_data_stream";a.ENABLE_LOCAL_VIDEO="enable_local_video";a.DISABLE_LOCAL_VIDEO="disable_local_video";a.ENABLE_LOCAL_AUDIO="enable_local_audio";a.DISABLE_LOCAL_AUDIO="disable_local_audio"})(fa||(fa={}));(function(a){a.CONNECTION_STATE_CHANGE=
"CONNECTION_STATE_CHANGE";a.NEED_ANSWER="NEED_ANSWER";a.NEED_RENEGOTIATE="NEED_RENEGOTIATE";a.P2P_LOST="P2P_LOST";a.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST";a.NEED_UNPUB="NEED_UNPUB";a.NEED_UNSUB="NEED_UNSUB";a.NEED_UPLOAD="NEED_UPLOAD";a.NEED_CONTROL="NEED_CONTROL";a.START_RECONNECT="START_RECONNECT";a.END_RECONNECT="END_RECONNECT";a.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT"})(E||(E={}));(function(a){a.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change";a.RECEIVE_TRACK_BUFFER="receive_track_buffer";a.ON_AUDIO_BUFFER=
"on_audio_buffer"})(Mb||(Mb={}));let vf={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,currentPacketLossRate:0},wf={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},kh={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,
totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},fm={uplinkNetworkQuality:0,downlinkNetworkQuality:0},lh={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};var ea,ua;!function(a){a.CONNECTED="websocket:connected";a.RECONNECTING=
"websocket:reconnecting";a.WILL_RECONNECT="websocket:will_reconnect";a.CLOSED="websocket:closed";a.FAILED="websocket:failed";a.ON_MESSAGE="websocket:on_message";a.REQUEST_NEW_URLS="websocket:request_new_urls"}(ea||(ea={}));(function(a){a.TRANSCODE="mix_streaming";a.RAW="raw_streaming";a.INJECT="inject_streaming"})(ua||(ua={}));let Tq={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},mh={x:0,y:0,width:160,height:160,zOrder:255,alpha:1},Uq={audioBitrate:48,audioChannels:1,audioSampleRate:48E3,
backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""},Vq={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48E3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var Nb,Ad,oa,gm,Va,Ja,G,Yb,Tc,je;!function(a){a.WARNING="@live_uap-warning";a.ERROR="@line_uap-error";a.PUBLISH_STREAM_STATUS="@live_uap-publish-status";a.INJECT_STREAM_STATUS=
"@live_uap-inject-status";a.WORKER_STATUS="@live_uap-worker-status";a.REQUEST_NEW_ADDRESS="@live_uap-request-address"}(Nb||(Nb={}));(Ad||(Ad={})).REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager";(function(a){a[a.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED";a[a.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM";a[a.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR";a[a.LIVE_STREAM_RESPONSE_BAD_STREAM=
451]="LIVE_STREAM_RESPONSE_BAD_STREAM";a[a.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR";a[a.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST";a[a.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED";a[a.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE";a[a.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN";a[a.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=
452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH";a[a.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED";a[a.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM";a[a.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR";a[a.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST";a[a.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT";a[a.LIVE_STREAM_RESPONSE_WORKER_QUIT=
503]="LIVE_STREAM_RESPONSE_WORKER_QUIT";a[a.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE";a[a.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE";a[a.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT";a[a.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH";a[a.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN"})(oa||(oa={}));(function(a){a.CONNECT_FAILED=
"connect failed";a.CONNECT_TIMEOUT="connect timeout";a.WS_DISCONNECTED="websocket disconnected";a.REQUEST_TIMEOUT="request timeout";a.REQUEST_FAILED="request failed";a.WAIT_STATUS_TIMEOUT="wait status timeout";a.WAIT_STATUS_ERROR="wait status error";a.BAD_STATE="bad state";a.WS_ABORT="ws abort";a.AP_REQUEST_TIMEOUT="AP request timeout";a.AP_JSON_PARSE_ERROR="AP json parse error";a.AP_REQUEST_ERROR="AP request error";a.AP_REQUEST_ABORT="AP request abort"})(gm||(gm={}));(function(a){a[a.SetSdkProfile=
0]="SetSdkProfile";a[a.SetSourceChannel=1]="SetSourceChannel";a[a.SetSourceUserId=2]="SetSourceUserId";a[a.SetDestChannel=3]="SetDestChannel";a[a.StartPacketTransfer=4]="StartPacketTransfer";a[a.StopPacketTransfer=5]="StopPacketTransfer";a[a.UpdateDestChannel=6]="UpdateDestChannel";a[a.Reconnect=7]="Reconnect";a[a.SetVideoProfile=8]="SetVideoProfile"})(Va||(Va={}));(function(a){a.DISCONNECT="disconnect";a.CONNECTION_STATE_CHANGE="connection-state-change";a.NETWORK_QUALITY="network-quality";a.STREAM_TYPE_CHANGE=
"stream-type-change";a.IS_P2P_DISCONNECTED="is-p2p-dis";a.DISCONNECT_P2P="dis-p2p";a.REQUEST_NEW_GATEWAY_LIST="req-gate-url";a.NEED_RENEW_SESSION="need-sid"})(Ja||(Ja={}));(function(a){a.NEED_RENEGOTIATE="@need_renegotiate";a.NEED_REPLACE_TRACK="@need_replace_track";a.NEED_CLOSE="@need_close";a.NEED_ADD_TRACK="@need_add_track";a.NEED_REMOVE_TRACK="@need_remove_track";a.NEED_SESSION_ID="@need_sid";a.SET_OPTIMIZATION_MODE="@set_optimization_mode";a.GET_STATS="@get_stats";a.GET_LOW_VIDEO_TRACK="@get_low_video_track";
a.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp";a.SET_VIDEO_TRACK_MUTED="@set_video_track_muted";a.SET_AUDIO_TRACK_MUTED="@set_audio_track_muted"})(G||(G={}));(function(a){a.SCREEN_TRACK="screen_track";a.LOW_STREAM="low_stream"})(Yb||(Yb={}));(function(a){a.SOURCE_STATE_CHANGE="source-state-change";a.TRACK_ENDED="track-ended";a.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload"})(Tc||(Tc={}));(je||(je={})).FIRST_FRAME_DECODED="first-frame-decoded";let hm="AFRICA ASIA CHINA EUROPE GLOBAL INDIA JAPAN NORTH_AMERICA OCEANIA OVERSEA SOUTH_AMERICA".split(" ");
var Ka;!function(a){a.CHINA="CN";a.ASIA="AS";a.NORTH_AMERICA="NA";a.EUROPE="EU";a.JAPAN="JP";a.INDIA="IN";a.OCEANIA="OC";a.SOUTH_AMERICA="SA";a.AFRICA="AF";a.OVERSEA="OVERSEA";a.GLOBAL="GLOBAL"}(Ka||(Ka={}));let nh={CHINA:{},ASIA:{CODE:Ka.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],
UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:Ka.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io",
"cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:Ka.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],
WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},
JAPAN:{CODE:Ka.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","\tuap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],
PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:Ka.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],
LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:Ka.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],
LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:Ka.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],
EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:Ka.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io",
"uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:Ka.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io",
"cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:Ka.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],
WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]}};
var ke,Gb,Bd;gh&&(nh.CHINA={CODE:Ka.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],
PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});(ke||(ke={})).UPDATE_BITRATE_LIMIT="update_bitrate_limit";(function(a){a.ONLINE="ONLINE";a.OFFLINE="OFFLINE"})(Gb||(Gb={}));(function(a){a.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE";a.ONLINE="ONLINE";a.OFFLINE="OFFLINE"})(Bd||(Bd={}));let Wq={join:["startJoin","startRequestAp","startJoinGateway","finishJoin"],publish:["startPublish"]},la={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,
supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1};L({target:"Object",stat:!0,forced:!na,sham:!na},{defineProperties:Eg});var hb=ub(function(a){var b=ma.Object;a=a.exports=function(a,e){return b.defineProperties(a,e)};b.defineProperties.sham&&(a.sham=!0)}),Xq=hf.concat("length","prototype"),oh={f:Object.getOwnPropertyNames||function(a){return Dk(a,Xq)}},Yq=Xb("Reflect",
"ownKeys")||function(a){var b=oh.f($a(a)),c=be.f;return c?b.concat(c(a)):b};L({target:"Object",stat:!0,sham:!na},{getOwnPropertyDescriptors:function(a){var b,c;a=yb(a);for(var e=md,f=Yq(a),h={},l=0;f.length>l;)void 0!==(c=e(a,b=f[l++]))&&Lc(h,b,c);return h}});var ka=ma.Object.getOwnPropertyDescriptors,im=oh.f,Zq={}.toString,jm="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],km=function(a){if(jm&&"[object Window]"==Zq.call(a))try{var b=im(a)}catch(c){b=
jm.slice()}else b=im(yb(a));return b},lm={f:za},$q=Ib.f,sb=ff("hidden"),mm=za("toPrimitive"),ar=Fa.set,nm=Fa.getterFor("Symbol"),Zb=Object.prototype,Ab=N.Symbol,le=Xb("JSON","stringify"),om=md,Cc=Ib.f,pm=km,br=We,rc=mc("symbols"),me=mc("op-symbols"),ph=mc("string-to-symbol-registry"),qh=mc("symbol-to-string-registry"),cr=mc("wks"),rh=N.QObject,sh=!rh||!rh.prototype||!rh.prototype.findChild,th=na&&ya(function(){return 7!=Ac(Cc({},"a",{get:function(){return Cc(this,"a",{value:7}).a}})).a})?function(a,
b,c){var e=om(Zb,b);e&&delete Zb[b];Cc(a,b,c);e&&a!==Zb&&Cc(Zb,b,e)}:Cc,qm=function(a,b){var c=rc[a]=Ac(Ab.prototype);return ar(c,{type:"Symbol",tag:a,description:b}),na||(c.description=b),c},uh=dc&&"symbol"==typeof Ab.iterator?function(a){return"symbol"==typeof a}:function(a){return Object(a)instanceof Ab},xf=function(a,b,c){a===Zb&&xf(me,b,c);$a(a);b=kd(b,!0);return $a(c),P(rc,b)?(c.enumerable?(P(a,sb)&&a[sb][b]&&(a[sb][b]=!1),c=Ac(c,{enumerable:lc(0,!1)})):(P(a,sb)||Cc(a,sb,lc(1,{})),a[sb][b]=
!0),th(a,b,c)):Cc(a,b,c)},sm=function(a,b){$a(a);var c=yb(b);b=zc(c).concat(vh(c));return td(b,function(b){na&&!rm.call(c,b)||xf(a,b,c[b])}),a},rm=function(a){a=kd(a,!0);var b=br.call(this,a);return!(this===Zb&&P(rc,a)&&!P(me,a))&&(!(b||!P(this,a)||!P(rc,a)||P(this,sb)&&this[sb][a])||b)},tm=function(a,b){a=yb(a);b=kd(b,!0);if(a!==Zb||!P(rc,b)||P(me,b)){var c=om(a,b);return!c||!P(rc,b)||P(a,sb)&&a[sb][b]||(c.enumerable=!0),c}},um=function(a){a=pm(yb(a));var b=[];return td(a,function(a){P(rc,a)||P(pd,
a)||b.push(a)}),b},vh=function(a){var b=a===Zb;a=pm(b?me:yb(a));var c=[];return td(a,function(a){!P(rc,a)||b&&!P(Zb,a)||c.push(rc[a])}),c};if(dc||(oc((Ab=function(){if(this instanceof Ab)throw TypeError("Symbol is not a constructor");var a=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,b=af(a),c=function(a){this===Zb&&c.call(me,a);P(this,sb)&&P(this[sb],b)&&(this[sb][b]=!1);th(this,b,lc(1,a))};return na&&sh&&th(Zb,b,{configurable:!0,set:c}),qm(b,a)}).prototype,"toString",function(){return nm(this).tag}),
We=rm,Ib.f=xf,md=tm,oh.f=km=um,be.f=vh,na&&Cc(Ab.prototype,"description",{configurable:!0,get:function(){return nm(this).description}})),lk||(lm.f=function(a){return qm(za(a),a)}),L({global:!0,wrap:!0,forced:!dc,sham:!dc},{Symbol:Ab}),td(zc(cr),function(a){var b=ma.Symbol||(ma.Symbol={});P(b,a)||$q(b,a,{value:lm.f(a)});!0}),L({target:"Symbol",stat:!0,forced:!dc},{for:function(a){a=String(a);if(P(ph,a))return ph[a];var b=Ab(a);return ph[a]=b,qh[b]=a,b},keyFor:function(a){if(!uh(a))throw TypeError(a+
" is not a symbol");if(P(qh,a))return qh[a]},useSetter:function(){sh=!0},useSimple:function(){sh=!1}}),L({target:"Object",stat:!0,forced:!dc,sham:!na},{create:function(a,b){return void 0===b?Ac(a):sm(Ac(a),b)},defineProperty:xf,defineProperties:sm,getOwnPropertyDescriptor:tm}),L({target:"Object",stat:!0,forced:!dc},{getOwnPropertyNames:um,getOwnPropertySymbols:vh}),L({target:"Object",stat:!0,forced:ya(function(){be.f(1)})},{getOwnPropertySymbols:function(a){return be.f(Jb(a))}}),le){var dr=!dc||ya(function(){var a=
Ab();return"[null]"!=le([a])||"{}"!=le({a})||"{}"!=le(Object(a))});L({target:"JSON",stat:!0,forced:dr},{stringify:function(a,b,c){for(var e,f=[a],h=1;arguments.length>h;)f.push(arguments[h++]);if(e=b,(qa(b)||void 0!==a)&&!uh(a))return Kc(b)||(b=function(a,b){if("function"==typeof e&&(b=e.call(this,a,b)),!uh(b))return b}),f[1]=b,le.apply(null,f)}})}Ab.prototype[mm]||Wb(Ab.prototype,mm,Ab.prototype.valueOf);Mc(Ab,"Symbol");pd[sb]=!0;var ja=ma.Object.getOwnPropertySymbols,ib,gb=function(a,b,c){return b in
a?Yk(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a};!function(a){a[a.CHOOSE_SERVER=11]="CHOOSE_SERVER";a[a.CLOUD_PROXY=18]="CLOUD_PROXY";a[a.CLOUD_PROXY_5=20]="CLOUD_PROXY_5"}(ib||(ib={}));var er=Aa("Array").values,vm=Array.prototype,fr={DOMTokenList:!0,NodeList:!0},Uc=function(a){var b=a.values;return a===vm||a instanceof Array&&b===vm.values||fr.hasOwnProperty(qd(a))?er:b},Vc=function(a){var b=Jb(a);var c="function"==typeof this?this:Array;var e=arguments.length;var f=1<e?arguments[1]:
void 0,h=void 0!==f,l=0;var r=ef(b);if(h&&(f=yc(f,2<e?arguments[2]:void 0,2)),null==r||c==Array&&rk(r))for(c=new c(e=zb(b.length));e>l;l++)Lc(c,l,h?f(b[l],l):b[l]);else for(e=(b=r.call(b)).next,c=new c;!(r=e.call(b)).done;l++)Lc(c,l,h?tk(b,f,[r.value,l],!0):r.value);return c.length=l,c},gr=!gl(function(a){Array.from(a)});L({target:"Array",stat:!0,forced:gr},{from:Vc});var Ub=ma.Array.from;class Wa{constructor(){this._events={};this.addListener=this.on}getListeners(a){var b;return this._events[a]?
z(b=this._events[a]).call(b,a=>a.listener):[]}on(a,b){this._events[a]||(this._events[a]=[]);a=this._events[a];-1===this._indexOfListener(a,b)&&a.push({listener:b,once:!1})}once(a,b){this._events[a]||(this._events[a]=[]);a=this._events[a];-1===this._indexOfListener(a,b)&&a.push({listener:b,once:!0})}off(a,b){if(this._events[a]){var c=this._events[a];b=this._indexOfListener(c,b);-1!==b&&Ra(c).call(c,b,1);0===this._events[a].length&&delete this._events[a]}}removeAllListeners(a){a?delete this._events[a]:
this._events={}}emit(a,...b){var c;this._events[a]||(this._events[a]=[]);let e=z(c=this._events[a]).call(c,a=>a);for(c=0;c<e.length;c+=1){let f=e[c];f.once&&this.off(a,f.listener);f.listener.apply(this,b||[])}}_indexOfListener(a,b){let c=a.length;for(;c--;)if(a[c].listener===b)return c;return-1}}let Me=0,ag=0,pb=new class extends Wa{constructor(){super();this._moduleName="network-indicator";this._networkState=Gb.ONLINE;window.addEventListener("online",()=>{this.networkState=Gb.ONLINE});window.addEventListener("offline",
()=>{this.networkState=Gb.OFFLINE})}set networkState(a){k.info("[".concat(this._moduleName,"]")+"network state changed, "+this._networkState+" -> "+a);this.emit(Bd.NETWORK_STATE_CHANGE,a,this._networkState);a===Gb.ONLINE?this.emit(Bd.ONLINE):a===Gb.OFFLINE&&(this.onlineWaiter=new y(a=>{this.once(Bd.ONLINE,()=>{this.onlineWaiter=void 0;a(Gb.ONLINE)})}),this.emit(Bd.OFFLINE));this._networkState=a}get networkState(){return this._networkState}},Ga={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1E4},
u=new class{constructor(){var a,b;this.baseInfoMap=new ba;this.clientList=pc;this.keyEventUploadPendingItems=[];this.normalEventUploadPendingItems=[];this.apiInvokeUploadPendingItems=[];this.apiInvokeCount=0;this.ltsList=[];this.lastSendNormalEventTime=x();this.customReportCount=0;this.eventUploadTimer=window.setInterval(xa(a=this.doSend).call(a,this),v.EVENT_REPORT_SEND_INTERVAL);this.setSessionIdTimer=window.setInterval(xa(b=this.appendSessionId).call(b,this),v.EVENT_REPORT_SEND_INTERVAL)}reportApiInvoke(a,
b,c){b.timeout=b.timeout||6E4;b.reportResult=void 0===b.reportResult||b.reportResult;const e=x(),f=this.apiInvokeCount+=1,h=()=>({tag:b.tag,invokeId:f,sid:a,name:b.name,apiInvokeTime:e,options:b.options,states:b.states||null}),l=!!v.SHOW_REPORT_INVOKER_LOG;l&&k.info("".concat(b.name," start"),b.options);let r=!1;jb(b.timeout).then(()=>{r||(this.sendApiInvoke(Ea({},h(),{error:n.API_INVOKE_TIMEOUT,success:!1})),k.debug("".concat(b.name," timeout")))});const p=new q(n.UNEXPECTED_ERROR,"".concat(b.name,
": this api invoke is end"));return{onSuccess:a=>{const e=()=>{if(r)throw p;return r=!0,this.sendApiInvoke(Ea({},h(),{success:!0},b.reportResult&&{result:a})),l&&k.info("".concat(b.name," onSuccess")),a};return c?wm(e,b.name+"Success",c,()=>r=!0):e()},onError:a=>{const e=()=>{if(r)throw a;r=!0;this.sendApiInvoke(Ea({},h(),{success:!1,error:a.toString()}));l&&k.info("".concat(b.name," onFailure"),a.toString())};return c?wm(e,b.name+"Error",c,()=>r=!0):e()}}}sessionInit(a,b){if(!this.baseInfoMap.has(a)){var c=
x();a=this.createBaseInfo(a,c);a.cname=b.cname;var e=Ya({},{willUploadConsoleLog:v.UPLOAD_LOG,maxTouchPoints:navigator.maxTouchPoints,areaVersion:gh?"global":"oversea",areas:v.AREAS&&v.AREAS.join(",")},b.extend),f=x();b=Ea({},a,{eventType:Ta.SESSION_INIT,appid:b.appid,browser:navigator.userAgent,build:"v4.7.3-0-g0eb931c7(11/16/2021, 7:46:22 PM)",lts:f,elapse:f-c,extend:A(e),mode:b.mode,process:v.PROCESS_ID,success:!0,version:ob});this.send({type:sa.SESSION,data:b},!0)}}joinChooseServer(a,b){if(a=
this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{eventType:Ta.JOIN_CHOOSE_SERVER,lts:e,eventElapse:e-b.lts,chooseServerAddr:b.csAddr,errorCode:b.ec,elapse:e-a.startTime,success:b.succ,chooseServerAddrList:A(b.serverList),uid:b.uid?wa(b.uid):null,cid:b.cid?wa(b.cid):null,chooseServerIp:b.csIp||"",opid:b.opid,unilbsServerIds:b.unilbsServerIds,extend:b.extend||void 0});this.send({type:sa.JOIN_CHOOSE_SERVER,data:b},!0)}}reqUserAccount(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},
c,{eventType:Ta.REQ_USER_ACCOUNT,lts:e,success:b.success,serverAddress:b.serverAddr,stringUid:b.stringUid,uid:b.uid,errorCode:b.errorCode,elapse:e-a.startTime,eventElapse:e-b.lts,extend:A(b.extend)});this.send({type:sa.REQ_USER_ACCOUNT,data:b},!0)}}joinGateway(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info;b.vid&&(c.vid=b.vid);c.uid=b.uid;c.cid=b.cid;var e=x();c=Ea({},c,{eventType:Ta.JOIN_GATEWAY,lts:e,gatewayAddr:b.addr,success:b.succ,errorCode:b.ec,elapse:e-a.startTime,eventElapse:e-b.lts});b.succ&&
(a.lastJoinSuccessTime=e);this.send({type:sa.JOIN_GATEWAT,data:c},!0)}}joinChannelTimeout(a,b){if(a=this.baseInfoMap.get(a)){var c=x();b=Ea({},a.info,{lts:c,timeout:b,elapse:c-a.startTime});this.send({type:sa.JOIN_CHANNEL_TIMEOUT,data:b},!0)}}publish(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{eventType:Ta.PUBLISH,lts:e,eventElapse:e-b.lts,elapse:e-a.startTime,success:b.succ,errorCode:b.ec,videoName:b.videoName,audioName:b.audioName,screenName:b.screenName,screenshare:b.screenshare,
audio:b.audio,video:b.video,p2pid:b.p2pid,publishRequestid:b.publishRequestid});this.send({type:sa.PUBLISH,data:b},!0)}}subscribe(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();a=Ea({},c,{eventType:Ta.SUBSCRIBE,lts:e,eventElapse:e-b.lts,elapse:e-a.startTime,success:b.succ,errorCode:b.ec,video:b.video,audio:b.audio,subscribeRequestid:b.subscribeRequestid,p2pid:b.p2pid});"string"==typeof b.peerid?a.peerSuid=b.peerid:a.peer=b.peerid;this.send({type:sa.SUBSCRIBE,data:a},!0)}}firstRemoteFrame(a,
b,c,e){if(a=this.baseInfoMap.get(a)){var f=a.info,h=x();b=Ea({},f,{},e,{elapse:h-a.startTime,eventType:b,lts:h});this.send({type:c,data:b},!0)}}onGatewayStream(a,b,c,e){if(a=this.baseInfoMap.get(a))b=Ea({},a.info,{},e,{eventType:b,lts:x()}),this.send({type:c,data:b},!0)}streamSwitch(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{eventType:Ta.STREAM_SWITCH,lts:e,isDual:b.isdual,elapse:e-a.startTime,success:b.succ});this.send({type:sa.STREAM_SWITCH,data:b},!0)}}requestProxyAppCenter(a,
b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{eventType:Ta.REQUEST_PROXY_APPCENTER,lts:e,eventElapse:e-b.lts,elapse:e-a.startTime,APAddr:b.APAddr,workerManagerList:b.workerManagerList,response:b.response,errorCode:b.ec,success:b.succ});this.send({type:sa.REQUEST_PROXY_APPCENTER,data:b},!0)}}requestProxyWorkerManager(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{eventType:Ta.REQUEST_PROXY_WORKER_MANAGER,lts:e,eventElapse:e-b.lts,elapse:e-a.startTime,workerManagerAddr:b.workerManagerAddr,
response:b.response,errorCode:b.ec,success:b.succ});this.send({type:sa.REQUEST_PROXY_WORKER_MANAGER,data:b},!0)}}setProxyServer(a){(this.proxyServer=a)?k.debug("reportProxyServerurl: ".concat(a)):k.debug("disable reportProxyServerurl: ".concat(a))}peerPublishStatus(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{subscribeElapse:b.subscribeElapse,peer:b.peer,peerPublishDuration:Math.max(b.audioPublishDuration,b.videoPublishDuration),audiotag:0<b.audioPublishDuration?1:-1,videotag:0<
b.videoPublishDuration?1:-1,lts:e,elapse:e-a.startTime,joinChannelSuccessElapse:e-(a.lastJoinSuccessTime||e)});this.send({type:sa.PEER_PUBLISH_STATUS,data:b},!0)}}workerEvent(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=function(a,b,c){const e=a[b];if(!e||"string"!=typeof e)return[a];a[b]="";const f=ed(A(a));let h=0;const l=[];let k=0;for(let r=0;r<e.length;r++)k+=127>=e.charCodeAt(r)?1:3,k<=c-f||(l[l.length]=hg({},a,{[b]:e.substring(h,r)}),h=r,k=127>=e.charCodeAt(r)?1:3);h!==e.length-
1&&(l[l.length]=hg({},a,{[b]:e.substring(h)}));return l}(Ea({},c,{},b,{elapse:e-a.startTime,lts:e,productType:"WebRTC"}),"payload",1300);t(b).call(b,a=>this.send({type:sa.WORKER_EVENT,data:a},!0))}}apworkerEvent(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{},b,{elapse:e-a.startTime,lts:e});this.send({type:sa.AP_WORKER_EVENT,data:b},!0)}}joinWebProxyAP(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{},b,{elapse:e-a.startTime,lts:e,extend:b.extend||void 0});this.send({type:sa.JOIN_WEB_PROXY_AP,
data:b},!0)}}WebSocketQuit(a,b){if(a=this.baseInfoMap.get(a)){var c=a.info,e=x();b=Ea({},c,{},b,{elapse:e-a.startTime,lts:e});this.send({type:sa.WEBSOCKET_QUIT,data:b},!0)}}async sendCustomReportMessage(a,b){if(this.customReportCount+=b.length,this.customReportCount>v.CUSTOM_REPORT_LIMIT)throw new q(n.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5E3));b=z(b).call(b,b=>({type:sa.USER_ANALYTICS,data:Ea({sid:a},
b)}));b={msgType:"EventMessages",sentTs:Math.round(x()/1E3),payloads:z(b).call(b,a=>A(a))};try{await this.postDataToStatsCollector(b)}catch(c){throw k.error("send custom report message failed",c.toString()),new q(n.CUSTOM_REPORT_SEND_FAILED,c.message);}}sendApiInvoke(a){var b=v.NOT_REPORT_EVENT;if(a.tag&&Z(b)&&Z(b).call(b,a.tag))return!1;if(null===a.sid)return this.apiInvokeUploadPendingItems.push(a),!1;b=this.baseInfoMap.get(a.sid);if(!b)return this.apiInvokeUploadPendingItems.push(a),!1;const {cname:c,
uid:e,cid:f}=b.info;a.lts=a.lts||x();a={invokeId:a.invokeId,sid:a.sid,cname:c,cid:f,uid:e,lts:a.lts,success:a.success,elapse:a.lts-b.startTime,execElapse:a.lts-a.apiInvokeTime,apiName:a.name,options:a.options?A(a.options):void 0,execStates:a.states?A(a.states):void 0,execResult:a.result?A(a.result):void 0,errorCode:a.error?A(a.error):void 0};return this.send({type:sa.API_INVOKE,data:a},!1),!0}appendSessionId(){var a;t(a=this.clientList).call(a,a=>{if(a._sessionId){const b=this.apiInvokeUploadPendingItems.length;
for(let c=0;c<b;c++){const b=this.apiInvokeUploadPendingItems.shift();b&&(b.sid=a._sessionId,this.sendApiInvoke(Ya({},b)))}}})}send(a,b){if(b)return this.keyEventUploadPendingItems.push(a),void this.sendItems(this.keyEventUploadPendingItems,!0);var c;(this.normalEventUploadPendingItems.push(a),this.normalEventUploadPendingItems.length>v.NORMAL_EVENT_QUEUE_CAPACITY)&&Ra(c=this.normalEventUploadPendingItems).call(c,0,1);10<=this.normalEventUploadPendingItems.length&&this.sendItems(this.normalEventUploadPendingItems,
!1)}doSend(){0<this.keyEventUploadPendingItems.length&&this.sendItems(this.keyEventUploadPendingItems,!0);0<this.normalEventUploadPendingItems.length&&5E3<=x()-this.lastSendNormalEventTime&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(a,b){const c=[];for(var e=[];a.length;){const b=a.shift();20>c.length?c.push(b):e.push(b)}a.push(...e);for(const a of[...c]){var f,h;-1!==J(f=this.ltsList).call(f,a.data.lts)?(a.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(a.data.lts)):
(this.ltsList.push(a.data.lts),he(h=this.ltsList).call(h,(a,b)=>a-b))}b||(this.lastSendNormalEventTime=x());e={msgType:"EventMessages",sentTs:Math.round(x()/1E3),payloads:z(c).call(c,a=>A(a)),vid:(a=>(a=a&&a.data.sid&&this.baseInfoMap.get(a.data.sid))&&a.info.vid&&+a.info.vid||0)(c[0])};return c.length&&this.postDataToStatsCollector(e).catch((a=>c=>{var e,f,h;v.EVENT_REPORT_RETRY&&(b?this.keyEventUploadPendingItems=m(e=this.keyEventUploadPendingItems).call(e,a):(this.normalEventUploadPendingItems=
m(f=this.normalEventUploadPendingItems).call(f,a),this.normalEventUploadPendingItems.length>v.NORMAL_EVENT_QUEUE_CAPACITY&&(Ra(h=this.normalEventUploadPendingItems).call(h,0,this.normalEventUploadPendingItems.length-v.NORMAL_EVENT_QUEUE_CAPACITY),k.warning("report: drop normal events"))))})(c)),a}async postDataToStatsCollector(a,b=!1){var c,e,f;pb.networkState===Gb.OFFLINE&&await y.race([pb.onlineWaiter,jb(2*Ga.maxRetryTimeout)]);const h=b?"/events/proto-raws":"/events/messages";let l=this.url||(this.proxyServer?
m(c=m(e="https://".concat(this.proxyServer,"/rs/?h=")).call(e,v.EVENT_REPORT_DOMAIN,"&p=6443&d=")).call(c,h):m(f="https://".concat(v.EVENT_REPORT_DOMAIN,":6443")).call(f,h));for(c=0;2>c;c+=1){var r,k,w;1===c&&(l=this.backupUrl||(this.proxyServer?m(r=m(k="https://".concat(this.proxyServer,"/rs/?h=")).call(k,v.EVENT_REPORT_BACKUP_DOMAIN,"&p=6443&d=")).call(r,h):m(w="https://".concat(v.EVENT_REPORT_BACKUP_DOMAIN,":6443")).call(w,h)));try{b?await fo(l,{timeout:1E4,data:a}):await Rb(l,{timeout:1E4,data:a})}catch(X){if(1===
c)throw X;continue}break}}createBaseInfo(a,b){const c=Ya({},Sq);return c.sid=a,this.baseInfoMap.set(a,{info:c,startTime:b}),c}};class xm extends Wa{constructor(a,b){super();this._hints=[];this._isClosed=!1;this._ID=b||va(8,"track-");this._mediaStreamTrack=this._originMediaStreamTrack=a;Z(Bc).call(Bc,this)||Bc.push(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(a){a||(a=u.reportApiInvoke(null,{name:D.GET_MEDIA_STREAM_TRACK,options:[],tag:C.TRACER}),this._mediaStreamTrack&&
"string"==typeof this._mediaStreamTrack.label?a.onSuccess(this._mediaStreamTrack.label):a.onSuccess(""));return this._mediaStreamTrack}close(){this._isClosed=!0;{let a=J(Bc).call(Bc,this);-1!==a&&Ra(Bc).call(Bc,a,1)}}}let hr=1;class sc{constructor(a){var b;this.lockingPromise=y.resolve();this.locks=0;this.name="";this.lockId=hr++;a&&(this.name=a);k.debug(m(b="[lock-".concat(this.name,"-")).call(b,this.lockId,"] is created."))}get isLocked(){return 0<this.locks}lock(){var a,b;let c;this.locks+=1;k.debug(m(a=
m(b="[lock-".concat(this.name,"-")).call(b,this.lockId,"] is locked, current queue ")).call(a,this.locks,"."));let e=new y(a=>{c=()=>{var b,c;--this.locks;k.debug(m(b=m(c="[lock-".concat(this.name,"-")).call(c,this.lockId,"] is not locked, current queue ")).call(b,this.locks,"."));a()}});a=this.lockingPromise.then(()=>c);return this.lockingPromise=this.lockingPromise.then(()=>e),a}}class yf extends xm{constructor(a,b){super(a,b);this._enabled=!0;this._isClosed=this._muted=!1;this._trackProcessors=
[];this._handleTrackEnded=()=>{this.onTrackEnded()};this._enabledMutex=new sc("".concat(b));a.addEventListener("ended",this._handleTrackEnded)}get muted(){return this._muted}get enabled(){return this._enabled}getTrackLabel(){return this._originMediaStreamTrack.label}close(){var a;this._isClosed||(this.stop(),t(a=this._trackProcessors).call(a,a=>a.destroy()),this._trackProcessors=[],this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),
this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,k.debug("[".concat(this.getTrackId(),"] close")),this.emit(G.NEED_CLOSE),super.close())}async _registerTrackProcessor(a){var b;if(-1===J(b=this._trackProcessors).call(b,a)){var c=this._trackProcessors[this._trackProcessors.length-1];this._trackProcessors.push(a);a.onOutputChange=async()=>{this._mediaStreamTrack=a.output||this._originMediaStreamTrack;this._updatePlayerSource();await Za(this,G.NEED_REPLACE_TRACK,
this._mediaStreamTrack)};c?(c.onOutputChange=async()=>{c.output&&await a.setInput(c.output)},await a.setInput(c.output||c.input||this._originMediaStreamTrack)):await a.setInput(this._originMediaStreamTrack)}}_getOutputFromProcessors(){if(0===this._trackProcessors.length)return this._originMediaStreamTrack;let a=this._trackProcessors[this._trackProcessors.length-1];return a.output||a.input||this._originMediaStreamTrack}async _updateOriginMediaStreamTrack(a,b){a!==this._originMediaStreamTrack&&((this._originMediaStreamTrack.removeEventListener("ended",
this._handleTrackEnded),b&&this._originMediaStreamTrack.stop(),a.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=a,0<this._trackProcessors.length)?(await this._trackProcessors[0].setInput(a),this._mediaStreamTrack=this._getOutputFromProcessors()):this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Za(this,G.NEED_REPLACE_TRACK,this._mediaStreamTrack))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){k.debug("[".concat(this.getTrackId(),
"] track ended"));this.emit(Tc.TRACK_ENDED)}stateCheck(a,b){var c,e,f;if(k.debug(m(c=m(e=m(f="check track state, [muted: ".concat(this._muted,", enabled: ")).call(f,this._enabled,"] to [")).call(e,a,": ")).call(c,b,"]")),"muted"===a&&!la.webAudioMediaStreamDest)throw(new q(n.NOT_SUPPORTED,"current environment does not support set mute")).print();if(Le(b,a),this._enabled&&this._muted&&"enabled"===a&&!1===b)throw(new q(n.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted")).print();
if(!this._enabled&&!this._muted&&"muted"===a&&!0===b)throw(new q(n.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled")).print();}}var Ha;!function(a){a.IOS_15_INTERRUPTION_START="ios15-interruption-start";a.IOS_15_INTERRUPTION_END="ios15-interruption-end";a.IOS_INTERRUPTION_START="ios-interruption-start";a.IOS_INTERRUPTION_END="ios-interruption-end"}(Ha||(Ha={}));let dj=window.AudioContext||window.webkitAudioContext,Sb=null,da=new class extends Wa{constructor(){super(...arguments);
this.onLocalAudioTrackMute=()=>{k.info("ios15-interruption-start");this.emit(Ha.IOS_15_INTERRUPTION_START)};this.onLocalAudioTrackUnmute=async()=>{k.info("ios15-interruption-end");"running"!==this.curState||this.duringInterruption?k.info("ios15-interruption-end-canceled"):(Sb&&await Sb.suspend(),this.emit(Ha.IOS_15_INTERRUPTION_END))}}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(a){k.debug("webaudio bindInterruptDetectorTrack ".concat(a.getTrackId()));
this.interruptDetectorTrack||(this.interruptDetectorTrack=a,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(a){k.debug("webaudio unbindInterruptDetectorTrack ".concat(a.getTrackId()));this.interruptDetectorTrack&&this.interruptDetectorTrack===a&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=
null),this.interruptDetectorTrack=void 0)}},cg=null;class ym extends Wa{constructor(){super();this.isPlayed=!1;this.audioOutputLevel=0;this.isNoAudioInput=this.isDestroyed=!1;this._noAudioInputCount=0;this.context=Nd();this.playNode=this.context.destination;this.outputNode=this.context.createGain();Od(this.outputNode);this.analyserNode=this.context.createAnalyser();this.analyserNode.smoothingTimeConstant=.4;this.analyserNode.fftSize=2048}startGetAudioBuffer(a){this.audioBufferNode||(this.audioBufferNode=
this.context.createScriptProcessor(a),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=a=>{this.emit(Mb.ON_AUDIO_BUFFER,function(a){for(let b=0;b<a.outputBuffer.numberOfChannels;b+=1){let c=a.outputBuffer.getChannelData(b);for(let a=0;a<c.length;a+=1)c[a]=0}return a.inputBuffer}(a))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),
this.audioBufferNode=void 0)}createOutputTrack(){if(!la.webAudioMediaStreamDest)throw new q(n.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(a){"running"!==this.context.state&&xb(()=>{da.emit("autoplay-failed")});this.isPlayed=!0;this.playNode=a||this.context.destination;
this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(a){}this.isPlayed=!1}getAccurateVolumeLevel(){if(!this.context||vb()||jc()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;let a=new Uint8Array(this.analyserNode.frequencyBinCount);this.analyserNode.getByteFrequencyData(a);let b=0;for(let c=0;c<a.length;c++)b+=64>c?Math.abs(10*a[c]):Math.abs(6*a[c]/15);return b/a.length/255}async checkHasAudioInput(a=
0){if(5<a)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;if(vb()||jc()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return!1;let b=new Uint8Array(this.analyserNode.frequencyBinCount);this.analyserNode.getByteFrequencyData(b);let c=!1;for(let a=0;a<b.length;a++)0!==b[a]&&(c=!0);return c?(this.isNoAudioInput=!1,!0):(await jb(200),await this.checkHasAudioInput(a?a+1:1)&&c)}getAudioVolume(){return this.outputNode.gain.value}setVolume(a){this.outputNode.gain.setValueAtTime(a,
this.context.currentTime)}setMute(a){a?(this.disconnect(),this.audioOutputLevel=0):this.connect()}destroy(){this.disconnect();this.stop();this.isDestroyed=!0;this.onNoAudioInput=void 0}disconnect(){this.sourceNode&&this.sourceNode.disconnect();this.outputNode&&this.outputNode.disconnect()}connect(){this.sourceNode&&this.sourceNode.connect(this.outputNode);this.outputNode.connect(this.analyserNode)}}class zm extends ym{constructor(a,b){if(super(),this.isCurrentTrackCloned=!1,this.isRemoteTrack=!1,
this.rebuildWebAudio=async()=>{if(k.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void k.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>k.info("resume success"));k.debug("rebuild web audio because of ios 12 bugs");this.disconnect();var a=this.track;
this.track=this.track.clone();this.isCurrentTrackCloned?a.stop():this.isCurrentTrackCloned=!0;a=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(a);Od(this.sourceNode);this.analyserNode=this.context.createAnalyser();let b=this.outputNode.gain.value;this.outputNode=this.context.createGain();this.outputNode.gain.setValueAtTime(b,this.context.currentTime);Od(this.outputNode);this.connect();this.audioElement.srcObject=a;this.isPlayed&&this.play(this.playNode);this.checkHasAudioInput()},
"audio"!==a.kind)throw new q(n.UNEXPECTED_ERROR);this.track=a;a=new MediaStream([this.track]);this.isRemoteTrack=!!b;this.sourceNode=this.context.createMediaStreamSource(a);Od(this.sourceNode);this.connect();this.audioElement=document.createElement("audio");this.audioElement.srcObject=a;a=V();b&&a.os===Na.IOS&&15>Number(a.osVersion&&a.osVersion.split(".")[0])&&(da.on("state-change",()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&
this.rebuildWebAudio()}),this.checkHasAudioInput().then(a=>{a||document.body.addEventListener("click",this.rebuildWebAudio,!0)}))}get isFreeze(){return!1}updateTrack(a){this.sourceNode.disconnect();this.track=a;this.isCurrentTrackCloned=!1;a=new MediaStream([a]);this.sourceNode=this.context.createMediaStreamSource(a);Od(this.sourceNode);this.sourceNode.connect(this.outputNode);this.audioElement.srcObject=a}destroy(){this.audioElement.srcObject=null;this.audioElement.remove();da.off("state-change",
this.rebuildWebAudio);super.destroy()}}let Ne=null,eg=new sc("safari"),hj=!1,ij=!1,lb=new class extends Wa{constructor(){super();this._state=Sc.IDLE;this.lastAccessCameraPermission=this.lastAccessMicrophonePermission=this.isAccessCameraPermission=this.isAccessMicrophonePermission=!1;this.deviceInfoMap=new ba;this.init().then(()=>{var a;navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",xa(a=this.updateDevicesInfo).call(a,this));window.setInterval(()=>V().name!==
S.WECHAT&&v.ENUMERATE_DEVICES_INTERVAL&&this.updateDevicesInfo(),6E4)}).catch(a=>k.error(a.toString()))}get state(){return this._state}set state(a){a!==this._state&&(this.emit(qc.STATE_CHANGE,a),this._state=a)}async enumerateDevices(a,b,c=!1){if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return(new q(n.NOT_SUPPORTED,"enumerateDevices() not supported.")).throw();var e=await navigator.mediaDevices.enumerateDevices();e=this.checkMediaDeviceInfoIsOk(e);let f=!this.isAccessMicrophonePermission&&
a,h=!this.isAccessCameraPermission&&b;e.audio&&(f=!1);e.video&&(h=!1);let l=e=null,r=null;if(!c&&(f||h)){eg.isLocked&&(k.debug("[device manager] wait GUM lock"),(await eg.lock())(),k.debug("[device manager] GUM unlock"));if(hj&&(f=!1,this.isAccessMicrophonePermission=!0),ij&&(h=!1,this.isAccessCameraPermission=!0),k.debug("[device manager] check media device permissions",a,b,f,h),f&&h){try{r=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(ra){c=Oe(ra.name||ra.code||ra,ra.message);
if(c.code===n.PERMISSION_DENIED)throw c;k.warning("getUserMedia failed in getDevices",c)}this.isAccessMicrophonePermission=this.isAccessCameraPermission=!0}else if(f){try{e=await navigator.mediaDevices.getUserMedia({audio:a})}catch(ra){c=Oe(ra.name||ra.code||ra,ra.message);if(c.code===n.PERMISSION_DENIED)throw c;k.warning("getUserMedia failed in getDevices",c)}this.isAccessMicrophonePermission=!0}else if(h){try{l=await navigator.mediaDevices.getUserMedia({video:b})}catch(ra){c=Oe(ra.name||ra.code||
ra,ra.message);if(c.code===n.PERMISSION_DENIED)throw c;k.warning("getUserMedia failed in getDevices",c)}this.isAccessCameraPermission=!0}k.debug("[device manager] mic permission",a,"cam permission",b)}try{var p,w,m;const a=await navigator.mediaDevices.enumerateDevices();return e&&t(p=e.getTracks()).call(p,a=>a.stop()),l&&t(w=l.getTracks()).call(w,a=>a.stop()),r&&t(m=r.getTracks()).call(m,a=>a.stop()),e=null,l=null,r=null,a}catch(ra){var K,Ca,B;e&&t(K=e.getTracks()).call(K,a=>a.stop());l&&t(Ca=l.getTracks()).call(Ca,
a=>a.stop());r&&t(B=r.getTracks()).call(B,a=>a.stop());r=l=e=null;return(new q(n.ENUMERATE_DEVICES_FAILED,ra.toString())).throw()}}async getRecordingDevices(a=!1){a=await this.enumerateDevices(!0,!1,a);return I(a).call(a,a=>"audioinput"===a.kind)}async getCamerasDevices(a=!1){a=await this.enumerateDevices(!1,!0,a);return I(a).call(a,a=>"videoinput"===a.kind)}async getSpeakers(a=!1){a=await this.enumerateDevices(!0,!1,a);return I(a).call(a,a=>"audiooutput"===a.kind)}searchDeviceNameById(a){return(a=
this.deviceInfoMap.get(a))?a.device.label||a.device.deviceId:null}searchDeviceIdByName(a){var b;let c=null;return t(b=this.deviceInfoMap).call(b,b=>{b.device.label===a&&(c=b.device.deviceId)}),c}async getDeviceById(a){var b=await this.enumerateDevices(!0,!0,!0);b=U(b).call(b,b=>b.deviceId===a);if(!b)throw new q(n.DEVICE_NOT_FOUND,"deviceId: ".concat(a));return b}async init(){this.state=Sc.INITING;try{await this.updateDevicesInfo(),this.state=Sc.INITEND}catch(b){k.warning("Device Detection functionality cannot start properly.",
b.toString());this.state=Sc.IDLE;var a="boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname;a||(new q(n.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.")).throw();throw b;}}async updateDevicesInfo(){var a;const b=await this.enumerateDevices(!0,!0,!0),c=x(),e=[],f=this.checkMediaDeviceInfoIsOk(b);
if(t(b).call(b,a=>{if(a.deviceId){var b=this.deviceInfoMap.get(a.deviceId);if("ACTIVE"!==(b?b.state:"INACTIVE")){const b={initAt:c,updateAt:c,device:a,state:"ACTIVE"};this.deviceInfoMap.set(a.deviceId,b);e.push(b)}b&&(b.updateAt=c)}}),t(a=this.deviceInfoMap).call(a,(a,b)=>{"ACTIVE"===a.state&&a.updateAt!==c&&(a.state="INACTIVE",e.push(a))}),this.state!==Sc.INITEND)return f.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(f.video&&(this.lastAccessCameraPermission=
!0,this.isAccessCameraPermission=!0));t(e).call(e,a=>{switch(a.device.kind){case "audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(qc.RECORDING_DEVICE_CHANGED,a);break;case "videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(qc.CAMERA_DEVICE_CHANGED,a);break;case "audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(qc.PLAYOUT_DEVICE_CHANGED,a)}});f.audio&&(this.lastAccessMicrophonePermission=
!0,this.isAccessMicrophonePermission=!0);f.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(a){const b=I(a).call(a,a=>"audioinput"===a.kind);a=I(a).call(a,a=>"videoinput"===a.kind);const c={audio:!1,video:!1};for(const a of b)if(a.label&&a.deviceId){c.audio=!0;break}for(const b of a)if(b.label&&b.deviceId){c.video=!0;break}return c}};var ir=Aa("Array").entries,Am=Array.prototype,jr={DOMTokenList:!0,NodeList:!0},Bm=function(a){var b=a.entries;return a===
Am||a instanceof Array&&b===Am.entries||jr.hasOwnProperty(qd(a))?ir:b};let fg=!1,kj=new Wa,Cm="play playing loadeddata canplay pause stalled suspend waiting abort emptied ended".split(" "),Bb=new class{constructor(){this.elementMap=new ba;this.elementStateMap=new ba;this.elementsNeedToResume=[];this.sinkIdMap=new ba;this.autoResumeAfterInterruption=()=>{var a,b;t(a=Ub(Bm(b=this.elementMap).call(b))).call(a,([a,b])=>{a=this.elementStateMap.get(a);const c=b.srcObject.getAudioTracks()[0];ad()?c&&"live"===
c.readyState&&"running"===da.curState&&(k.debug("auto resume after interruption for iOS 15"),b.pause(),b.play()):a&&"pause"===a&&c&&"live"===c.readyState&&"running"===da.curState&&(k.debug("auto resume after interruption for iOS"),b.play())})};this.autoResumeAfterInterruptionOnIOS15=()=>{var a,b;t(a=Ub(Bm(b=this.elementMap).call(b))).call(a,([,a])=>{const b=a.srcObject.getAudioTracks()[0];b&&"live"===b.readyState&&(k.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),
a.pause(),a.play())})};this.autoResumeAudioElement();da.on(Ha.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption);da.on(Ha.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15)}async setSinkID(a,b){const c=this.elementMap.get(a);if(this.sinkIdMap.set(a,b),c)try{await c.setSinkId(b)}catch(e){throw new q(n.PERMISSION_DENIED,"can not set sink id: "+e.toString());}}play(a,b,c){if(!this.elementMap.has(b)){var e=document.createElement("audio");e.autoplay=!0;e.srcObject=new MediaStream([a]);
this.bindAudioElementEvents(b,e);this.elementMap.set(b,e);this.elementStateMap.set(b,Qa.INIT);this.setVolume(b,c);(a=this.sinkIdMap.get(b))&&e.setSinkId(a).catch(a=>{k.warning("[".concat(b,"] set sink id failed"),a.toString())});(a=e.play())&&a.then&&a.catch(a=>{k.warning("audio element play warning",a.toString());this.elementMap.has(b)&&"NotAllowedError"===a.name&&(k.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(e),xb(()=>{this.onAutoplayFailed&&this.onAutoplayFailed();
jj()}))})}}updateTrack(a,b){(a=this.elementMap.get(a))&&(a.srcObject=new MediaStream([b]))}isPlaying(a){return this.elementMap.has(a)}setVolume(a,b){(a=this.elementMap.get(a))&&(b=Math.max(0,Math.min(100,b)),a.volume=b/100)}stop(a){var b,c;const e=this.elementMap.get(a);if(this.sinkIdMap.delete(a),e){var f=J(b=this.elementsNeedToResume).call(b,e);Ra(c=this.elementsNeedToResume).call(c,f,1);e.srcObject=null;e.remove();this.elementMap.delete(a);this.elementStateMap.delete(a)}}bindAudioElementEvents(a,
b){t(Cm).call(Cm,c=>{b.addEventListener(c,b=>{var c,e;const l=this.elementStateMap.get(a);b=b.type;k.debug(m(c=m(e="[".concat(a,"] audio-element-status change ")).call(e,l," => ")).call(c,b));this.elementStateMap.set(a,b)})})}autoResumeAudioElement(){const a=()=>{var a;t(a=this.elementsNeedToResume).call(a,a=>{a.play().then(a=>{k.debug("Auto resume audio element success")}).catch(a=>{k.warning("Auto resume audio element failed!",a)})});this.elementsNeedToResume=[]};(new y(a=>{document.body?a():window.addEventListener("load",
()=>a())})).then(()=>{document.body.addEventListener("touchstart",a,!0);document.body.addEventListener("mousedown",a,!0)})}};var tb=function(a,b,c,e){var f,h=arguments.length,l=3>h?b:null===e?e=ca(b,c):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(a,b,c,e);else for(var r=a.length-1;0<=r;r--)(f=a[r])&&(l=(3>h?f(l):3<h?f(b,c,l):f(b,c))||l);return 3<h&&l&&Q(b,c,l),l},Y=function(a,b){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(a,
b)};class La extends yf{constructor(a,b,c){super(a,c);this.trackMediaType="audio";this._enabled=!0;this._volume=100;this._bypassWebAudio=this._useAudioElement=!1;this._encoderConfig=b;this._source=new zm(a)}get isPlaying(){return this._useAudioElement?Bb.isPlaying(this.getTrackId()):this._source.isPlayed}setVolume(a){ha(a,"volume",0,1E3);let b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_AUDIO_TRACK_SET_VOLUME,options:[this.getTrackId(),a]},300);this._volume=a;this._source.setVolume(a/100);this._useAudioElement&&
Bb.setVolume(this.getTrackId(),a);try{if(this._bypassWebAudio)return void k.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));let a=this._source.createOutputTrack();this._mediaStreamTrack!==a&&(this._mediaStreamTrack=a,Za(this,G.NEED_REPLACE_TRACK,this._mediaStreamTrack).then(()=>{k.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(a=>{k.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),a)}))}catch(c){}b.onSuccess()}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}async setPlaybackDevice(a){let b=
u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_AUDIO_SET_OUTPUT_DEVICE,options:[this.getTrackId(),a]});if(!this._useAudioElement)throw new q(n.NOT_SUPPORTED,"your browser does not support setting the audio output device");try{await Bb.setSinkID(this.getTrackId(),a)}catch(c){throw b.onError(c),c;}b.onSuccess()}async setEnabled(a,b,c){var e;if(!c){if(a===this._enabled)return;this.stateCheck("enabled",a)}k.info("[".concat(this.getTrackId(),"] start setEnabled"),a);b=await this._enabledMutex.lock();
if(!a){this._originMediaStreamTrack.enabled=!1;try{await Za(this,G.NEED_REMOVE_TRACK,this)}catch(f){throw k.error("[".concat(this.getTrackId(),"] setEnabled to false error"),f.toString()),b(),f;}return c||(this._enabled=!1),b()}this._originMediaStreamTrack.enabled=!0;try{await Za(this,G.NEED_ADD_TRACK,this)}catch(f){throw k.error("[".concat(this.getTrackId(),"] setEnabled to true error"),f.toString()),b(),f;}k.info(m(e="[".concat(this.getTrackId(),"] setEnabled to ")).call(e,a," success"));c||(this._enabled=
!0);b()}async setMuted(a){var b,c;if(this._bypassWebAudio)return k.debug(m(c="[".concat(this.getTrackId(),"] setMuted:")).call(c,a," fallback to setEnabled because no pass through.")),void await this.setEnabled(!a);if(a!==this._muted){if(this.stateCheck("muted",a),this._muted=a,V().name===S.FIREFOX)return k.debug("[".concat(this.getTrackId(),"] firefox set mute fallback to set enabled")),void await this.setEnabled(!a,void 0,!0);this._mediaStreamTrack.enabled=!a;k.debug(m(b="[".concat(this.getTrackId(),
"] start set muted: ")).call(b,a));await Za(this,G.SET_AUDIO_TRACK_MUTED,{track:this,muted:a})}}getStats(){Qd(()=>{k.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning");return Hc(this,G.GET_STATS)||Pe({},vf)}setAudioFrameCallback(a,b=4096){if(!a)return this._source.removeAllListeners(Mb.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(b);this._source.removeAllListeners(Mb.ON_AUDIO_BUFFER);
this._source.on(Mb.ON_AUDIO_BUFFER,b=>a(b))}play(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_AUDIO_TRACK_PLAY,options:[this.getTrackId()]});k.debug("[".concat(this.getTrackId(),"] start audio playback"));this._useAudioElement?(k.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Bb.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play();a.onSuccess()}stop(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_AUDIO_TRACK_STOP,options:[this.getTrackId()]});
k.debug("[".concat(this.getTrackId(),"] stop audio playback"));this._useAudioElement?Bb.stop(this.getTrackId()):this._source.stop();a.onSuccess()}close(){super.close();this._source.destroy()}_updatePlayerSource(){k.debug("[".concat(this.getTrackId(),"] update player source track"));this._source.updateTrack(this._mediaStreamTrack);this._useAudioElement&&Bb.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(a,b){this._originMediaStreamTrack!==a&&(this._originMediaStreamTrack.removeEventListener("ended",
this._handleTrackEnded),a.addEventListener("ended",this._handleTrackEnded),b&&this._originMediaStreamTrack.stop(),this._originMediaStreamTrack=a,this._source.updateTrack(this._originMediaStreamTrack),this._mediaStreamTrack!==this._source.outputTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await Za(this,G.NEED_REPLACE_TRACK,this._mediaStreamTrack)))}renewMediaStreamTrack(){return y.resolve(void 0)}}tb([pa(),Y("design:type",Function),Y("design:paramtypes",[String]),
Y("design:returntype",y)],La.prototype,"setPlaybackDevice",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[Boolean,Object,Boolean]),Y("design:returntype",y)],La.prototype,"setEnabled",null);tb([pa(),bg({report:u}),Y("design:type",Function),Y("design:paramtypes",[Boolean]),Y("design:returntype",y)],La.prototype,"setMuted",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",Object)],La.prototype,"getStats",null);tb([pa(),Y("design:type",Function),
Y("design:paramtypes",[Object,Number]),Y("design:returntype",void 0)],La.prototype,"setAudioFrameCallback",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",void 0)],La.prototype,"play",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",void 0)],La.prototype,"stop",null);class ne extends La{constructor(a,b,c,e){super(a,b.encoderConfig?Ge(b.encoderConfig):{},e);this._deviceName="default";this._enabled=!0;this._config=b;this._constraints=
c;this._deviceName=a.label;"boolean"==typeof b.bypassWebAudio&&(this._bypassWebAudio=b.bypassWebAudio);ad()&&da.bindInterruptDetectorTrack(this)}async setDevice(a){var b,c;let e=u.reportApiInvoke(null,{tag:C.TRACER,name:D.MIC_AUDIO_TRACK_SET_DEVICE,options:[this.getTrackId(),a]});if(k.info(m(b="[".concat(this.getTrackId(),"] start set device to ")).call(b,a)),this._enabled)try{let c=await lb.getDeviceById(a);b={};b.audio=Pe({},this._constraints);b.audio.deviceId={exact:a};this._originMediaStreamTrack.stop();
let e=null;try{e=await Fb(b,this.getTrackId())}catch(l){throw k.error("[".concat(this.getTrackId(),"] setDevice failed"),l.toString()),e=await Fb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),l;}await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1);this._deviceName=c.label;this._config.microphoneId=a;this._constraints.deviceId={exact:a}}catch(f){throw e.onError(f),k.error("[".concat(this.getTrackId(),"] setDevice error"),
f.toString()),f;}else try{this._deviceName=(await lb.getDeviceById(a)).label,this._config.microphoneId=a,this._constraints.deviceId={exact:a}}catch(f){throw e.onError(f),k.error("[".concat(this.getTrackId(),"] setDevice error"),f.toString()),f;}e.onSuccess();k.info(m(c="[".concat(this.getTrackId(),"] set device to ")).call(c,a," success"))}async setEnabled(a,b,c){if(b)return k.debug("[".concat(this.getTrackId,"] setEnabled false (do not close microphone)")),await super.setEnabled(a);if(!c){if(a===
this._enabled)return;this.stateCheck("enabled",a)}k.info("[".concat(this.getTrackId(),"] start setEnabled"),a);b=await this._enabledMutex.lock();if(!a){this._originMediaStreamTrack.onended=null;this._originMediaStreamTrack.stop();c||(this._enabled=!1);try{await Za(this,G.NEED_REMOVE_TRACK,this)}catch(f){throw k.error("[".concat(this.getTrackId(),"] setEnabled false failed"),f.toString()),b(),f;}return void b()}a=Pe({},this._constraints);let e=lb.searchDeviceIdByName(this._deviceName);e&&!a.deviceId&&
(a.deviceId=e);try{let a=await Fb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(a.getAudioTracks()[0],!1);await Za(this,G.NEED_ADD_TRACK,this)}catch(f){throw b(),k.error("[".concat(this.getTrackId(),"] setEnabled true failed"),f.toString()),f;}c||(this._enabled=!0);k.info("[".concat(this.getTrackId(),"] setEnabled success"));b()}close(){super.close();ad()&&da.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((vb()||jc())&&this._enabled&&!this._isClosed&&
da.duringInterruption){let a=async()=>{da.off(Ha.IOS_INTERRUPTION_END,a);this._enabled&&!this._isClosed&&(k.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};da.on(Ha.IOS_INTERRUPTION_END,a)}else k.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(Tc.TRACK_ENDED)}async renewMediaStreamTrack(){var a=Pe({},this._constraints);let b=lb.searchDeviceIdByName(this._deviceName);b&&!a.deviceId&&
(a.deviceId=b);a=await Fb({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(a.getAudioTracks()[0],!0)}}tb([pa(),Y("design:type",Function),Y("design:paramtypes",[String]),Y("design:returntype",y)],ne.prototype,"setDevice",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[Boolean,Boolean,Boolean]),Y("design:returntype",y)],ne.prototype,"setEnabled",null);class Cd extends La{constructor(a,b,c,e){super(b.createOutputTrack(),c,e);this.source=a;this._bufferSource=
b;this._bufferSource.on(Mb.AUDIO_SOURCE_STATE_CHANGE,a=>{this.emit(Tc.SOURCE_STATE_CHANGE,a)});try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(f){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(a){let b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.BUFFER_AUDIO_TRACK_START,options:[this.getTrackId(),a,this.duration]});a&&this._bufferSource.updateOptions(a);
this._bufferSource.startProcessAudioBuffer();b.onSuccess()}pauseProcessAudioBuffer(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.BUFFER_AUDIO_TRACK_PAUSE,options:[this.getTrackId()]});this._bufferSource.pauseProcessAudioBuffer();a.onSuccess()}seekAudioBuffer(a){let b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.BUFFER_AUDIO_TRACK_SEEK,options:[this.getTrackId()]});this._bufferSource.seekAudioBuffer(a);b.onSuccess()}resumeProcessAudioBuffer(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.BUFFER_AUDIO_TRACK_RESUME,
options:[this.getTrackId()]});this._bufferSource.resumeProcessAudioBuffer();a.onSuccess()}stopProcessAudioBuffer(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.BUFFER_AUDIO_TRACK_STOP,options:[this.getTrackId()]});this._bufferSource.stopProcessAudioBuffer();a.onSuccess()}}tb([pa(),Y("design:type",Function),Y("design:paramtypes",[Object]),Y("design:returntype",void 0)],Cd.prototype,"startProcessAudioBuffer",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",
void 0)],Cd.prototype,"pauseProcessAudioBuffer",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[Number]),Y("design:returntype",void 0)],Cd.prototype,"seekAudioBuffer",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",void 0)],Cd.prototype,"resumeProcessAudioBuffer",null);tb([pa(),Y("design:type",Function),Y("design:paramtypes",[]),Y("design:returntype",void 0)],Cd.prototype,"stopProcessAudioBuffer",null);class ab extends La{constructor(){let a=
Nd().createMediaStreamDestination();super(a.stream.getAudioTracks()[0],void 0,va(8,"track-mix-"));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(b){}this.destNode=a;this.trackList=[]}get isActive(){var a;return!(!this.trackList.length||!U(a=this.trackList).call(a,a=>!a.muted))}getSubTrackLabels(){var a;return z(a=this.trackList).call(a,a=>a.getTrackLabel())}hasAudioTrack(a){var b;return-1!==J(b=this.trackList).call(b,a)}addAudioTrack(a){var b;-1===J(b=this.trackList).call(b,a)?
(k.debug("add ".concat(a.getTrackId()," to mixing track")),a._source.outputNode.connect(this.destNode),this.trackList.push(a),this.updateEncoderConfig()):k.debug("track ".concat(a.getTrackId()," is already added"))}removeAudioTrack(a){var b;if(-1!==J(b=this.trackList).call(b,a)){k.debug("remove ".concat(a.getTrackId()," from mixing track"));try{a._source.outputNode.disconnect(this.destNode)}catch(c){}Gc(this.trackList,a);this.updateEncoderConfig()}}updateEncoderConfig(){var a;let b={};t(a=this.trackList).call(a,
a=>{a._encoderConfig&&((a._encoderConfig.bitrate||0)>(b.bitrate||0)&&(b.bitrate=a._encoderConfig.bitrate),(a._encoderConfig.sampleRate||0)>(b.sampleRate||0)&&(b.sampleRate=a._encoderConfig.sampleRate),(a._encoderConfig.sampleSize||0)>(b.sampleSize||0)&&(b.sampleSize=a._encoderConfig.sampleSize),a._encoderConfig.stereo&&(b.stereo=!0))});this._encoderConfig=b}}class kr extends Wa{constructor(){super(...arguments);this.resultStorage=new ba}setLocalAudioStats(a,b,c){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",
a,this.checkAudioInputLevel(c,b));this.record("SEND_AUDIO_BITRATE_TOO_LOW",a,this.checkSendAudioBitrate(c,b))}setLocalVideoStats(a,b,c){this.record("SEND_VIDEO_BITRATE_TOO_LOW",a,this.checkSendVideoBitrate(c,b));this.record("FRAMERATE_INPUT_TOO_LOW",a,this.checkFramerateInput(c,b));this.record("FRAMERATE_SENT_TOO_LOW",a,this.checkFramerateSent(c))}setRemoteAudioStats(a,b){a=a.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",a,this.checkAudioOutputLevel(b))}setRemoteVideoStats(a,b){a=a.getUserId();
this.record("RECV_VIDEO_DECODE_FAILED",a,this.checkVideoDecode(b))}record(a,b,c){this.resultStorage.has(a)||this.resultStorage.set(a,{result:[],isPrevNormal:!0});let e=this.resultStorage.get(a);if(e&&(e.result.push(c),5<=e.result.length)){var f;c=Z(f=e.result).call(f,!0);e.isPrevNormal&&!c&&this.emit("exception",Dm[a],a,b);!e.isPrevNormal&&c&&this.emit("exception",Dm[a]+2E3,a+"_RECOVER",b);e.isPrevNormal=c;e.result=[]}}checkAudioOutputLevel(a){return!(0<a.receiveBitrate&&0===a.receiveLevel)}checkAudioInputLevel(a,
b){return b instanceof ab&&!b.isActive||!!b.muted||0!==a.sendVolumeLevel}checkFramerateInput(a,b){let c=null;b._encoderConfig&&b._encoderConfig.frameRate&&(c=wc(b._encoderConfig.frameRate));a=a.captureFrameRate;return!c||!a||!(10<c&&5>a||10>c&&5<=c&&1>=a)}checkFramerateSent(a){return!(a.captureFrameRate&&a.sendFrameRate&&5<a.captureFrameRate&&1>=a.sendFrameRate)}checkSendVideoBitrate(a,b){return!!b.muted||0!==a.sendBitrate}checkSendAudioBitrate(a,b){return b instanceof ab&&!b.isActive||!!b.muted||
0!==a.sendBitrate}checkVideoDecode(a){return 0===a.receiveBitrate||0!==a.decodeFrameRate}}let Dm={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003};class oe{constructor(a){this.localConnectionsMap=new ba;this.remoteConnectionsMap=new ba;this.trafficStatsPeerList=[];this.updateStats=()=>{var a,c;t(a=this.remoteConnectionsMap).call(a,a=>
{var b;let c=a.audioStats;var e=a.videoStats,r=a.pcStats;let k=bc({},kh),w=bc({},lh),m=bc({},fm),n=a.connection.pc.getStats(),q=n.audioRecv[0],B=n.videoRecv[0];r=r?r.videoRecv[0]:void 0;let t=!0===a.connection.pc._statsFilter.videoIsReady,u=this.trafficStats&&U(b=this.trafficStats.peer_delay).call(b,b=>b.peer_uid===a.connection.getUserId());q&&("opus"!==q.codec&&"aac"!==q.codec||(k.codecType=q.codec),q.outputLevel?k.receiveLevel=Math.round(32767*q.outputLevel):a.connection.user.audioTrack&&(k.receiveLevel=
Math.round(32767*a.connection.user.audioTrack.getVolumeLevel())),k.receiveBytes=q.bytes,k.receivePackets=q.packets,k.receivePacketsLost=q.packetsLost,k.packetLossRate=k.receivePacketsLost/(k.receivePackets+k.receivePacketsLost),k.receiveBitrate=c?8*Math.max(0,k.receiveBytes-c.receiveBytes):0,k.totalDuration=c?c.totalDuration+1:1,k.totalFreezeTime=c?c.totalFreezeTime:0,k.freezeRate=k.totalFreezeTime/k.totalDuration,k.receiveDelay=q.jitterBufferMs,b=a.connection.user.audioTrack,10<k.totalDuration&&
oe.isRemoteAudioFreeze(b)&&(k.totalFreezeTime+=1));B&&("H264"!==B.codec&&"VP8"!==B.codec&&"VP9"!==B.codec&&"AV1X"!==B.codec||(w.codecType=B.codec),w.receiveBytes=B.bytes,w.receiveBitrate=e?8*Math.max(0,w.receiveBytes-e.receiveBytes):0,w.decodeFrameRate=B.decodeFrameRate,w.renderFrameRate=B.decodeFrameRate,B.outputFrame&&(w.renderFrameRate=B.outputFrame.frameRate),B.receivedFrame?(w.receiveFrameRate=B.receivedFrame.frameRate,w.receiveResolutionHeight=B.receivedFrame.height,w.receiveResolutionWidth=
B.receivedFrame.width):a.connection.user.videoTrack&&(w.receiveResolutionHeight=a.connection.user.videoTrack._videoHeight||0,w.receiveResolutionWidth=a.connection.user.videoTrack._videoWidth||0),void 0!==B.framesRateFirefox&&(w.receiveFrameRate=Math.round(B.framesRateFirefox)),w.receivePackets=B.packets,w.receivePacketsLost=B.packetsLost,w.packetLossRate=w.receivePacketsLost/(w.receivePackets+w.receivePacketsLost),w.totalDuration=e?e.totalDuration+1:1,w.totalFreezeTime=e?e.totalFreezeTime:0,w.receiveDelay=
B.jitterBufferMs||0,e=a.connection.user.videoTrack,a.connection.subscribeOptions.video&&t&&oe.isRemoteVideoFreeze(e,B,r)&&(w.totalFreezeTime+=1),w.freezeRate=w.totalFreezeTime/w.totalDuration);u&&(k.end2EndDelay=u.B_ad,w.end2EndDelay=u.B_vd,k.transportDelay=u.B_ed,w.transportDelay=u.B_ed,k.currentPacketLossRate=u.B_ealr4/100,w.currentPacketLossRate=u.B_evlr4/100,m.uplinkNetworkQuality=u.B_punq?u.B_punq:0,m.downlinkNetworkQuality=u.B_pdnq?u.B_punq:0);a.audioStats=k;a.videoStats=w;a.pcStats=n;a.networkStats=
m;a.connection.user.audioTrack&&this.exceptionMonitor.setRemoteAudioStats(a.connection.user.audioTrack,k);a.connection.user.videoTrack&&this.exceptionMonitor.setRemoteVideoStats(a.connection.user.videoTrack,w)});t(c=this.localConnectionsMap).call(c,a=>{let b=a.audioStats,c=a.videoStats,e=bc({},vf),k=bc({},wf);var p=a.connection.pc.getStats();let w=p.audioSend[0];p=p.videoSend[0];let m=a.connection.getUserId();w&&("opus"!==w.codec&&"aac"!==w.codec||(e.codecType=w.codec),w.inputLevel?e.sendVolumeLevel=
Math.round(32767*w.inputLevel):a.connection.audioTrack&&(e.sendVolumeLevel=Math.round(32767*a.connection.audioTrack.getVolumeLevel())),e.sendBytes=w.bytes,e.sendPackets=w.packets,e.sendPacketsLost=w.packetsLost,e.sendBitrate=b?8*Math.max(0,e.sendBytes-b.sendBytes):0);p&&("H264"!==p.codec&&"VP8"!==p.codec&&"VP9"!==p.codec&&"AV1X"!==p.codec||(k.codecType=p.codec),k.sendBytes=p.bytes,k.sendBitrate=c?8*Math.max(0,k.sendBytes-c.sendBytes):0,p.inputFrame?(k.captureFrameRate=p.inputFrame.frameRate,k.captureResolutionHeight=
p.inputFrame.height,k.captureResolutionWidth=p.inputFrame.width):a.connection.videoTrack&&(k.captureResolutionWidth=a.connection.videoTrack._videoWidth||0,k.captureResolutionHeight=a.connection.videoTrack._videoHeight||0),p.sentFrame?(k.sendFrameRate=p.sentFrame.frameRate,k.sendResolutionHeight=p.sentFrame.height,k.sendResolutionWidth=p.sentFrame.width):a.connection.videoTrack&&(k.sendResolutionWidth=a.connection.videoTrack._videoWidth||0,k.sendResolutionHeight=a.connection.videoTrack._videoHeight||
0),p.avgEncodeMs&&(k.encodeDelay=p.avgEncodeMs),a.connection.videoTrack&&a.connection.videoTrack._encoderConfig&&a.connection.videoTrack._encoderConfig.bitrateMax&&(k.targetSendBitrate=1E3*a.connection.videoTrack._encoderConfig.bitrateMax),k.sendPackets=p.packets,k.sendPacketsLost=p.packetsLost,k.totalDuration=c?c.totalDuration+1:1,k.totalFreezeTime=c?c.totalFreezeTime:0,this.isLocalVideoFreeze(p)&&(k.totalFreezeTime+=1));this.trafficStats&&(e.sendPacketsLost=this.trafficStats.B_palr4/100,k.sendPacketsLost=
this.trafficStats.B_pvlr4/100);a.audioStats=e;a.videoStats=k;a.audioStats&&a.connection.audioTrack&&this.exceptionMonitor.setLocalAudioStats(m,a.connection.audioTrack,a.audioStats);a.videoStats&&a.connection.videoTrack&&this.exceptionMonitor.setLocalVideoStats(m,a.connection.videoTrack,a.videoStats)})};this.clientId=a;this.updateStatsInterval=window.setInterval(this.updateStats,1E3);this.exceptionMonitor=new kr;this.exceptionMonitor.on("exception",(a,c,e)=>{this.onStatsException&&this.onStatsException(a,
c,e)})}reset(){this.localConnectionsMap=new ba;this.remoteConnectionsMap=new ba;this.trafficStats=void 0;this.trafficStatsPeerList=[];this.uplinkStats=void 0}getLocalAudioTrackStats(a){return(a=this.localConnectionsMap.get(a))&&a.audioStats?a.audioStats:bc({},vf)}getLocalVideoTrackStats(a){return(a=this.localConnectionsMap.get(a))&&a.videoStats?a.videoStats:bc({},wf)}getRemoteAudioTrackStats(a){var b;let c=this.remoteConnectionsMap.get(a);if(!c||!c.audioStats)return bc({},kh);if(!this.trafficStats)return c.audioStats;
a=U(b=this.trafficStats.peer_delay).call(b,a=>a.peer_uid===c.connection.user.uid);return a&&(c.audioStats.publishDuration=a.B_ppad+(x()-this.trafficStats.timestamp)),c.audioStats}getRemoteNetworkQualityStats(a){return(a=this.remoteConnectionsMap.get(a))&&a.networkStats?a.networkStats:bc({},fm)}getRemoteVideoTrackStats(a){var b;let c=this.remoteConnectionsMap.get(a);if(!c||!c.videoStats)return bc({},lh);if(!this.trafficStats)return c.videoStats;a=U(b=this.trafficStats.peer_delay).call(b,a=>a.peer_uid===
c.connection.user.uid);return a&&(c.videoStats.publishDuration=a.B_ppvd+(x()-this.trafficStats.timestamp)),c.videoStats}getRTCStats(){var a,b;let c=0,e=0,f=0,h=0;t(a=this.localConnectionsMap).call(a,a=>{a.audioStats&&(c+=a.audioStats.sendBytes,e+=a.audioStats.sendBitrate);a.videoStats&&(c+=a.videoStats.sendBytes,e+=a.videoStats.sendBitrate)});t(b=this.remoteConnectionsMap).call(b,a=>{a.audioStats&&(f+=a.audioStats.receiveBytes,h+=a.audioStats.receiveBitrate);a.videoStats&&(f+=a.videoStats.receiveBytes,
h+=a.videoStats.receiveBitrate)});a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:e,SendBytes:c,RecvBytes:f,RecvBitrate:h,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1E3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}removeConnection(a){this.localConnectionsMap.delete(a);this.remoteConnectionsMap.delete(a)}addLocalConnection(a){let b=a.connectionId;this.localConnectionsMap.has(b)||this.localConnectionsMap.set(b,
{connection:a})}addRemoteConnection(a){let b=a.connectionId;this.remoteConnectionsMap.has(b)||this.remoteConnectionsMap.set(b,{connection:a})}updateTrafficStats(a){var b;let c=I(b=a.peer_delay).call(b,a=>{var b;return-1===J(b=this.trafficStatsPeerList).call(b,a.peer_uid)});t(c).call(c,a=>{var b,c;let e=U(b=Ub(Uc(c=this.remoteConnectionsMap).call(c))).call(b,b=>b.connection._userId===a.peer_uid);void 0!==a.B_ppad&&void 0!==a.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(a.peer_uid,
a.B_ppad,a.B_ppvd,e?x()-e.connection.startTime:0),this.trafficStatsPeerList.push(a.peer_uid))});this.trafficStats=a}updateUplinkStats(a){var b;this.uplinkStats&&this.uplinkStats.B_fir!==a.B_fir&&k.debug(m(b="[".concat(this.clientId,"]: Period fir changes to ")).call(b,a.B_fir));this.uplinkStats=a}static isRemoteVideoFreeze(a,b,c){if(!a)return!1;a=!c||b.framesDecodeCount>c.framesDecodeCount;return!!c&&b.framesDecodeFreezeTime>c.framesDecodeFreezeTime||!a}static isRemoteAudioFreeze(a){return!!a&&a._isFreeze()}isLocalVideoFreeze(a){return!(!a.inputFrame||
!a.sentFrame)&&5<a.inputFrame.frameRate&&3>a.sentFrame.frameRate}}var Em;let Qe=()=>{},vj={},Fm=new class{constructor(){this.fnMap=new ba}throttleByKey(a,b,c,e,...f){if(this.fnMap.has(b)){var h=this.fnMap.get(b);h.threshold!==c?(h.fn(...h.args),clearTimeout(h.timer),h=window.setTimeout(()=>{const a=this.fnMap.get(b);a&&a.fn(...a.args);this.fnMap.delete(b)},c),this.fnMap.set(b,{fn:a,threshold:c,timer:h,args:f,skipFn:e})):(h.skipFn&&h.skipFn(...h.args),this.fnMap.set(b,hg({},h,{fn:a,args:f,skipFn:e})))}else h=
window.setTimeout(()=>{const a=this.fnMap.get(b);a&&a.fn(...a.args);this.fnMap.delete(b)},c),this.fnMap.set(b,{fn:a,threshold:c,timer:h,args:f,skipFn:e})}},wm=xa(Em=Fm.throttleByKey).call(Em,Fm),id=async({fragementLength:a,referenceList:b,asyncMapHandler:c,allFailedhandler:e,promisesCollector:f})=>{let h=0,l,k=0;const p=async()=>{const r=(()=>{var e=h*a;const f=e+a;e=Ma(b).call(b,e,f);return z(e).call(e,c)})();f&&f.push(...r);try{l=await gd(r)}catch(X){if(k+=a,h++,!(k>=b.length))return void await p();
e(X)}t(r).call(r,a=>a.cancel())};return await p(),l},no={[hd.ACCESS_POINT]:{[Ua.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[Ua.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[Ua.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[Ua.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voice service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",
retry:!0},[Ua.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",
retry:!0},[Ua.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[Ua.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[hd.UNILBS]:{[rb.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[rb.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[rb.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[rb.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[rb.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",
retry:!1},[rb.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[rb.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[rb.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[rb.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[rb.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[rb.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[rb.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[hd.STRING_UID_ALLOCATOR]:{[ie.IIIEGAL_APPID]:{desc:"invalid appid",
retry:!1},[ie.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[ie.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}},oo={[F.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[F.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[F.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[F.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[F.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},
[F.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[F.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[F.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[F.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[F.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[F.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[F.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[F.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",
action:"failed"},[F.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[F.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[F.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[F.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[F.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[F.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},
[F.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[F.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[F.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[F.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[F.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[F.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[F.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",
action:"failed"},[F.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[F.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[F.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[F.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[F.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[F.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[F.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",
action:"tryNext"},[F.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[F.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[F.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[F.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[F.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[F.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[F.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",
action:"failed"},[F.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[F.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[F.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[F.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[F.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[F.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",
action:"failed"},[F.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[F.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[F.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[F.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[F.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[F.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[F.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",
action:"recover"},[F.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[F.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[F.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"}};var nr=ub(function(a,b){a.exports=function(){function a(a){for(var b=a.length,c=0,e=0;e<b;){var f=a.charCodeAt(e++);if(0!=(4294967168&f))if(0==(4294965248&f))c+=2;else{if(55296<=f&&56319>=f&&e<b){var h=a.charCodeAt(e);56320==(64512&h)&&(++e,f=((1023&f)<<10)+(1023&h)+65536)}c+=0==(4294901760&f)?
3:4}else c++}return c}function b(a,b,c){c=b+c;for(var e=[],f="";b<c;){var h=a[b++];if(0==(128&h))e.push(h);else if(192==(224&h)){var l=63&a[b++];e.push((31&h)<<6|l)}else if(224==(240&h)){l=63&a[b++];var k=63&a[b++];e.push((31&h)<<12|l<<6|k)}else 240==(248&h)?(h=(7&h)<<18|(63&a[b++])<<12|(63&a[b++])<<6|63&a[b++],65535<h&&(h-=65536,e.push(h>>>10&1023|55296),h=56320|1023&h),e.push(h)):e.push(h);4096<=e.length&&(f+=String.fromCharCode.apply(String,E([],F(e))),e.length=0)}return 0<e.length&&(f+=String.fromCharCode.apply(String,
E([],F(e)))),f}function f(a,b){return 4294967296*a.getInt32(b)+a.getUint32(b+4)}function h(a){var b,c=a.sec;a=a.nsec;if(0<=c&&0<=a&&17179869183>=c){if(0===a&&4294967295>=c){var e=new Uint8Array(4);return(new DataView(e.buffer)).setUint32(0,c),e}var f=c/4294967296;c&=4294967295;return e=new Uint8Array(8),(b=new DataView(e.buffer)).setUint32(0,a<<2|3&f),b.setUint32(4,c),e}e=new Uint8Array(12);(b=new DataView(e.buffer)).setUint32(0,a);b.setUint32(4,Math.floor(c/4294967296));b.setUint32(8,c);return e}
function l(a){var b=a.getTime();a=Math.floor(b/1E3);b=1E6*(b-1E3*a);var c=Math.floor(b/1E9);return{sec:a+c,nsec:b-1E9*c}}function k(a){return a instanceof Date?h(l(a)):null}function p(a){var b=new DataView(a.buffer,a.byteOffset,a.byteLength);switch(a.byteLength){case 4:return{sec:b.getUint32(0),nsec:0};case 8:return a=b.getUint32(0),{sec:4294967296*(3&a)+b.getUint32(4),nsec:a>>>2};case 12:return{sec:f(b,4),nsec:b.getUint32(0)};default:throw Error("Unrecognized data size for timestamp: "+a.length);
}}function m(a){a=p(a);return new Date(1E3*a.sec+a.nsec/1E6)}function n(a){return a instanceof Uint8Array?a:ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a instanceof ArrayBuffer?new Uint8Array(a):Uint8Array.from(a)}function q(a,b){return void 0===b&&(b=O),(new M(b.extensionCodec,b.context,b.maxDepth,b.initialBufferSize,b.sortKeys,b.forceFloat32,b.ignoreUndefined,b.forceIntegerToFloat)).encode(a)}function t(a){return(0>a?"-":"")+"0x"+Math.abs(a).toString(16).padStart(2,
"0")}function B(a,b){return void 0===b&&(b=Z),(new W(b.extensionCodec,b.context,b.maxStrLength,b.maxBinLength,b.maxArrayLength,b.maxMapLength,b.maxExtLength)).decode(a)}function u(a,b){return void 0===b&&(b=Z),(new W(b.extensionCodec,b.context,b.maxStrLength,b.maxBinLength,b.maxArrayLength,b.maxMapLength,b.maxExtLength)).decodeMulti(a)}function v(a){return null!=a[Symbol.asyncIterator]?a:function(a){return ha(this,arguments,function(){var b,c,e,f;return fa(this,function(h){switch(h.label){case 0:b=
a.getReader(),h.label=1;case 1:h.trys.push([1,,9,10]),h.label=2;case 2:return[4,ba(b.read())];case 3:return c=h.sent(),e=c.done,f=c.value,e?[4,ba(void 0)]:[3,5];case 4:return[2,h.sent()];case 5:if(null==f)throw Error("Assertion Failure: value must not be null nor undefined");return[4,ba(f)];case 6:return[4,h.sent()];case 7:return h.sent(),[3,2];case 8:return[3,10];case 9:return b.releaseLock(),[7];case 10:return[2]}})})}(a)}function x(a,b){return void 0===b&&(b=Z),c=this,e=void 0,h=function(){var c;
return function(a,b){function c(c){return function(l){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;k;)try{if(e=1,f&&(h=2&c[0]?f.return:c[0]?f.throw||((h=f.return)&&h.call(f),0):f.next)&&!(h=h.call(f,c[1])).done)return h;switch(f=0,h&&(c=[2&c[0],h.value]),c[0]){case 0:case 1:h=c;break;case 4:return k.label++,{value:c[1],done:!1};case 5:k.label++;f=c[1];c=[0];continue;case 7:c=k.ops.pop();k.trys.pop();continue;default:if(!((h=0<(h=k.trys).length&&h[h.length-1])||
6!==c[0]&&2!==c[0])){k=0;continue}if(3===c[0]&&(!h||c[1]>h[0]&&c[1]<h[3]))k.label=c[1];else if(6===c[0]&&k.label<h[1])k.label=h[1],h=c;else if(h&&k.label<h[2])k.label=h[2],k.ops.push(c);else{h[2]&&k.ops.pop();k.trys.pop();continue}}c=b.call(a,k)}catch(zf){c=[6,zf],f=0}finally{e=h=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,l])}}var e,f,h,l,k={label:0,sent:function(){if(1&h[0])throw h[1];return h[1]},trys:[],ops:[]};return l={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&
(l[Symbol.iterator]=function(){return this}),l}(this,function(e){return c=v(a),[2,(new W(b.extensionCodec,b.context,b.maxStrLength,b.maxBinLength,b.maxArrayLength,b.maxMapLength,b.maxExtLength)).decodeAsync(c)]})},new (f=void 0,f=Promise)(function(a,b){function l(a){try{r(h.next(a))}catch(zh){b(zh)}}function k(a){try{r(h.throw(a))}catch(zh){b(zh)}}function r(b){var c;b.done?a(b.value):(c=b.value,c instanceof f?c:new f(function(a){a(c)})).then(l,k)}r((h=h.apply(c,e||[])).next())});var c,e,f,h}function y(a,
b){void 0===b&&(b=Z);a=v(a);return(new W(b.extensionCodec,b.context,b.maxStrLength,b.maxBinLength,b.maxArrayLength,b.maxMapLength,b.maxExtLength)).decodeArrayStream(a)}function z(a,b){void 0===b&&(b=Z);a=v(a);return(new W(b.extensionCodec,b.context,b.maxStrLength,b.maxBinLength,b.maxArrayLength,b.maxMapLength,b.maxExtLength)).decodeStream(a)}function A(a,b){return void 0===b&&(b=Z),z(a,b)}var C={d:function(a,b){for(var c in b)C.o(b,c)&&!C.o(a,c)&&Object.defineProperty(a,c,{enumerable:!0,get:b[c]})},
o:function(a,b){return Object.prototype.hasOwnProperty.call(a,b)},r:function(a){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(a,Symbol.toStringTag,{value:"Module"});Object.defineProperty(a,"__esModule",{value:!0})}},D={};C.r(D);C.d(D,{DecodeError:function(){return Q},Decoder:function(){return W},EXT_TIMESTAMP:function(){return kc},Encoder:function(){return M},ExtData:function(){return Pa},ExtensionCodec:function(){return Ic},decode:function(){return B},decodeArrayStream:function(){return y},
decodeAsync:function(){return x},decodeMulti:function(){return u},decodeMultiStream:function(){return z},decodeStream:function(){return A},decodeTimestampExtension:function(){return m},decodeTimestampToTimeSpec:function(){return p},encode:function(){return q},encodeDateToTimeSpec:function(){return l},encodeTimeSpecToTimestamp:function(){return h},encodeTimestampExtension:function(){return k}});var F=function(a,b){var c="function"==typeof Symbol&&a[Symbol.iterator];if(!c)return a;var e;a=c.call(a);
var f=[];try{for(;(void 0===b||0<b--)&&!(e=a.next()).done;)f.push(e.value)}catch(mr){var h={error:mr}}finally{try{e&&!e.done&&(c=a.return)&&c.call(a)}finally{if(h)throw h.error;}}return f},E=function(a,b){for(var c=0,e=b.length,f=a.length;c<e;c++,f++)a[f]=b[c];return a},G="undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder,I=G?new TextEncoder:void 0,H=G?"undefined"!=typeof process?200:0:4294967295,L=(null==I?0:I.encodeInto)?function(a,b,c){I.encodeInto(a,b.subarray(c))}:function(a,b,
c){b.set(I.encode(a),c)},J=G?new TextDecoder:null,N=G?"undefined"!=typeof process?200:0:4294967295,Pa=function(a,b){this.type=a;this.data=b},kc=-1,Rd={type:kc,encode:k,decode:m},Ic=function(){function a(){this.builtInEncoders=[];this.builtInDecoders=[];this.encoders=[];this.decoders=[];this.register(Rd)}return a.prototype.register=function(a){var b=a.type,c=a.encode;a=a.decode;0<=b?(this.encoders[b]=c,this.decoders[b]=a):(b=1+b,this.builtInEncoders[b]=c,this.builtInDecoders[b]=a)},a.prototype.tryToEncode=
function(a,b){for(var c=0;c<this.builtInEncoders.length;c++)if(null!=(e=this.builtInEncoders[c])&&null!=(f=e(a,b)))return new Pa(-1-c,f);for(c=0;c<this.encoders.length;c++){var e,f;if(null!=(e=this.encoders[c])&&null!=(f=e(a,b)))return new Pa(c,f)}return a instanceof Pa?a:null},a.prototype.decode=function(a,b,c){var e=0>b?this.builtInDecoders[-1-b]:this.decoders[b];return e?e(a,b,c):new Pa(b,a)},a.defaultCodec=new a,a}(),Sd=function(a){var b="function"==typeof Symbol&&Symbol.iterator,c=b&&a[b],e=
0;if(c)return c.call(a);if(a&&"number"==typeof a.length)return{next:function(){return a&&e>=a.length&&(a=void 0),{value:a&&a[e++],done:!a}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.");},M=function(){function b(a,b,c,e,f,h,l,k){void 0===a&&(a=Ic.defaultCodec);void 0===b&&(b=void 0);void 0===c&&(c=100);void 0===e&&(e=2048);void 0===f&&(f=!1);void 0===h&&(h=!1);void 0===l&&(l=!1);void 0===k&&(k=!1);this.extensionCodec=a;this.context=b;this.maxDepth=c;this.initialBufferSize=
e;this.sortKeys=f;this.forceFloat32=h;this.ignoreUndefined=l;this.forceIntegerToFloat=k;this.pos=0;this.view=new DataView(new ArrayBuffer(this.initialBufferSize));this.bytes=new Uint8Array(this.view.buffer)}return b.prototype.getUint8Array=function(){return this.bytes.subarray(0,this.pos)},b.prototype.reinitializeState=function(){this.pos=0},b.prototype.encode=function(a){return this.reinitializeState(),this.doEncode(a,1),this.getUint8Array()},b.prototype.doEncode=function(a,b){if(b>this.maxDepth)throw Error("Too deep objects in depth "+
b);null==a?this.encodeNil():"boolean"==typeof a?this.encodeBoolean(a):"number"==typeof a?this.encodeNumber(a):"string"==typeof a?this.encodeString(a):this.encodeObject(a,b)},b.prototype.ensureBufferSizeToWrite=function(a){a=this.pos+a;this.view.byteLength<a&&this.resizeBuffer(2*a)},b.prototype.resizeBuffer=function(a){var b=new ArrayBuffer(a);a=new Uint8Array(b);b=new DataView(b);a.set(this.bytes);this.view=b;this.bytes=a},b.prototype.encodeNil=function(){this.writeU8(192)},b.prototype.encodeBoolean=
function(a){!1===a?this.writeU8(194):this.writeU8(195)},b.prototype.encodeNumber=function(a){Number.isSafeInteger(a)&&!this.forceIntegerToFloat?0<=a?128>a?this.writeU8(a):256>a?(this.writeU8(204),this.writeU8(a)):65536>a?(this.writeU8(205),this.writeU16(a)):4294967296>a?(this.writeU8(206),this.writeU32(a)):(this.writeU8(207),this.writeU64(a)):-32<=a?this.writeU8(224|a+32):-128<=a?(this.writeU8(208),this.writeI8(a)):-32768<=a?(this.writeU8(209),this.writeI16(a)):-2147483648<=a?(this.writeU8(210),this.writeI32(a)):
(this.writeU8(211),this.writeI64(a)):this.forceFloat32?(this.writeU8(202),this.writeF32(a)):(this.writeU8(203),this.writeF64(a))},b.prototype.writeStringHeader=function(a){if(32>a)this.writeU8(160+a);else if(256>a)this.writeU8(217),this.writeU8(a);else if(65536>a)this.writeU8(218),this.writeU16(a);else{if(!(4294967296>a))throw Error("Too long string: "+a+" bytes in UTF-8");this.writeU8(219);this.writeU32(a)}},b.prototype.encodeString=function(b){if(b.length>H){var c=a(b);this.ensureBufferSizeToWrite(5+
c);this.writeStringHeader(c);L(b,this.bytes,this.pos)}else{c=a(b);this.ensureBufferSizeToWrite(5+c);this.writeStringHeader(c);for(var e=this.bytes,f=b.length,h=this.pos,l=0;l<f;){var k=b.charCodeAt(l++);if(0!=(4294967168&k)){if(0==(4294965248&k))e[h++]=k>>6&31|192;else{if(55296<=k&&56319>=k&&l<f){var r=b.charCodeAt(l);56320==(64512&r)&&(++l,k=((1023&k)<<10)+(1023&r)+65536)}0==(4294901760&k)?(e[h++]=k>>12&15|224,e[h++]=k>>6&63|128):(e[h++]=k>>18&7|240,e[h++]=k>>12&63|128,e[h++]=k>>6&63|128)}e[h++]=
63&k|128}else e[h++]=k}}this.pos+=c},b.prototype.encodeObject=function(a,b){var c=this.extensionCodec.tryToEncode(a,this.context);if(null!=c)this.encodeExtension(c);else if(Array.isArray(a))this.encodeArray(a,b);else if(ArrayBuffer.isView(a))this.encodeBinary(a);else{if("object"!=typeof a)throw Error("Unrecognized object: "+Object.prototype.toString.apply(a));this.encodeMap(a,b)}},b.prototype.encodeBinary=function(a){var b=a.byteLength;if(256>b)this.writeU8(196),this.writeU8(b);else if(65536>b)this.writeU8(197),
this.writeU16(b);else{if(!(4294967296>b))throw Error("Too large binary: "+b);this.writeU8(198);this.writeU32(b)}a=n(a);this.writeU8a(a)},b.prototype.encodeArray=function(a,b){var c,e=a.length;if(16>e)this.writeU8(144+e);else if(65536>e)this.writeU8(220),this.writeU16(e);else{if(!(4294967296>e))throw Error("Too large array: "+e);this.writeU8(221);this.writeU32(e)}try{for(var f=Sd(a),h=f.next();!h.done;h=f.next())this.doEncode(h.value,b+1)}catch(wh){var l={error:wh}}finally{try{h&&!h.done&&(c=f.return)&&
c.call(f)}finally{if(l)throw l.error;}}},b.prototype.countWithoutUndefined=function(a,b){var c,e=0;try{for(var f=Sd(b),h=f.next();!h.done;h=f.next())void 0!==a[h.value]&&e++}catch(wh){var l={error:wh}}finally{try{h&&!h.done&&(c=f.return)&&c.call(f)}finally{if(l)throw l.error;}}return e},b.prototype.encodeMap=function(a,b){var c,e=Object.keys(a);this.sortKeys&&e.sort();var f=this.ignoreUndefined?this.countWithoutUndefined(a,e):e.length;if(16>f)this.writeU8(128+f);else if(65536>f)this.writeU8(222),
this.writeU16(f);else{if(!(4294967296>f))throw Error("Too large map object: "+f);this.writeU8(223);this.writeU32(f)}try{for(var h=Sd(e),l=h.next();!l.done;l=h.next()){var k=l.value,r=a[k];this.ignoreUndefined&&void 0===r||(this.encodeString(k),this.doEncode(r,b+1))}}catch(Wc){var p={error:Wc}}finally{try{l&&!l.done&&(c=h.return)&&c.call(h)}finally{if(p)throw p.error;}}},b.prototype.encodeExtension=function(a){var b=a.data.length;if(1===b)this.writeU8(212);else if(2===b)this.writeU8(213);else if(4===
b)this.writeU8(214);else if(8===b)this.writeU8(215);else if(16===b)this.writeU8(216);else if(256>b)this.writeU8(199),this.writeU8(b);else if(65536>b)this.writeU8(200),this.writeU16(b);else{if(!(4294967296>b))throw Error("Too large extension object: "+b);this.writeU8(201);this.writeU32(b)}this.writeI8(a.type);this.writeU8a(a.data)},b.prototype.writeU8=function(a){this.ensureBufferSizeToWrite(1);this.view.setUint8(this.pos,a);this.pos++},b.prototype.writeU8a=function(a){var b=a.length;this.ensureBufferSizeToWrite(b);
this.bytes.set(a,this.pos);this.pos+=b},b.prototype.writeI8=function(a){this.ensureBufferSizeToWrite(1);this.view.setInt8(this.pos,a);this.pos++},b.prototype.writeU16=function(a){this.ensureBufferSizeToWrite(2);this.view.setUint16(this.pos,a);this.pos+=2},b.prototype.writeI16=function(a){this.ensureBufferSizeToWrite(2);this.view.setInt16(this.pos,a);this.pos+=2},b.prototype.writeU32=function(a){this.ensureBufferSizeToWrite(4);this.view.setUint32(this.pos,a);this.pos+=4},b.prototype.writeI32=function(a){this.ensureBufferSizeToWrite(4);
this.view.setInt32(this.pos,a);this.pos+=4},b.prototype.writeF32=function(a){this.ensureBufferSizeToWrite(4);this.view.setFloat32(this.pos,a);this.pos+=4},b.prototype.writeF64=function(a){this.ensureBufferSizeToWrite(8);this.view.setFloat64(this.pos,a);this.pos+=8},b.prototype.writeU64=function(a){this.ensureBufferSizeToWrite(8);var b=this.view,c=this.pos;b.setUint32(c,a/4294967296);b.setUint32(c+4,a);this.pos+=8},b.prototype.writeI64=function(a){this.ensureBufferSizeToWrite(8);var b=this.view,c=
this.pos;b.setUint32(c,Math.floor(a/4294967296));b.setUint32(c+4,a);this.pos+=8},b}(),O={},R;G=function(){function a(a,b){void 0===a&&(a=16);void 0===b&&(b=16);this.maxKeyLength=a;this.maxLengthPerKey=b;this.miss=this.hit=0;this.caches=[];for(a=0;a<this.maxKeyLength;a++)this.caches.push([])}return a.prototype.canBeCached=function(a){return 0<a&&a<=this.maxKeyLength},a.prototype.find=function(a,b,c){var e,f=this.caches[c-1];try{var h=function(a){var b="function"==typeof Symbol&&Symbol.iterator,c=b&&
a[b],e=0;if(c)return c.call(a);if(a&&"number"==typeof a.length)return{next:function(){return a&&e>=a.length&&(a=void 0),{value:a&&a[e++],done:!a}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.");}(f),l=h.next();a:for(;!l.done;l=h.next()){var k=l.value,r=k.bytes;for(f=0;f<c;f++)if(r[f]!==a[b+f])continue a;return k.str}}catch(Wc){var p={error:Wc}}finally{try{l&&!l.done&&(e=h.return)&&e.call(h)}finally{if(p)throw p.error;}}return null},a.prototype.store=function(a,
b){var c=this.caches[a.length-1];a={bytes:a,str:b};c.length>=this.maxLengthPerKey?c[Math.random()*c.length|0]=a:c.push(a)},a.prototype.decode=function(a,c,e){var f=this.find(a,c,e);if(null!=f)return this.hit++,f;this.miss++;f=b(a,c,e);a=Uint8Array.prototype.slice.call(a,c,c+e);return this.store(a,f),f},a}();var U=(R=function(a,b){return(R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=
b[c])})(a,b)},function(a,b){function c(){this.constructor=a}if("function"!=typeof b&&null!==b)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");R(a,b);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)}),S=function(a,b){function c(c){return function(l){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;k;)try{if(e=1,f&&(h=2&c[0]?f.return:c[0]?f.throw||((h=f.return)&&h.call(f),0):f.next)&&!(h=h.call(f,c[1])).done)return h;
switch(f=0,h&&(c=[2&c[0],h.value]),c[0]){case 0:case 1:h=c;break;case 4:return k.label++,{value:c[1],done:!1};case 5:k.label++;f=c[1];c=[0];continue;case 7:c=k.ops.pop();k.trys.pop();continue;default:if(!((h=0<(h=k.trys).length&&h[h.length-1])||6!==c[0]&&2!==c[0])){k=0;continue}if(3===c[0]&&(!h||c[1]>h[0]&&c[1]<h[3]))k.label=c[1];else if(6===c[0]&&k.label<h[1])k.label=h[1],h=c;else if(h&&k.label<h[2])k.label=h[2],k.ops.push(c);else{h[2]&&k.ops.pop();k.trys.pop();continue}}c=b.call(a,k)}catch(Wc){c=
[6,Wc],f=0}finally{e=h=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,l])}}var e,f,h,l,k={label:0,sent:function(){if(1&h[0])throw h[1];return h[1]},trys:[],ops:[]};return l={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l},T=function(a){function b(b){c[b]=a[b]&&function(c){return new Promise(function(e,f){!function(a,b,c,e){Promise.resolve(e).then(function(b){a({value:b,done:c})},b)}(e,f,(c=a[b](c)).done,c.value)})}}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");
var c,e=a[Symbol.asyncIterator];return e?e.call(a):(a="function"==typeof __values?__values(a):a[Symbol.iterator](),c={},b("next"),b("throw"),b("return"),c[Symbol.asyncIterator]=function(){return this},c)},P=function(a){return this instanceof P?(this.v=a,this):new P(a)},Y=function(a,b,c){function e(a){p[a]&&(r[a]=function(b){return new Promise(function(c,e){1<m.push([a,b,c,e])||f(a,b)})})}function f(a,b){try{(c=p[a](b)).value instanceof P?Promise.resolve(c.value.v).then(h,l):k(m[0][2],c)}catch(yh){k(m[0][3],
yh)}var c}function h(a){f("next",a)}function l(a){f("throw",a)}function k(a,b){a(b);m.shift();m.length&&f(m[0][0],m[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,p=c.apply(a,b||[]),m=[];return r={},e("next"),e("throw"),e("return"),r[Symbol.asyncIterator]=function(){return this},r},V=new DataView(new ArrayBuffer(0)),da=new Uint8Array(V.buffer);a:{try{V.getInt8(0)}catch(lr){var aa=lr.constructor;break a}throw Error("never reached");}var ca=new aa("Insufficient data"),
ea=new G,Q=function(a){function b(c){c=a.call(this,c)||this;var e=Object.create(b.prototype);return Object.setPrototypeOf(c,e),Object.defineProperty(c,"name",{configurable:!0,enumerable:!1,value:b.name}),c}return U(b,a),b}(Error),W=function(){function a(a,b,c,e,f,h,l,k){void 0===a&&(a=Ic.defaultCodec);void 0===b&&(b=void 0);void 0===c&&(c=4294967295);void 0===e&&(e=4294967295);void 0===f&&(f=4294967295);void 0===h&&(h=4294967295);void 0===l&&(l=4294967295);void 0===k&&(k=ea);this.extensionCodec=a;
this.context=b;this.maxStrLength=c;this.maxBinLength=e;this.maxArrayLength=f;this.maxMapLength=h;this.maxExtLength=l;this.keyDecoder=k;this.pos=this.totalPos=0;this.view=V;this.bytes=da;this.headByte=-1;this.stack=[]}return a.prototype.reinitializeState=function(){this.totalPos=0;this.headByte=-1;this.stack.length=0},a.prototype.setBuffer=function(a){this.bytes=n(a);a=this.bytes;a instanceof ArrayBuffer?a=new DataView(a):(a=n(a),a=new DataView(a.buffer,a.byteOffset,a.byteLength));this.view=a;this.pos=
0},a.prototype.appendBuffer=function(a){if(-1!==this.headByte||this.hasRemaining()){var b=this.bytes.subarray(this.pos);a=n(a);var c=new Uint8Array(b.length+a.length);c.set(b);c.set(a,b.length);this.setBuffer(c)}else this.setBuffer(a)},a.prototype.hasRemaining=function(a){return void 0===a&&(a=1),this.view.byteLength-this.pos>=a},a.prototype.createExtraByteError=function(a){var b=this.view;return new RangeError("Extra "+(b.byteLength-this.pos)+" of "+b.byteLength+" byte(s) found at buffer["+a+"]")},
a.prototype.decode=function(a){this.reinitializeState();this.setBuffer(a);a=this.doDecodeSync();if(this.hasRemaining())throw this.createExtraByteError(this.pos);return a},a.prototype.decodeMulti=function(a){return S(this,function(b){switch(b.label){case 0:this.reinitializeState(),this.setBuffer(a),b.label=1;case 1:return this.hasRemaining()?[4,this.doDecodeSync()]:[3,3];case 2:return b.sent(),[3,1];case 3:return[2]}})},a.prototype.decodeAsync=function(a){var b,c,e,f,h,l,k;return h=this,k=function(){var h,
l,k,r,p,m,w,n;return S(this,function(q){switch(q.label){case 0:h=!1,q.label=1;case 1:q.trys.push([1,6,7,12]),b=T(a),q.label=2;case 2:return[4,b.next()];case 3:if((c=q.sent()).done)return[3,5];if(k=c.value,h)throw this.createExtraByteError(this.totalPos);this.appendBuffer(k);try{l=this.doDecodeSync(),h=!0}catch(zf){if(!(zf instanceof aa))throw zf;}this.totalPos+=this.pos;q.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return r=q.sent(),e={error:r},[3,12];case 7:return q.trys.push([7,,10,11]),
c&&!c.done&&(f=b.return)?[4,f.call(b)]:[3,9];case 8:q.sent(),q.label=9;case 9:return[3,11];case 10:if(e)throw e.error;return[7];case 11:return[7];case 12:if(h){if(this.hasRemaining())throw this.createExtraByteError(this.totalPos);return[2,l]}throw m=(p=this).headByte,w=p.pos,n=p.totalPos,new RangeError("Insufficient data in parsing "+t(m)+" at "+n+" ("+w+" in the current buffer)");}})},new (l=void 0,l=Promise)(function(a,b){function c(a){try{f(k.next(a))}catch(xh){b(xh)}}function e(a){try{f(k.throw(a))}catch(xh){b(xh)}}
function f(b){var f;b.done?a(b.value):(f=b.value,f instanceof l?f:new l(function(a){a(f)})).then(c,e)}f((k=k.apply(h,[])).next())})},a.prototype.decodeArrayStream=function(a){return this.decodeMultiAsync(a,!0)},a.prototype.decodeStream=function(a){return this.decodeMultiAsync(a,!1)},a.prototype.decodeMultiAsync=function(a,b){return Y(this,arguments,function(){var c,e,f,h,l,k,r,p,m;return S(this,function(w){switch(w.label){case 0:c=b,e=-1,w.label=1;case 1:w.trys.push([1,13,14,19]),f=T(a),w.label=2;
case 2:return[4,P(f.next())];case 3:if((h=w.sent()).done)return[3,12];if(l=h.value,b&&0===e)throw this.createExtraByteError(this.totalPos);this.appendBuffer(l);c&&(e=this.readArraySize(),c=!1,this.complete());w.label=4;case 4:w.trys.push([4,9,,10]),w.label=5;case 5:return[4,P(this.doDecodeSync())];case 6:return[4,w.sent()];case 7:return w.sent(),0==--e?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((k=w.sent())instanceof aa))throw k;return[3,10];case 10:this.totalPos+=this.pos,w.label=11;case 11:return[3,
2];case 12:return[3,19];case 13:return r=w.sent(),p={error:r},[3,19];case 14:return w.trys.push([14,,17,18]),h&&!h.done&&(m=f.return)?[4,P(m.call(f))]:[3,16];case 15:w.sent(),w.label=16;case 16:return[3,18];case 17:if(p)throw p.error;return[7];case 18:return[7];case 19:return[2]}})})},a.prototype.doDecodeSync=function(){a:for(;;){var a=this.readHeadByte();if(224<=a)a-=256;else if(192>a){if(!(128>a))if(144>a){if(0!=(a-=128)){this.pushMapState(a);this.complete();continue a}a={}}else if(160>a){if(0!=
(a-=144)){this.pushArrayState(a);this.complete();continue a}a=[]}else a-=160,a=this.decodeUtf8String(a,0)}else if(192===a)a=null;else if(194===a)a=!1;else if(195===a)a=!0;else if(202===a)a=this.readF32();else if(203===a)a=this.readF64();else if(204===a)a=this.readU8();else if(205===a)a=this.readU16();else if(206===a)a=this.readU32();else if(207===a)a=this.readU64();else if(208===a)a=this.readI8();else if(209===a)a=this.readI16();else if(210===a)a=this.readI32();else if(211===a)a=this.readI64();else if(217===
a)a=this.lookU8(),a=this.decodeUtf8String(a,1);else if(218===a)a=this.lookU16(),a=this.decodeUtf8String(a,2);else if(219===a)a=this.lookU32(),a=this.decodeUtf8String(a,4);else if(220===a){if(0!==(a=this.readU16())){this.pushArrayState(a);this.complete();continue a}a=[]}else if(221===a){if(0!==(a=this.readU32())){this.pushArrayState(a);this.complete();continue a}a=[]}else if(222===a){if(0!==(a=this.readU16())){this.pushMapState(a);this.complete();continue a}a={}}else if(223===a){if(0!==(a=this.readU32())){this.pushMapState(a);
this.complete();continue a}a={}}else if(196===a)a=this.lookU8(),a=this.decodeBinary(a,1);else if(197===a)a=this.lookU16(),a=this.decodeBinary(a,2);else if(198===a)a=this.lookU32(),a=this.decodeBinary(a,4);else if(212===a)a=this.decodeExtension(1,0);else if(213===a)a=this.decodeExtension(2,0);else if(214===a)a=this.decodeExtension(4,0);else if(215===a)a=this.decodeExtension(8,0);else if(216===a)a=this.decodeExtension(16,0);else if(199===a)a=this.lookU8(),a=this.decodeExtension(a,1);else if(200===a)a=
this.lookU16(),a=this.decodeExtension(a,2);else{if(201!==a)throw new Q("Unrecognized type byte: "+t(a));a=this.lookU32();a=this.decodeExtension(a,4)}this.complete();for(var b=this.stack;0<b.length;){var c=b[b.length-1];if(0===c.type){if(c.array[c.position]=a,c.position++,c.position!==c.size)continue a;b.pop();a=c.array}else{if(1===c.type){if("string"!=(e=typeof a)&&"number"!==e)throw new Q("The type of key must be string or number but "+typeof a);if("__proto__"===a)throw new Q("The key __proto__ is not allowed");
c.key=a;c.type=2;continue a}if(c.map[c.key]=a,c.readCount++,c.readCount!==c.size){c.key=null;c.type=1;continue a}b.pop();a=c.map}}return a}var e},a.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},a.prototype.complete=function(){this.headByte=-1},a.prototype.readArraySize=function(){var a=this.readHeadByte();switch(a){case 220:return this.readU16();case 221:return this.readU32();default:if(160>a)return a-144;throw new Q("Unrecognized array type byte: "+
t(a));}},a.prototype.pushMapState=function(a){if(a>this.maxMapLength)throw new Q("Max length exceeded: map length ("+a+") > maxMapLengthLength ("+this.maxMapLength+")");this.stack.push({type:1,size:a,key:null,readCount:0,map:{}})},a.prototype.pushArrayState=function(a){if(a>this.maxArrayLength)throw new Q("Max length exceeded: array length ("+a+") > maxArrayLength ("+this.maxArrayLength+")");this.stack.push({type:0,size:a,array:Array(a),position:0})},a.prototype.decodeUtf8String=function(a,c){var e;
if(a>this.maxStrLength)throw new Q("Max length exceeded: UTF-8 byte length ("+a+") > maxStrLength ("+this.maxStrLength+")");if(this.bytes.byteLength<this.pos+c+a)throw ca;var f,h=this.pos+c;this.stateIsMapKey()&&(null===(e=this.keyDecoder)||void 0===e?0:e.canBeCached(a))?e=this.keyDecoder.decode(this.bytes,h,a):a>N?(e=this.bytes.subarray(h,h+a),e=J.decode(e)):e=b(this.bytes,h,a);return f=e,this.pos+=c+a,f},a.prototype.stateIsMapKey=function(){return 0<this.stack.length&&1===this.stack[this.stack.length-
1].type},a.prototype.decodeBinary=function(a,b){if(a>this.maxBinLength)throw new Q("Max length exceeded: bin length ("+a+") > maxBinLength ("+this.maxBinLength+")");if(!this.hasRemaining(a+b))throw ca;var c=this.pos+b;c=this.bytes.subarray(c,c+a);return this.pos+=b+a,c},a.prototype.decodeExtension=function(a,b){if(a>this.maxExtLength)throw new Q("Max length exceeded: ext length ("+a+") > maxExtLength ("+this.maxExtLength+")");var c=this.view.getInt8(this.pos+b);a=this.decodeBinary(a,b+1);return this.extensionCodec.decode(a,
c,this.context)},a.prototype.lookU8=function(){return this.view.getUint8(this.pos)},a.prototype.lookU16=function(){return this.view.getUint16(this.pos)},a.prototype.lookU32=function(){return this.view.getUint32(this.pos)},a.prototype.readU8=function(){var a=this.view.getUint8(this.pos);return this.pos++,a},a.prototype.readI8=function(){var a=this.view.getInt8(this.pos);return this.pos++,a},a.prototype.readU16=function(){var a=this.view.getUint16(this.pos);return this.pos+=2,a},a.prototype.readI16=
function(){var a=this.view.getInt16(this.pos);return this.pos+=2,a},a.prototype.readU32=function(){var a=this.view.getUint32(this.pos);return this.pos+=4,a},a.prototype.readI32=function(){var a=this.view.getInt32(this.pos);return this.pos+=4,a},a.prototype.readU64=function(){var a,b,c=(a=this.view,b=this.pos,4294967296*a.getUint32(b)+a.getUint32(b+4));return this.pos+=8,c},a.prototype.readI64=function(){var a=f(this.view,this.pos);return this.pos+=8,a},a.prototype.readF32=function(){var a=this.view.getFloat32(this.pos);
return this.pos+=4,a},a.prototype.readF64=function(){var a=this.view.getFloat64(this.pos);return this.pos+=8,a},a}(),Z={},fa=function(a,b){function c(c){return function(l){return function(c){if(e)throw new TypeError("Generator is already executing.");for(;k;)try{if(e=1,f&&(h=2&c[0]?f.return:c[0]?f.throw||((h=f.return)&&h.call(f),0):f.next)&&!(h=h.call(f,c[1])).done)return h;switch(f=0,h&&(c=[2&c[0],h.value]),c[0]){case 0:case 1:h=c;break;case 4:return k.label++,{value:c[1],done:!1};case 5:k.label++;
f=c[1];c=[0];continue;case 7:c=k.ops.pop();k.trys.pop();continue;default:if(!((h=0<(h=k.trys).length&&h[h.length-1])||6!==c[0]&&2!==c[0])){k=0;continue}if(3===c[0]&&(!h||c[1]>h[0]&&c[1]<h[3]))k.label=c[1];else if(6===c[0]&&k.label<h[1])k.label=h[1],h=c;else if(h&&k.label<h[2])k.label=h[2],k.ops.push(c);else{h[2]&&k.ops.pop();k.trys.pop();continue}}c=b.call(a,k)}catch(Wc){c=[6,Wc],f=0}finally{e=h=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,l])}}var e,f,h,l,k={label:0,sent:function(){if(1&
h[0])throw h[1];return h[1]},trys:[],ops:[]};return l={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l},ba=function(a){return this instanceof ba?(this.v=a,this):new ba(a)},ha=function(a,b,c){function e(a){p[a]&&(r[a]=function(b){return new Promise(function(c,e){1<m.push([a,b,c,e])||f(a,b)})})}function f(a,b){try{(c=p[a](b)).value instanceof ba?Promise.resolve(c.value.v).then(h,l):k(m[0][2],c)}catch(yh){k(m[0][3],yh)}var c}function h(a){f("next",
a)}function l(a){f("throw",a)}function k(a,b){a(b);m.shift();m.length&&f(m[0][0],m[0][1])}if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,p=c.apply(a,b||[]),m=[];return r={},e("next"),e("throw"),e("return"),r[Symbol.asyncIterator]=function(){return this},r};return D}()}),or=Math.min;L({target:"Array",proto:!0},{copyWithin:[].copyWithin||function(a,b){var c=Jb(this),e=zb(c.length),f=Oc(a,e),h=Oc(b,e),l=2<arguments.length?arguments[2]:void 0;e=or((void 0===
l?e:Oc(l,e))-h,e-f);l=1;for(h<f&&f<h+e&&(l=-1,h+=e-1,f+=e-1);0<e--;)h in c?c[f]=c[h]:delete c[f],f+=l,h+=l;return c}});var ro=Aa("Array").copyWithin,yj=Array.prototype;L({target:"Array",proto:!0,forced:Qc("every")},{every:function(a){return lp(this,a,1<arguments.length?arguments[1]:void 0)}});var pr=Aa("Array").every,Gm=Array.prototype,to=function(a){var b=a.every;return a===Gm||a instanceof Array&&b===Gm.every?pr:b},Af=df.getWeakData,qr=Fa.set,rr=Fa.getterFor,sr=0,Bf=function(a){return a.frozen||
(a.frozen=new Hm)},Hm=function(){this.entries=[]},Ah=function(a,b){return vk(a.entries,function(a){return a[0]===b})};Hm.prototype={get:function(a){if(a=Ah(this,a))return a[1]},has:function(a){return!!Ah(this,a)},set:function(a,b){var c=Ah(this,a);c?c[1]=b:this.entries.push([a,b])},delete:function(a){var b=wk(this.entries,function(b){return b[0]===a});return~b&&this.entries.splice(b,1),!!~b}};var Im={getConstructor:function(a,b,c,e){var f=a(function(a,h){sd(a,f,b);qr(a,{type:b,id:sr++,frozen:void 0});
null!=h&&rd(h,a[e],a,c)}),h=rr(b),l=function(a,b,c){var e=h(a),f=Af($a(b),!0);return!0===f?Bf(e).set(b,c):f[e.id]=c,a};return Pc(f.prototype,{delete:function(a){var b=h(this);if(!qa(a))return!1;var c=Af(a);return!0===c?Bf(b).delete(a):c&&P(c,b.id)&&delete c[b.id]},has:function(a){var b=h(this);if(!qa(a))return!1;var c=Af(a);return!0===c?Bf(b).has(a):c&&P(c,b.id)}}),Pc(f.prototype,c?{get:function(a){var b=h(this);if(qa(a)){var c=Af(a);return!0===c?Bf(b).get(a):c?c[b.id]:void 0}},set:function(a,b){return l(this,
a,b)}}:{add:function(a){return l(this,a,!0)}}),f}},tr=(ub(function(a){var b=Fa.enforce,c=!N.ActiveXObject&&"ActiveXObject"in N,e=Object.isExtensible,f=function(a){return function(){return a(this,arguments.length?arguments[0]:void 0)}};a=a.exports=Ak("WeakMap",f,Im);if(yk&&c){var h=Im.getConstructor(f,"WeakMap",!0);df.REQUIRED=!0;c=a.prototype;var l=c.delete,k=c.has,p=c.get,m=c.set;Pc(c,{delete:function(a){if(qa(a)&&!e(a)){var c=b(this);return c.frozen||(c.frozen=new h),l.call(this,a)||c.frozen.delete(a)}return l.call(this,
a)},has:function(a){if(qa(a)&&!e(a)){var c=b(this);return c.frozen||(c.frozen=new h),k.call(this,a)||c.frozen.has(a)}return k.call(this,a)},get:function(a){if(qa(a)&&!e(a)){var c=b(this);return c.frozen||(c.frozen=new h),k.call(this,a)?p.call(this,a):c.frozen.get(a)}return p.call(this,a)},set:function(a,c){if(qa(a)&&!e(a)){var f=b(this);f.frozen||(f.frozen=new h);k.call(this,a)?m.call(this,a,c):f.frozen.set(a,c)}else m.call(this,a,c);return this}})}}),Math.min),Bh=[].lastIndexOf,Jm=!!Bh&&0>1/[1].lastIndexOf(1,
-0),ur=Qc("lastIndexOf"),Km=Jm||ur?function(a){if(Jm)return Bh.apply(this,arguments)||0;var b=yb(this),c=zb(b.length),e=c-1;1<arguments.length&&(e=tr(e,Yd(arguments[1])));for(0>e&&(e=c+e);0<=e;e--)if(e in b&&b[e]===a)return e||0;return-1}:Bh;L({target:"Array",proto:!0,forced:Km!==[].lastIndexOf},{lastIndexOf:Km});var vr=Aa("Array").lastIndexOf,Lm=Array.prototype,qo=function(a){var b=a.lastIndexOf;return a===Lm||a instanceof Array&&b===Lm.lastIndexOf?vr:b};let so=()=>function(a){var b;a=z(b=window.atob(a).split("")).call(b,
a=>a.charCodeAt(0));return new Uint8Array(a,0,a.length/Uint8Array.BYTES_PER_ELEMENT)}(" "),
kg,tc,Mm=Uint8Array.BYTES_PER_ELEMENT,wr={bytesReceived:"br",frameDropped:"fd",frameReceived:"fr",googJitterReceived:"jr",isAudioMute:"am",isFreeze:"fz",mediaType:"mt",packetsLost:"pl",packetsReceived:"pr",peerId:"pid",id:"id",ssrc:"ssrc",timestamp:"ts",type:"tp",frameRateInput:"fi",frameRateSent:"fs",googRtt:"rt",isVideoMute:"vm"},xr={stats:"sts",state:"st",stream_id:"stid",session_id:"seid",stream_type:"stt",app_id:"aid",channel_key:"ck",channel_name:"cn",sdk_version:"sv",browser:"b",process_id:"pcid",
mode:"m",codec:"c",role:"r",has_changed_gateway:"hcg",ap_response:"ar",extends:"es",details:"d",features:"ft",p2p_id:"ppid",sdp:"sdp",audio:"a",video:"v",attributes:"at",hq:"h",lq:"l",stereo:"str",speech:"spe",extend:"e",pingpongElapse:"ppe"},yr={_message:"m",_type:"t",_id:"id"},zr={join_v2:"j2",publish:"pub",publish_related_stats:"prs",ping:"pi",traffic_stats:"ts",ping_back:"pib",publish_stats:"pubs"},Ch;class Ar{constructor(){}async init(){Ch||(Ch=(await (async()=>(tc||(tc=await po()),{zlibCompress:a=>
{var b,c=new Uint8Array(a);const e=Mm*c.byteLength;a=tc._malloc(e);const f=tc._malloc(3*e);for(let b=0;b<e;b++)tc.HEAP8[a/Mm+b]=c[b];c=tc._zlibCompress(a,e,f);c=new Uint8Array(Ma(b=tc.HEAP8).call(b,f,f+c));return tc._free(a),tc._free(f),c}}))()).zlibCompress);this.zlibCompress=Ch}msgPackCompress(a){return nr.encode(a)}compress(a){let b=x(),c=this.compressKeyAndValue(JSON.parse(A(a))),e=this.msgPackCompress(c);var f=this.zlibCompress(e);f=new Uint8Array([49,49,49,50,...Ub(f)]);return{origin:Ya({},
a),originLength:A(a).length,shortKeyAndValue:c,msgpackSer:e,compressed:f,compressedLength:f.length,time:x()-b}}compressKeyAndValue(a){return this._ObjectKeyCompress(this._typeCompress(a))}_typeCompress(a){let b=a._type;return b?(a._type=zr[b]||b,a):a}_ObjectKeyCompress(a){let b=a._message;if(b){let c=b.stats;c&&(b.stats=this._statsCompress(c));a._message=this._messageCompress(b)}return this._reportCompress(a)}_statsCompress(a){return this._keyCompress(a,wr)}_messageCompress(a){return this._keyCompress(a,
xr)}_reportCompress(a){return this._keyCompress(a,yr)}_keyCompress(a,b){let c={},e=W(a);return Be(e).call(e,(e,h)=>{e=a[h];return b[h]?c[b[h]]=e:c[h]=e,c},c),c}}class Br extends Wa{constructor(a){super();this.lowPriorityQueue=[];this.highPriorityQueue=[];this.AgoraWebSocketManager=a}get queue(){return[...this.highPriorityQueue,...this.lowPriorityQueue]}reset(){this.lowPriorityQueue=[];this.highPriorityQueue=[]}pushMessage(a,b=!1){b?this.highPriorityQueue.push(a):this.lowPriorityQueue.push(a);this.sendMessage()}sendMessage(){let a=
this.queue.length;wb(()=>{this._sendMessage()},5>a?15*a:60+3*(a-4))}_sendMessage(){var a;if(this.queue.length){var b=this.AgoraWebSocketManager.getConnection();if(b&&1===b.readyState){var c=this.queue.shift();return Z(a=this.lowPriorityQueue).call(a,c)?this.lowPriorityQueue.shift():this.highPriorityQueue.shift(),b.send(c.compressed),c}}}}class Dh extends Wa{constructor(a,b,c=!1){super();this.currentURLIndex=this.connectionID=0;this.reconnectMode="tryNext";this._state="closed";this.reconnectCount=
0;this.isCompressorInitSuccess=!1;this.wsDeflateLength=this.wsInflateLength=0;this.name=a;this.retryConfig=b;this.useCompress=c}get url(){return this.websocket?this.websocket.url:null}get state(){return this._state}set state(a){a!==this._state&&(this._state=a,"reconnecting"===this._state?this.emit(ea.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(ea.CONNECTED):"closed"===this._state?this.emit(ea.CLOSED):"failed"===this._state&&this.emit(ea.FAILED))}getConnection(){return this.websocket||
void 0}init(a){let b=(b,e)=>{this.urls=a;const c=this.urls[this.currentURLIndex];this.state="connecting";this.messageSender=new Br(this);this.createWebSocketConnection(c).then(b).catch(e);this.once(ea.CLOSED,()=>e(new q(n.WS_DISCONNECT)));this.once(ea.CONNECTED,()=>b())};return new y((a,e)=>{this.compressor=new Ar;this.compressor.init().then(()=>{var c;k.debug("websocket compressor initialized successfully");this.isCompressorInitSuccess=!0;this.compress=xa(c=this.compressor.compress).call(c,this.compressor);
b(a,e)}).catch(()=>{k.debug("websocket compressor failed to initialize");b(a,e)})})}close(a,b){if(this.currentURLIndex=0,this.reconnectCount=0,this.websocket){this.websocket.onclose=null;this.websocket.onopen=null;this.websocket.onmessage=null;let a=this.websocket;b?wb(()=>a.close(),500):a.close();this.websocket=void 0}this.state=a?"failed":"closed"}reconnect(a,b){if(!this.websocket)return void k.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==a&&(this.reconnectMode=a);
k.debug("[".concat(this.name,"] reconnect is triggered initiative"));a=this.websocket.onclose;this.websocket.onclose=null;this.websocket.close();a&&xa(a).call(a,this.websocket)({code:9999,reason:b})}sendMessage(a,b=!1){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new q(n.WS_ABORT,"websocket is not ready");try{let c=null;if(this.isCompressorInitSuccess&&this.useCompress&&v.WEBSOCKET_COMPRESS)c=this.compress(a),this.setWsInflateData(c);else{if(this.isCompressorInitSuccess&&this.useCompress){let b=
this.compress(a);this.setWsInflateData(b)}let b=A(a);c={compressed:b,compressedLength:b.length,origin:a}}b?this.websocket.send(c.compressed):this.messageSender.pushMessage(c)}catch(c){throw new q(n.WS_ERR,"send websocket message error"+c.toString());}}setWsInflateData(a){this.wsDeflateLength+=a.originLength;this.wsInflateLength+=a.compressedLength}getWsInflateData(){let a=this.wsInflateLength,b=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:a,wsDeflateLength:b}}clearWsInflateData(){this.wsDeflateLength=
this.wsInflateLength=0}async createWebSocketConnection(a){let b=this.connectionID+=1;return new y((c,e)=>{var f,h;this.websocket&&(this.websocket.onclose=null,this.websocket.close());v.GATEWAY_WSS_ADDRESS&&Hd(f=this.name).call(f,"gateway")&&(a=v.GATEWAY_WSS_ADDRESS);k.debug(m(h="[".concat(this.name,"] start connect, url: ")).call(h,a));try{this.websocket=new WebSocket(a),this.websocket.binaryType="arraybuffer"}catch(r){var l;f=new q(n.WS_ERR,"init websocket failed! Error: ".concat(r.toString()));
return k.error(m(l="[".concat(this.name,"]")).call(l,f)),void e(f)}jb(5E3).then(()=>{b===this.connectionID&&this.websocket&&this.websocket.readyState!==WebSocket.OPEN&&this.websocket&&this.websocket.close()});this.websocket.onopen=()=>{k.debug("[".concat(this.name,"] websocket opened:"),a);this.reconnectMode="retry";this.state="connected";this.reconnectCount=0;c()};this.websocket.onclose=async a=>{var b,f,h,l;if(k.debug(m(b=m(f=m(h=m(l="[".concat(this.name,"] websocket close ")).call(l,this.websocket&&
this.websocket.url,", code: ")).call(h,a.code,", reason: ")).call(f,a.reason,", current mode: ")).call(b,this.reconnectMode)),this.reconnectCount<this.retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=a.reason,this.state="reconnecting");b=Hc(this,ea.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode;b=await this.reconnectWithAction(b);if("closed"===this.state)return void k.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!b)return e(new q(n.WS_DISCONNECT,
"websocket reconnect failed: ".concat(a.code))),void this.close(!0);c()}else e(new q(n.WS_DISCONNECT,"websocket close: ".concat(a.code))),this.close()};this.websocket.onmessage=a=>{this.emit(ea.ON_MESSAGE,a)}})}async reconnectWithAction(a,b){var c,e;if(!b&&this.reconnectCount>=this.retryConfig.maxRetryCount||!this.urls||"closed"===this.state)return!1;this.onlineReconnectListener||pb.networkState!==Gb.OFFLINE||(this.onlineReconnectListener=pb.onlineWaiter&&pb.onlineWaiter.then(()=>{this.onlineReconnectListener=
void 0}));b=function(a,b){return Math.min(b.maxRetryTimeout,b.timeout*Math.pow(b.timeoutFactor,a))}(this.reconnectCount,this.retryConfig);if(k.debug(m(c=m(e="[".concat(this.name,"] wait ")).call(e,b,"ms to reconnect websocket, mode: ")).call(c,a)),await y.race([jb(b),this.onlineReconnectListener||new y(()=>{})]),"closed"===this.state)return!1;this.reconnectCount+=1;try{if("retry"===a)await this.createWebSocketConnection(this.urls[this.currentURLIndex]);else if("tryNext"===a){var f,h;if(this.currentURLIndex+=
1,this.currentURLIndex>=this.urls.length)return await this.reconnectWithAction("recover");k.debug(m(f=m(h="[".concat(this.name,"] websocket url length: ")).call(h,this.urls.length," current index: ")).call(f,this.currentURLIndex));await this.createWebSocketConnection(this.urls[this.currentURLIndex])}else"recover"===a&&(k.debug("[".concat(this.name,"] request new urls")),this.urls=await Ia(this,ea.REQUEST_NEW_URLS),this.currentURLIndex=0,await this.createWebSocketConnection(this.urls[this.currentURLIndex]));
return!0}catch(l){return k.error("[".concat(this.name,"] reconnect failed"),l.toString()),await this.reconnectWithAction(a)}}}class Cr{constructor(a){this.input=[];this.size=a}add(a){var b;(this.input.push(a),this.input.length>this.size)&&Ra(b=this.input).call(b,0,1)}mean(){var a;return 0===this.input.length?0:Be(a=this.input).call(a,(a,c)=>a+c)/this.input.length}}class Dr extends Wa{constructor(a){super();this._connectionState=Da.CLOSED;this.openConnectionTime=x();this.lastMsgTime=x();this.uploadCache=
[];this.rttRolling=new Cr(5);this.pingpongTimeoutCount=0;this.onWebsocketMessage=a=>{if(a.data instanceof ArrayBuffer)return void this.emit(T.ON_BINARY_DATA,a.data);a=JSON.parse(a.data);if(this.lastMsgTime=x(),Object.prototype.hasOwnProperty.call(a,"_id")){let b="res-@".concat(a._id);this.emit(b,a._result,a._message)}else if(Object.prototype.hasOwnProperty.call(a,"_type")&&(this.emit(a._type,a._message),a._type===fa.ON_NOTIFICATION&&this.handleNotification(a._message),a._type===fa.ON_USER_BANNED))switch(a._message.error_code){case 14:this.close("UID_BANNED");
break;case 15:this.close("IP_BANNED");break;case 16:this.close("CHANNEL_BANNED")}};this.clientId=a.clientId;this.spec=a;this.websocket=new Dh("gateway-".concat(this.clientId),this.spec.retryConfig,!0);this.handleWebsocketEvents();window.addEventListener("offline",()=>{this.connectionState===Da.CONNECTED&&this.reconnect("retry",kb.OFFLINE)})}get connectionState(){return this._connectionState}set connectionState(a){a!==this._connectionState&&(this._connectionState=a,a===Da.CONNECTED?this.emit(T.WS_CONNECTED):
a===Da.RECONNECTING?this.emit(T.WS_RECONNECTING,this._websocketReconnectReason):a===Da.CLOSED&&this.emit(T.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}async request(a,b,c,e){var f,h,l,r,p;let w=va(6,"");var X={_id:w,_type:a,_message:b};let K=this.websocket.connectionID;var t=()=>new y((a,b)=>{if(this.connectionState===Da.CONNECTED)return a();const c=
()=>{this.off(T.WS_CLOSED,e);a()},e=()=>{this.off(T.WS_CONNECTED,c);b(new q(n.WS_ABORT))};this.once(T.WS_CONNECTED,c);this.once(T.WS_CLOSED,e)});if(this.connectionState!==Da.CONNECTING&&this.connectionState!==Da.RECONNECTING||a===ia.JOIN||a===ia.REJOIN||await t(),this.websocket.sendMessage(X,!0),!e){X=new y((c,e)=>{let f=!1;const h=(e,h)=>{f=!0;c({isSuccess:"success"===e,message:h||{}});this.off(T.WS_CLOSED,l);this.off(T.WS_RECONNECTING,l);this.emit(T.REQUEST_SUCCESS,a,b)};this.once("res-@".concat(w),
h);const l=()=>{e(new q(n.WS_ABORT,"type: ".concat(a)));this.off(T.WS_CLOSED,l);this.off(T.WS_RECONNECTING,l);this.off("res-@".concat(w),h)};this.once(T.WS_CLOSED,l);this.once(T.WS_RECONNECTING,l);jb(v.SIGNAL_REQUEST_TIMEOUT).then(()=>{this.websocket.connectionID!==K||f||(k.warning("ws request timeout, type: ".concat(a)),this.emit(T.REQUEST_TIMEOUT,a,b))})});e=null;try{e=await X}catch(B){if(this.connectionState===Da.CLOSED||a===ia.LEAVE)throw new q(n.WS_ABORT);return!this.spec.forceWaitGatewayResponse||
c?B.throw():a===ia.JOIN||a===ia.REJOIN?null:(await t(),await this.request(a,b))}if(e.isSuccess)return e.message;c=Number(e.message.error_code||e.message.code);t=wj(c);X=new q(n.UNEXPECTED_RESPONSE,m(f="".concat(t.desc,": ")).call(f,e.message.error_str),{code:c,data:e.message});return"success"===t.action?e.message:(k.warning(m(h=m(l=m(r=m(p="[".concat(this.websocket.connectionID,"] unexpected response from type ")).call(p,a,", error_code: ")).call(r,c,", message: ")).call(l,t.desc,", action: ")).call(h,
t.action)),"failed"===t.action?X.throw():"quit"===t.action?(this.initError=X,this.close(),X.throw()):(c===F.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=e.message.option,k.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",kb.MULTI_IP)):this.reconnect(t.action,kb.SERVER_ERROR),a===ia.JOIN||a===ia.REJOIN?null:await this.request(a,b)))}}waitMessage(a,b){return new y(c=>{let e=f=>{b&&!b(f)||(this.off(a,e),c(f))};this.on(a,e)})}upload(a,b){a={_type:a,_message:b};try{this.websocket.sendMessage(a)}catch(e){b=
v.MAX_UPLOAD_CACHE||50;var c;(this.uploadCache.push(a),this.uploadCache.length>b)&&Ra(c=this.uploadCache).call(c,0,1);0<this.uploadCache.length&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{var a;if(this.connectionState===Da.CONNECTED){var b=Ra(a=this.uploadCache).call(a,0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0);this.upload(b._type,b._message)}},v.UPLOAD_CACHE_INTERVAL||2E3))}}send(a,b){this.websocket.sendMessage({_type:a,
_message:b})}init(a){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,new y((b,c)=>{this.once(T.WS_CONNECTED,()=>b(this.joinResponse));this.once(T.WS_CLOSED,()=>c(this.initError||new q(n.WS_ABORT)));this.connectionState=Da.CONNECTING;this.websocket.init(a).catch(c);this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer);this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2E4)})}close(a){this.pingpongTimer&&
(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0);this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0);this.joinResponse=this.reconnectToken=void 0;this._disconnectedReason=a||"LEAVE";this.connectionState=Da.CLOSED;this.websocket.close()}async join(){var a;if(!this.joinResponse){var b=Pd(this,T.REQUEST_JOIN_INFO);b=await this.request(ia.JOIN,b);if(!b)return this.emit(T.REPORT_JOIN_GATEWAY,
n.TIMEOUT,this.url||""),!1;this.joinResponse=b;this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Da.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(xa(a=this.handlePingPong).call(a,this),3E3),!0}async rejoin(){var a,b;if(!this.reconnectToken)throw new q(n.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");var c=Pd(this,T.REQUEST_REJOIN_INFO);c.token=this.reconnectToken;c=await this.request(ia.REJOIN,c);return!!c&&
(this.connectionState=Da.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(xa(a=this.handlePingPong).call(a,this),3E3),c.peers&&t(b=c.peers).call(b,a=>{this.emit(fa.ON_USER_ONLINE,{uid:a.uid});a.audio_mute?this.emit(fa.MUTE_AUDIO,{uid:a.uid}):this.emit(fa.UNMUTE_AUDIO,{uid:a.uid});a.video_mute?this.emit(fa.MUTE_VIDEO,{uid:a.uid}):this.emit(fa.UNMUTE_VIDEO,{uid:a.uid});a.audio_enable_local?this.emit(fa.ENABLE_LOCAL_AUDIO,{uid:a.uid}):this.emit(fa.DISABLE_LOCAL_AUDIO,
{uid:a.uid});a.video_enable_local?this.emit(fa.ENABLE_LOCAL_VIDEO,{uid:a.uid}):this.emit(fa.DISABLE_LOCAL_VIDEO,{uid:a.uid});a.audio||a.video||this.emit(fa.ON_REMOVE_STREAM,{uid:a.uid,uint_id:a.uint_id});a.audio&&this.emit(fa.ON_ADD_AUDIO_STREAM,{uid:a.uid,uint_id:a.uint_id,audio:!0});a.video&&this.emit(fa.ON_ADD_VIDEO_STREAM,{uid:a.uid,uint_id:a.uint_id,video:!0})}),!0)}reconnect(a,b){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0);
this.websocket.reconnect(a,b)}handleNotification(a){k.debug("[".concat(this.clientId,"] receive notification: "),a);a=wj(a.code);if("success"!==a.action){if("failed"!==a.action)return"quit"===a.action?("ERR_REPEAT_JOIN_CHANNEL"===a.desc&&this.close("UID_BANNED"),void this.close()):void this.reconnect(a.action,kb.SERVER_ERROR);k.error("[".concat(this.clientId,"] ignore error: "),a.desc)}}handlePingPong(){if(this.websocket&&"connected"===this.websocket.state){0<this.pingpongTimeoutCount&&this.rttRolling.add(3E3);
this.pingpongTimeoutCount+=1;var a=v.PING_PONG_TIME_OUT,b=x();this.pingpongTimeoutCount>=a&&(k.warning("PINGPONG Timeout. Last Socket Message: ".concat(b-this.lastMsgTime,"ms")),b-this.lastMsgTime>v.WEBSOCKET_TIMEOUT_MIN)?this.reconnect("retry",kb.TIMEOUT):this.request(ia.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;let a=x()-b;this.rttRolling.add(a);v.REPORT_STATS&&this.send(ia.PING_BACK,{pingpongElapse:a})}).catch(a=>{})}}handleWsInflateData(){let {wsInflateLength:a,wsDeflateLength:b}=
this.websocket.getWsInflateData();0!==a&&0!==b&&this.upload(Lb.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:b,ws_inflate_length:a})}handleWebsocketEvents(){this.websocket.on(ea.ON_MESSAGE,this.onWebsocketMessage);this.websocket.on(ea.CLOSED,()=>{this.connectionState=Da.CLOSED});this.websocket.on(ea.FAILED,()=>{this._disconnectedReason="NETWORK_ERROR";this.connectionState=Da.CLOSED});this.websocket.on(ea.RECONNECTING,a=>{this._websocketReconnectReason=a;this.joinResponse=void 0;this.connectionState===
Da.CONNECTED?this.connectionState=Da.RECONNECTING:this.connectionState=Da.CONNECTING});this.websocket.on(ea.WILL_RECONNECT,(a,b)=>{if(Pd(this,T.IS_P2P_DISCONNECTED)&&"retry"===a)return this.reconnectToken=void 0,this.emit(T.NEED_RENEW_SESSION),this.emit(T.DISCONNECT_P2P),b("tryNext");"retry"!==a&&(this.reconnectToken=void 0,this.emit(T.NEED_RENEW_SESSION),this.emit(T.DISCONNECT_P2P));b(a)});this.websocket.on(ea.CONNECTED,()=>{this.openConnectionTime=x();this.reconnectToken?this.rejoin().catch(a=>
{var b;k.warning(m(b="[".concat(this.clientId,"] rejoin failed ")).call(b,a));this.reconnect("tryNext",kb.SERVER_ERROR)}):this.join().catch(a=>{if(this.emit(T.REPORT_JOIN_GATEWAY,a.message||a.code,this.url||""),a instanceof q&&a.code===n.UNEXPECTED_RESPONSE&&a.data.code===F.ERR_NO_AUTHORIZED)return k.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",kb.SERVER_ERROR);k.error("[".concat(this.clientId,"] join gateway request failed"),a.toString());
this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",kb.SERVER_ERROR):(this.initError=a,this.close())})});this.websocket.on(ea.REQUEST_NEW_URLS,(a,b)=>{Ia(this,T.REQUEST_RECOVER,this.multiIpOption).then(a).catch(b)})}}let Eh=new ba;class Er extends Wa{constructor(a){super();this.inChannelInfo={joinAt:null,duration:0};this._state="DISCONNECTED";this.needToSendUnpubUnsub=new ba;this.hasChangeBGPAddress=this.isSignalRecover=!1;this.joinGatewayStartTime=0;this._signalTimeout=!1;this.clientId=a.clientId;
this.spec=a;this.signal=new Dr(lg({},a,{retryConfig:a.websocketRetryConfig}));this._statsCollector=a.statsCollector;this.role=a.role||"audience";this._clientRoleOptions=a.clientRoleOptions;this.handleSignalEvents()}get state(){return this._state}set state(a){if(a!==this._state){var b=this._state;this._state=a;"DISCONNECTED"===a&&this._disconnectedReason?this.emit(Ja.CONNECTION_STATE_CHANGE,a,b,this._disconnectedReason):this.emit(Ja.CONNECTION_STATE_CHANGE,a,b)}}async join(a,b){var c,e;"disabled"!==
a.cloudProxyServer&&(this.hasChangeBGPAddress=!0);let f=x();var h=Eh.get(a.cname);if(h||(h=new ba,Eh.set(a.cname,h)),h.has(a.uid))throw h=new q(n.UID_CONFLICT),u.joinGateway(a.sid,{lts:f,succ:!1,ec:h.message,addr:null,uid:a.uid,cid:a.cid}),h;h.set(a.uid,!0);this.joinInfo=a;this.key=b;b=a.proxyServer?z(c=a.gatewayAddrs).call(c,b=>{var c,e;b=b.split(":");return m(c=m(e="wss://".concat(a.proxyServer,"/ws/?h=")).call(e,b[0],"&p=")).call(c,b[1])}):z(e=a.gatewayAddrs).call(e,a=>"wss://".concat(a));c=0;
this.joinGatewayStartTime=f;try{c=(await this.signal.init(b)).uid}catch(l){throw k.error("[".concat(this.clientId,"] User join failed"),l.toString()),u.joinGateway(a.sid,{lts:f,succ:!1,ec:l.message,addr:this.signal.url,uid:a.uid,cid:a.cid}),h.delete(a.uid),this.signal.close(),l;}return this.state="CONNECTED",this.inChannelInfo.joinAt=x(),k.debug("[".concat(this.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(a=>{k.warning("[".concat(this.clientId,
"] get traffic stats error"),a.toString())})},3E3),this.networkQualityInterval=window.setInterval(()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(Ja.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(Ja.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(Ja.NETWORK_QUALITY,{uplinkNetworkQuality:rj(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:rj(this._statsCollector.trafficStats.B_dnq)}):
this.emit(Ja.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2E3),c}async leave(a=!1){if("DISCONNECTED"!==this.state){this.state="DISCONNECTING";try{if(!a&&this.signal.connectionState===Da.CONNECTED){var b=this.signal.request(ia.LEAVE,void 0,!0);await (3E3===1/0?b:y.race([b,mo(3E3)]))}}catch(c){k.warning("[".concat(this.clientId,"] leave request failed, ignore"),c)}this.signal.close();this.reset();this.state="DISCONNECTED"}}async publish(a,b){if(!this.joinInfo)throw new q(n.UNEXPECTED_ERROR,
"publish no joinInfo");let c=a.getUserId(),e=a.videoTrack?function(a){var b;a=a._encoderConfig;if(!a)return{};const c={resolution:a.width&&a.height?m(b="".concat(wc(a.width),"x")).call(b,wc(a.height)):void 0,maxVideoBW:a.bitrateMax,minVideoBW:a.bitrateMin};return"number"==typeof a.frameRate?(c.maxFrameRate=a.frameRate,c.minFrameRate=a.frameRate):a.frameRate&&(c.maxFrameRate=a.frameRate.max||a.frameRate.ideal||a.frameRate.exact||a.frameRate.min,c.minFrameRate=a.frameRate.min||a.frameRate.ideal||a.frameRate.exact||
a.frameRate.max),c}(a.videoTrack):{};if(a.on(E.NEED_ANSWER,(f,h,l)=>{var r;let p={state:"offer",stream_type:b,p2p_id:a.pc.ID,sdp:A(f),audio:!!a.audioTrack,video:!!a.videoTrack,screen:a.videoTrack&&-1!==J(r=a.videoTrack._hints).call(r,Yb.SCREEN_TRACK),attributes:e,dtx:a.audioTrack instanceof ne&&a.audioTrack._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1,mode:this.spec.mode,codec:this.spec.codec,extend:v.PUB_EXTEND};a.audioTrack&&a.audioTrack instanceof ab&&(a.audioTrack&&(r={stream_id:this.joinInfo&&
(this.joinInfo.stringUid||this.joinInfo.uid),action:""},a.audioTrack.isActive?r.action="unmute_local_audio":r.action="mute_local_audio",this.sendControl(r)),a.videoTrack&&(r={stream_id:this.joinInfo&&(this.joinInfo.stringUid||this.joinInfo.uid),action:""},a.videoTrack.muted?r.action="mute_local_video":r.action="unmute_local_video",this.sendControl(r)));this.signal.request(ia.PUBLISH,p,!0).then(a=>{c&&this.needToSendUnpubUnsub.set(c,!0);h(JSON.parse(a.sdp))}).catch(b=>{if(f.retry&&b.data&&b.data.code===
F.ERR_PUBLISH_REQUEST_INVALID)return k.warning("[".concat(this.clientId,"] receiver publish error code, retry"),b.toString()),Ia(a,E.NEED_UNPUB).then(()=>{f.retry=!1;Ia(a,E.NEED_ANSWER,f).then(h).catch(l)});b.code!==n.WS_ABORT&&l(b)})}),a.on(E.NEED_RENEGOTIATE,(c,e,l)=>{this.signal.request(ia.PUBLISH,{state:"negotiation",stream_type:b,p2p_id:a.pc.ID,sdp:c},!0).then(a=>{e(JSON.parse(a.sdp))}).catch(a=>{a.code!==n.WS_ABORT&&l(a)})}),a.on(E.NEED_UNPUB,e=>c&&!this.needToSendUnpubUnsub.has(c)?e(!1):"RECONNECTING"===
this.state?e(!0):void this.signal.request(ia.UNPUBLISH,{stream_id:a.getUserId(),stream_type:b},!0).then(()=>e(!1)).catch(a=>{k.warning("unpublish warning: ",a);e(!0)})),a.on(E.NEED_UPLOAD,(a,c)=>{this.signal.upload(a,{stream_type:b,stats:c})}),a.on(E.NEED_SIGNAL_RTT,a=>{a(this.signal.rtt)}),a.on(E.NEED_CONTROL,(a,b,c)=>{if("video"===a.type&&a.muted)a="mute_local_video";else if("video"!==a.type||a.muted)if("audio"===a.type&&a.muted)a="mute_local_audio";else{if("audio"!==a.type||a.muted)return;a="unmute_local_audio"}else a=
"unmute_local_video";this.sendControl({stream_id:this.joinInfo&&(this.joinInfo.stringUid||this.joinInfo.uid),action:a}).then(b).catch(c)}),"RECONNECTING"!==this.state){if("CONNECTED"!==this.state)return(new q(n.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state))).throw();await a.startP2PConnection()}else a.readyToReconnectPC()}async subscribe(a){if(!this.joinInfo)throw new q(n.UNEXPECTED_ERROR,"subscribe no joinInfo");let b=a.getUserId();if(a.on(E.NEED_ANSWER,(c,e,f)=>
{var h=a.subscribeOptions;h={stream_id:a.getUserId(),audio:!!h.audio,video:!!h.video,mode:this.spec.mode,codec:this.spec.codec,p2p_id:a.pc.ID,sdp:A(c),tcc:!!v.SUBSCRIBE_TCC,extend:v.SUB_EXTEND};this.signal.request(ia.SUBSCRIBE,h,!0).then(a=>{this.needToSendUnpubUnsub.set(b,!0);e(JSON.parse(a.sdp))}).catch(b=>{if(c.retry&&b.data&&b.data.code===F.ERR_SUBSCRIBE_REQUEST_INVALID)return k.warning("[".concat(this.clientId,"] receiver subscribe error code, retry"),b.toString()),Ia(a,E.NEED_UNSUB).then(()=>
{c.retry=!1;Ia(a,E.NEED_ANSWER,c).then(e).catch(f)});b.code!==n.WS_ABORT&&f(b)})}),a.on(E.NEED_UNSUB,c=>this.needToSendUnpubUnsub.has(b)?"RECONNECTING"===this.state?c(!0):void this.signal.request(ia.UNSUBSCRIBE,{stream_id:a.getUserId()},!0).then(()=>c(!1)).catch(a=>{k.warning("unsubscribe warning",a);c(!0)}):c(!1)),a.on(E.NEED_UPLOAD,(b,e)=>{this.signal.upload(b,{stream_id:a.getUserId(),stats:e})}),a.on(E.NEED_SIGNAL_RTT,a=>{a(this.signal.rtt)}),"RECONNECTING"!==this.state){if("CONNECTED"!==this.state)return(new q(n.INVALID_OPERATION,
"can not subscribe when connection state is ".concat(this.state))).throw();await a.startP2PConnection()}else a.readyToReconnectPC()}async subscribeChange(a,b){var c,e;if(!this.joinInfo)throw new q(n.UNEXPECTED_ERROR,"subscribe no joinInfo");if(await a.setSubscribeOptions(b),"RECONNECTING"!==this.state){if("CONNECTED"!==this.state)return(new q(n.INVALID_OPERATION,"can not subscribe change when connection state is ".concat(this.state))).throw();k.debug(m(c=m(e="[".concat(this.clientId,"] send subscribe change, audio: ")).call(e,
b.audio,", video: ")).call(c,b.video));await this.signal.request(ia.SUBSCRIBE_CHANGE,{stream_id:a.getUserId(),audio:!!b.audio,video:!!b.video},!0)}}async sendControl(a){this.signal.request(ia.CONTROL,a,!0,!0)}async unsubscribe(a){await a.closeP2PConnection()}getGatewayInfo(){return this.signal.request(ia.GATEWAY_INFO)}renewToken(a){return this.signal.request(ia.RENEW_TOKEN,{token:a})}async setClientRole(a,b){if(b&&(this._clientRoleOptions=Ya({},b)),"CONNECTED"!==this.state)return void(this.role=a);
await this.signal.request(ia.SET_CLIENT_ROLE,{role:a,level:"audience"===a?this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:0});this.role=a}async setRemoteVideoStreamType(a,b){await this.signal.request(ia.SWITCH_VIDEO_STREAM,{stream_id:a,stream_type:b})}async setStreamFallbackOption(a,b){await this.signal.request(ia.SET_FALLBACK_OPTION,{stream_id:a,fallback_type:b})}async pickSVCLayer(a,b){await this.signal.request(ia.PICK_SVC_LAYER,{stream_id:a,spatial_layer:b.spatialLayer,
temporal_layer:b.temporalLayer})}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=x()-this.inChannelInfo.joinAt),lg({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(ia.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=x()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){let a=
Eh.get(this.joinInfo.cname);a&&a.delete(this.joinInfo.uid)}this.needToSendUnpubUnsub=new ba;this.key=this.joinInfo=void 0;this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(this.joinInfo){var a=(a=(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex])||"").match(/(wss:\/\/)?([^:]+):(\d+)/))?{username:Oa.username,password:Oa.password,turnServerURL:a[2],
tcpport:wa(a[3])+30,udpport:wa(a[3])+30,forceturn:!1}:null;this.joinInfo.turnServer.serversFromGateway=[];a&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(lg({},Oa,{turnServerURL:a.turnServerURL,tcpport:a.tcpport,udpport:a.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}}async updateTrafficStats(){var a;if("CONNECTED"===this.state){var b=await this.signal.request(ia.TRAFFIC_STATS,void 0,
!0);b.timestamp=x();t(a=b.peer_delay).call(a,a=>{var b;let c=this._statsCollector.trafficStats&&U(b=this._statsCollector.trafficStats.peer_delay).call(b,b=>b.peer_uid===a.peer_uid);c&&c.B_st!==a.B_st&&xb(()=>{this.emit(Ja.STREAM_TYPE_CHANGE,a.peer_uid,a.B_st)})});this._statsCollector.updateTrafficStats(b)}}getJoinMessage(){if(!this.joinInfo||!this.key)throw new q(n.UNEXPECTED_ERROR,"can not generate join message, no join info");let a=Ya({},this.joinInfo.apResponse);var b=v.REPORT_APP_SCENARIO;if("string"!=
typeof b)try{b=A(b)}catch(c){b=void 0}b&&128<b.length&&(b=void 0);b={session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:ob,browser:navigator.userAgent,process_id:v.PROCESS_ID,mode:this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:a,extend:v.JOIN_EXTEND,details:{6:this.joinInfo.stringUid,cservice_map:"proxy3"===this.joinInfo.cloudProxyServer?"1":void 0},features:{rejoin:!0},
optionalInfo:this.joinInfo.optionalInfo,appScenario:b};return this.joinInfo.stringUid&&(b.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(b.aes_mode=this.joinInfo.aesmode,v.ENCRYPT_AES?(b.aes_secret=this.joinInfo.aespassword,b.aes_encrypt=!0):b.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(b.aes_salt=this.joinInfo.aessalt)),a.addresses[this.signal.websocket.currentURLIndex]&&(b.ap_response.ticket=a.addresses[this.signal.websocket.currentURLIndex].ticket,
delete a.addresses),b}getRejoinMessage(){if(!this.joinInfo)throw new q(n.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(T.WS_RECONNECTING,a=>{this.joinInfo&&u.WebSocketQuit(this.joinInfo.sid,{lts:x(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:a||kb.NETWORK_ERROR});
this.joinInfo&&(this.state="RECONNECTING",u.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode}),this.isSignalRecover=!1,this.joinGatewayStartTime=x())});this.signal.on(T.WS_CLOSED,a=>{let b;switch(a){case "LEAVE":b=kb.LEAVE;break;case "UID_BANNED":case "IP_BANNED":case "CHANNEL_BANNED":case "SERVER_ERROR":b=kb.SERVER_ERROR;break;default:b=kb.NETWORK_ERROR}k.debug("[signal] websocket closed, reason: ".concat(b||
"undefined -> "+kb.NETWORK_ERROR));this.joinInfo&&u.WebSocketQuit(this.joinInfo.sid,{lts:x(),succ:"LEAVE"===a?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:b});this.reset();this._disconnectedReason=a;this.state="DISCONNECTED"});this.signal.on(T.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){var a,b,c;"audience"===this.role&&this._clientRoleOptions&&this._clientRoleOptions.level&&(k.debug(m(a=m(b=m(c="[".concat(this.clientId,
"] patch to send set client role, role: ")).call(c,this.role,", mode: ")).call(b,this.spec.mode,", level: ")).call(a,this._clientRoleOptions&&this._clientRoleOptions.level)),this.setClientRole(this.role,this._clientRoleOptions));if(u.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid}),this.joinInfo.useLocalAccessPoint){a=this.signal.url&&this.signal.url.match(/wss:\/\/([^:]+):(\d+)/);
var e;if(!a)return void k.error(m(e="[".concat(this.clientId,"] set local access point after joined failed: ")).call(e,a));eb("EVENT_REPORT_DOMAIN",a[1]);eb("EVENT_REPORT_BACKUP_DOMAIN",a[1]);eb("LOG_UPLOAD_SERVER","".concat(a[1],":6444"))}}});this.signal.on(fa.ON_UPLINK_STATS,a=>{this._statsCollector.updateUplinkStats(a)});this.signal.on(T.REQUEST_RECOVER,(a,b,c)=>{if(!this.joinInfo)return c(new q(n.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));a&&(this.joinInfo.multiIP=a,this.hasChangeBGPAddress=
!0);this.isSignalRecover=!0;Ia(this,Ja.REQUEST_NEW_GATEWAY_LIST).then(b).catch(c)});this.signal.on(T.REQUEST_JOIN_INFO,a=>{a(this.getJoinMessage())});this.signal.on(T.REQUEST_REJOIN_INFO,a=>{a(this.getRejoinMessage())});this.signal.on(T.REPORT_JOIN_GATEWAY,(a,b)=>{this.joinInfo&&u.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:a,addr:b,uid:this.joinInfo.uid,cid:this.joinInfo.cid})});this.signal.on(T.IS_P2P_DISCONNECTED,a=>{a(Pd(this,Ja.IS_P2P_DISCONNECTED))});this.signal.on(T.DISCONNECT_P2P,
()=>{this.needToSendUnpubUnsub=new ba;this.emit(Ja.DISCONNECT_P2P)});this.signal.on(T.NEED_RENEW_SESSION,()=>{this.emit(Ja.NEED_RENEW_SESSION)});this.signal.on(T.REQUEST_SUCCESS,()=>{this._signalTimeout=!1});this.signal.on(T.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0})}}var Fr=za("iterator"),Fh=!ya(function(){var a=new URL("b?a=1&b=2&c=3","http://a"),b=a.searchParams,c="";return a.pathname="c%20d",b.forEach(function(a,f){b.delete("b");c+=f+a}),!a.toJSON||!b.sort||"http://a/c%20d?a=1&c=3"!==a.href||
"3"!==b.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!b[Fr]||"a"!==(new URL("https://a@b")).username||"b"!==(new URLSearchParams(new URLSearchParams("a=b"))).get("a")||"xn--e1aybc"!==(new URL("http://\u0442\u0435\u0441\u0442")).host||"#%D0%B1"!==(new URL("http://a#\u0431")).hash||"a1c3"!==c||"x"!==(new URL("http://x",void 0)).host}),Gr=/[^\0-\u007E]/,Hr=/[.\u3002\uFF0E\uFF61]/g,Dd=Math.floor,Gh=String.fromCharCode,Nm=function(a){return a+22+75*(26>a)},Ir=function(a){var b,c=[];var e=[];
for(var f=0,h=a.length;f<h;){var l=a.charCodeAt(f++);if(55296<=l&&56319>=l&&f<h){var k=a.charCodeAt(f++);56320==(64512&k)?e.push(((1023&l)<<10)+(1023&k)+65536):(e.push(l),f--)}else e.push(l)}f=(a=e).length;h=128;var p=0,m=72;for(e=0;e<a.length;e++)128>(b=a[e])&&c.push(Gh(b));for((k=l=c.length)&&c.push("-");k<f;){var n=2147483647;for(e=0;e<a.length;e++)(b=a[e])>=h&&b<n&&(n=b);var q=k+1;if(n-h>Dd((2147483647-p)/q))throw RangeError("Overflow: input needs wider integers to process");p+=(n-h)*q;h=n;for(e=
0;e<a.length;e++){if((b=a[e])<h&&2147483647<++p)throw RangeError("Overflow: input needs wider integers to process");if(b==h){var t=p;for(n=36;;n+=36){var B=n<=m?1:n>=m+26?26:n-m;if(t<B)break;t-=B;var u=36-B;c.push(Gh(Nm(B+t%u)));t=Dd(t/u)}c.push(Gh(Nm(t)));m=q;n=0;p=k==l?Dd(p/700):p>>1;for(p+=Dd(p/m);455<p;n+=36)p=Dd(p/35);m=Dd(n+36*p/(p+38));p=0;++k}}++p;++h}return c.join("")},Om=function(a){var b=ef(a);if("function"!=typeof b)throw TypeError(String(a)+" is not iterable");return $a(b.call(a))},Pm=
Xb("fetch"),Hh=Xb("Headers"),Jr=za("iterator"),Qm=Fa.set,Cb=Fa.getterFor("URLSearchParams"),Kr=Fa.getterFor("URLSearchParamsIterator"),Lr=/\+/g,Rm=Array(4),Mr=function(a){return Rm[a-1]||(Rm[a-1]=RegExp("((?:%[\\da-f]{2}){"+a+"})","gi"))},Nr=function(a){try{return decodeURIComponent(a)}catch(b){return a}},Sm=function(a){a=a.replace(Lr," ");var b=4;try{return decodeURIComponent(a)}catch(c){for(;b;)a=a.replace(Mr(b--),Nr);return a}},Tm=/[!'()~]|%20/g,Or={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E",
"%20":"+"},Um=function(a){return Or[a]},Vm=function(a,b){if(b){var c,e;b=b.split("&");for(var f=0;f<b.length;)(c=b[f++]).length&&(e=c.split("="),a.push({key:Sm(e.shift()),value:Sm(e.join("="))}))}},Pr=function(a){this.entries.length=0;Vm(this.entries,a)},Ed=function(a,b){if(a<b)throw TypeError("Not enough arguments");},Ih=Kk(function(a,b){Qm(this,{type:"URLSearchParamsIterator",iterator:Om(Cb(a).entries),kind:b})},"Iterator",function(){var a=Kr(this),b=a.kind;a=a.iterator.next();var c=a.value;return a.done||
(a.value="keys"===b?c.key:"values"===b?c.value:[c.key,c.value]),a}),pe=function(){sd(this,pe,"URLSearchParams");var a,b,c,e,f;var h=0<arguments.length?arguments[0]:void 0;var l=[];if(Qm(this,{type:"URLSearchParams",entries:l,updateURL:function(){},updateSearchParams:Pr}),void 0!==h)if(qa(h))if("function"==typeof(a=ef(h)))for(b=(a=a.call(h)).next;!(h=b.call(a)).done;){if((h=(e=(c=Om($a(h.value))).next).call(c)).done||(f=e.call(c)).done||!e.call(c).done)throw TypeError("Expected sequence with length 2");
l.push({key:h.value+"",value:f.value+""})}else for(b in h)P(h,b)&&l.push({key:b,value:h[b]+""});else Vm(l,"string"==typeof h?"?"===h.charAt(0)?h.slice(1):h:h+"")},Cf=pe.prototype;Pc(Cf,{append:function(a,b){Ed(arguments.length,2);var c=Cb(this);c.entries.push({key:a+"",value:b+""});c.updateURL()},delete:function(a){Ed(arguments.length,1);for(var b=Cb(this),c=b.entries,e=a+"",f=0;f<c.length;)c[f].key===e?c.splice(f,1):f++;b.updateURL()},get:function(a){Ed(arguments.length,1);for(var b=Cb(this).entries,
c=a+"",e=0;e<b.length;e++)if(b[e].key===c)return b[e].value;return null},getAll:function(a){Ed(arguments.length,1);for(var b=Cb(this).entries,c=a+"",e=[],f=0;f<b.length;f++)b[f].key===c&&e.push(b[f].value);return e},has:function(a){Ed(arguments.length,1);for(var b=Cb(this).entries,c=a+"",e=0;e<b.length;)if(b[e++].key===c)return!0;return!1},set:function(a,b){Ed(arguments.length,1);for(var c,e=Cb(this),f=e.entries,h=!1,l=a+"",k=b+"",p=0;p<f.length;p++)(c=f[p]).key===l&&(h?f.splice(p--,1):(h=!0,c.value=
k));h||f.push({key:l,value:k});e.updateURL()},sort:function(){var a,b,c=Cb(this),e=c.entries,f=e.slice();for(b=e.length=0;b<f.length;b++){var h=f[b];for(a=0;a<b;a++)if(e[a].key>h.key){e.splice(a,0,h);break}a===b&&e.push(h)}c.updateURL()},forEach:function(a){for(var b,c=Cb(this).entries,e=yc(a,1<arguments.length?arguments[1]:void 0,3),f=0;f<c.length;)e((b=c[f++]).value,b.key,this)},keys:function(){return new Ih(this,"keys")},values:function(){return new Ih(this,"values")},entries:function(){return new Ih(this,
"entries")}},{enumerable:!0});oc(Cf,Jr,Cf.entries);oc(Cf,"toString",function(){for(var a,b=Cb(this).entries,c=[],e=0;e<b.length;)a=b[e++],c.push(encodeURIComponent(a.key).replace(Tm,Um)+"="+encodeURIComponent(a.value).replace(Tm,Um));return c.join("&")},{enumerable:!0});Mc(pe,"URLSearchParams");L({global:!0,forced:!Fh},{URLSearchParams:pe});Fh||"function"!=typeof Pm||"function"!=typeof Hh||L({global:!0,enumerable:!0,forced:!0},{fetch:function(a){var b,c,e,f=[a];return 1<arguments.length&&(qa(b=arguments[1])&&
(c=b.body,"URLSearchParams"===qd(c)&&((e=b.headers?new Hh(b.headers):new Hh).has("content-type")||e.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),b=Ac(b,{body:lc(0,String(c)),headers:lc(0,e)}))),f.push(b)),Pm.apply(this,f)}});var qe=N.URL,Qr=pe,Rr=Fa.set,Ba=Fa.getterFor("URL"),Sr=Math.floor,Wm=Math.pow,Xm=/[A-Za-z]/,Tr=/[\d+\-.A-Za-z]/,Jh=/\d/,Ur=/^(0x|0X)/,Vr=/^[0-7]+$/,Wr=/^\d+$/,Ym=/^[\dA-Fa-f]+$/,Xr=/[\u0000\u0009\u000A\u000D #%/:?@[\\]]/,Yr=/[\u0000\u0009\u000A\u000D #/:?@[\\]]/,
Zr=/^[\u0000-\u001F ]+|[\u0000-\u001F ]+$/g,$r=/[\u0009\u000A\u000D]/g,Kh=function(a,b){var c,e;if("["==b.charAt(0)){if("]"!=b.charAt(b.length-1)||!(c=as(b.slice(1,-1))))return"Invalid host"}else if(Xa(a)){var f=[],h=b.toLowerCase().replace(Hr,".").split(".");for(e=0;e<h.length;e++){var l=h[e];f.push(Gr.test(l)?"xn--"+Ir(l):l)}if((b=f.join("."),Xr.test(b))||null===(c=bs(b)))return"Invalid host"}else{if(Yr.test(b))return"Invalid host";c="";b=Vc(b);for(e=0;e<b.length;e++)c+=Dc(b[e],Df)}a.host=c},bs=
function(a){var b,c,e,f,h=a.split(".");if(h.length&&""==h[h.length-1]&&h.pop(),4<(b=h.length))return a;var l=[];for(c=0;c<b;c++){if(""==(e=h[c]))return a;if(f=10,1<e.length&&"0"==e.charAt(0)&&(f=Ur.test(e)?16:8,e=e.slice(8==f?1:2)),""===e)e=0;else{if(!(10==f?Wr:8==f?Vr:Ym).test(e))return a;e=parseInt(e,f)}l.push(e)}for(c=0;c<b;c++)if(e=l[c],c==b-1){if(e>=Wm(256,5-b))return null}else if(255<e)return null;a=l.pop();for(c=0;c<l.length;c++)a+=l[c]*Wm(256,3-c);return a},as=function(a){var b,c,e,f=[0,0,
0,0,0,0,0,0],h=0,l=null,k=0;var p=function(){return a.charAt(k)};if(":"==p()){if(":"!=a.charAt(1))return;k+=2;l=++h}for(;p();){if(8==h)return;if(":"!=p()){for(b=c=0;4>c&&Ym.test(p());)b=16*b+parseInt(p(),16),k++,c++;if("."==p()){if(0==c||(k-=c,6<h))return;for(b=0;p();){if(c=null,0<b){if(!("."==p()&&4>b))return;k++}if(!Jh.test(p()))return;for(;Jh.test(p());){if(e=parseInt(p(),10),null===c)c=e;else{if(0==c)return;c=10*c+e}if(255<c)return;k++}f[h]=256*f[h]+c;2!=++b&&4!=b||h++}if(4!=b)return;break}if(":"==
p()){if(k++,!p())return}else if(p())return;f[h++]=b}else{if(null!==l)return;k++;l=++h}}if(null!==l)for(p=h-l,h=7;0!=h&&0<p;)b=f[h],f[h--]=f[l+p-1],f[l+--p]=b;else if(8!=h)return;return f},re=function(a){var b,c;if("number"==typeof a){var e=[];for(b=0;4>b;b++)e.unshift(a%256),a=Sr(a/256);return e.join(".")}if("object"==typeof a){e="";b=null;var f=1;for(var h=null,l=0,k=0;8>k;k++)0!==a[k]?(l>f&&(b=h,f=l),h=null,l=0):(null===h&&(h=k),++l);f=(l>f&&(b=h),b);for(b=0;8>b;b++)c&&0===a[b]||(c&&(c=!1),f===
b?(e+=b?":":"::",c=!0):(e+=a[b].toString(16),7>b&&(e+=":")));return"["+e+"]"}return a},Df={},Zm=ce({},Df,{" ":1,'"':1,"<":1,">":1,"`":1}),$m=ce({},Zm,{"#":1,"?":1,"{":1,"}":1}),Lh=ce({},$m,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Dc=function(a,b){var c=Dp(a,0);return 32<c&&127>c&&!P(b,a)?a:encodeURIComponent(a)},Ef={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Xa=function(a){return P(Ef,a.scheme)},Mh=function(a){return!a.host||a.cannotBeABaseURL||"file"==a.scheme},se=function(a,
b){var c;return 2==a.length&&Xm.test(a.charAt(0))&&(":"==(c=a.charAt(1))||!b&&"|"==c)},an=function(a){var b;return 1<a.length&&se(a.slice(0,2))&&(2==a.length||"/"===(b=a.charAt(2))||"\\"===b||"?"===b||"#"===b)},bn=function(a){var b=a.path,c=b.length;!c||"file"==a.scheme&&1==c&&se(b[0],!0)||b.pop()},Nh={},cn={},Oh={},dn={},en={},Ph={},fn={},gn={},Ff={},Gf={},Qh={},Rh={},Sh={},Th={},hn={},Uh={},te={},fc={},jn={},Xc={},uc={},gc=function(a,b,c,e){var f,h;var l=c||Nh;var k=0;var p="";var m=!1,n=!1,q=!1;
c||(a.scheme="",a.username="",a.password="",a.host=null,a.port=null,a.path=[],a.query=null,a.fragment=null,a.cannotBeABaseURL=!1,b=b.replace(Zr,""));b=b.replace($r,"");for(b=Vc(b);k<=b.length;){switch(f=b[k],l){case Nh:if(!f||!Xm.test(f)){if(c)return"Invalid scheme";l=Oh;continue}p+=f.toLowerCase();l=cn;break;case cn:if(f&&(Tr.test(f)||"+"==f||"-"==f||"."==f))p+=f.toLowerCase();else{if(":"!=f){if(c)return"Invalid scheme";p="";l=Oh;k=0;continue}if(c&&(Xa(a)!=P(Ef,p)||"file"==p&&(""!=a.username||""!=
a.password||null!==a.port)||"file"==a.scheme&&!a.host))return;if(a.scheme=p,c)return void(Xa(a)&&Ef[a.scheme]==a.port&&(a.port=null));p="";"file"==a.scheme?l=Th:Xa(a)&&e&&e.scheme==a.scheme?l=dn:Xa(a)?l=gn:"/"==b[k+1]?(l=en,k++):(a.cannotBeABaseURL=!0,a.path.push(""),l=jn)}break;case Oh:if(!e||e.cannotBeABaseURL&&"#"!=f)return"Invalid scheme";if(e.cannotBeABaseURL&&"#"==f){a.scheme=e.scheme;a.path=e.path.slice();a.query=e.query;a.fragment="";a.cannotBeABaseURL=!0;l=uc;break}l="file"==e.scheme?Th:
Ph;continue;case dn:if("/"!=f||"/"!=b[k+1]){l=Ph;continue}l=Ff;k++;break;case en:if("/"==f){l=Gf;break}l=fc;continue;case Ph:if(a.scheme=e.scheme,void 0==f)a.username=e.username,a.password=e.password,a.host=e.host,a.port=e.port,a.path=e.path.slice(),a.query=e.query;else if("/"==f||"\\"==f&&Xa(a))l=fn;else if("?"==f)a.username=e.username,a.password=e.password,a.host=e.host,a.port=e.port,a.path=e.path.slice(),a.query="",l=Xc;else{if("#"!=f){a.username=e.username;a.password=e.password;a.host=e.host;
a.port=e.port;a.path=e.path.slice();a.path.pop();l=fc;continue}a.username=e.username;a.password=e.password;a.host=e.host;a.port=e.port;a.path=e.path.slice();a.query=e.query;a.fragment="";l=uc}break;case fn:if(!Xa(a)||"/"!=f&&"\\"!=f){if("/"!=f){a.username=e.username;a.password=e.password;a.host=e.host;a.port=e.port;l=fc;continue}l=Gf}else l=Ff;break;case gn:if(l=Ff,"/"!=f||"/"!=p.charAt(k+1))continue;k++;break;case Ff:if("/"!=f&&"\\"!=f){l=Gf;continue}break;case Gf:if("@"==f){m&&(p="%40"+p);m=!0;
p=Vc(p);for(f=0;f<p.length;f++){var t=p[f];":"!=t||q?(t=Dc(t,Lh),q?a.password+=t:a.username+=t):q=!0}p=""}else if(void 0==f||"/"==f||"?"==f||"#"==f||"\\"==f&&Xa(a)){if(m&&""==p)return"Invalid authority";k-=Vc(p).length+1;p="";l=Qh}else p+=f;break;case Qh:case Rh:if(c&&"file"==a.scheme){l=Uh;continue}if(":"!=f||n){if(void 0==f||"/"==f||"?"==f||"#"==f||"\\"==f&&Xa(a)){if(Xa(a)&&""==p)return"Invalid host";if(c&&""==p&&(""!=a.username||""!=a.password||null!==a.port))return;if(l=Kh(a,p))return l;if(p=
"",l=te,c)return;continue}"["==f?n=!0:"]"==f&&(n=!1);p+=f}else{if(""==p)return"Invalid host";if(l=Kh(a,p))return l;if(p="",l=Sh,c==Rh)return}break;case Sh:if(!Jh.test(f)){if(void 0==f||"/"==f||"?"==f||"#"==f||"\\"==f&&Xa(a)||c){if(""!=p){l=parseInt(p,10);if(65535<l)return"Invalid port";a.port=Xa(a)&&l===Ef[a.scheme]?null:l;p=""}if(c)return;l=te;continue}return"Invalid port"}p+=f;break;case Th:if(a.scheme="file","/"==f||"\\"==f)l=hn;else{if(!e||"file"!=e.scheme){l=fc;continue}if(void 0==f)a.host=e.host,
a.path=e.path.slice(),a.query=e.query;else if("?"==f)a.host=e.host,a.path=e.path.slice(),a.query="",l=Xc;else{if("#"!=f){an(b.slice(k).join(""))||(a.host=e.host,a.path=e.path.slice(),bn(a));l=fc;continue}a.host=e.host;a.path=e.path.slice();a.query=e.query;a.fragment="";l=uc}}break;case hn:if("/"==f||"\\"==f){l=Uh;break}e&&"file"==e.scheme&&!an(b.slice(k).join(""))&&(se(e.path[0],!0)?a.path.push(e.path[0]):a.host=e.host);l=fc;continue;case Uh:if(void 0==f||"/"==f||"\\"==f||"?"==f||"#"==f){if(!c&&se(p))l=
fc;else{if(""==p){if(a.host="",c)return}else{if(l=Kh(a,p))return l;if("localhost"==a.host&&(a.host=""),c)return;p=""}l=te}continue}p+=f;break;case te:if(Xa(a)){if(l=fc,"/"!=f&&"\\"!=f)continue}else if(c||"?"!=f)if(c||"#"!=f){if(void 0!=f&&(l=fc,"/"!=f))continue}else a.fragment="",l=uc;else a.query="",l=Xc;break;case fc:if(void 0==f||"/"==f||"\\"==f&&Xa(a)||!c&&("?"==f||"#"==f)){if(".."===(h=(h=p).toLowerCase())||"%2e."===h||".%2e"===h||"%2e%2e"===h?(bn(a),"/"==f||"\\"==f&&Xa(a)||a.path.push("")):
"."===p||"%2e"===p.toLowerCase()?"/"==f||"\\"==f&&Xa(a)||a.path.push(""):("file"==a.scheme&&!a.path.length&&se(p)&&(a.host&&(a.host=""),p=p.charAt(0)+":"),a.path.push(p)),p="","file"==a.scheme&&(void 0==f||"?"==f||"#"==f))for(;1<a.path.length&&""===a.path[0];)a.path.shift();"?"==f?(a.query="",l=Xc):"#"==f&&(a.fragment="",l=uc)}else p+=Dc(f,$m);break;case jn:"?"==f?(a.query="",l=Xc):"#"==f?(a.fragment="",l=uc):void 0!=f&&(a.path[0]+=Dc(f,Df));break;case Xc:c||"#"!=f?void 0!=f&&("'"==f&&Xa(a)?a.query+=
"%27":a.query+="#"==f?"%23":Dc(f,Df)):(a.fragment="",l=uc);break;case uc:void 0!=f&&(a.fragment+=Dc(f,Zm))}k++}},Yc=function(a){var b=sd(this,Yc,"URL");var c=1<arguments.length?arguments[1]:void 0;var e=String(a),f=Rr(b,{type:"URL"});if(void 0!==c)if(c instanceof Yc)var h=Ba(c);else if(c=gc(h={},String(c)))throw TypeError(c);if(c=gc(f,e,null,h))throw TypeError(c);var l=f.searchParams=new Qr;h=Cb(l);h.updateSearchParams(f.query);h.updateURL=function(){f.query=String(l)||null};na||(b.href=Hf.call(b),
b.origin=kn.call(b),b.protocol=ln.call(b),b.username=mn.call(b),b.password=nn.call(b),b.host=on.call(b),b.hostname=pn.call(b),b.port=qn.call(b),b.pathname=rn.call(b),b.search=sn.call(b),b.searchParams=tn.call(b),b.hash=un.call(b))},Vh=Yc.prototype,Hf=function(){var a=Ba(this),b=a.scheme,c=a.username,e=a.password,f=a.host,h=a.port,l=a.path,k=a.query,p=a.fragment,m=b+":";return null!==f?(m+="//",(""!=a.username||""!=a.password)&&(m+=c+(e?":"+e:"")+"@"),m+=re(f),null!==h&&(m+=":"+h)):"file"==b&&(m+=
"//"),m+=a.cannotBeABaseURL?l[0]:l.length?"/"+l.join("/"):"",null!==k&&(m+="?"+k),null!==p&&(m+="#"+p),m},kn=function(){var a=Ba(this),b=a.scheme,c=a.port;if("blob"==b)try{return(new URL(b.path[0])).origin}catch(e){return"null"}return"file"!=b&&Xa(a)?b+"://"+re(a.host)+(null!==c?":"+c:""):"null"},ln=function(){return Ba(this).scheme+":"},mn=function(){return Ba(this).username},nn=function(){return Ba(this).password},on=function(){var a=Ba(this),b=a.host;a=a.port;return null===b?"":null===a?re(b):
re(b)+":"+a},pn=function(){var a=Ba(this).host;return null===a?"":re(a)},qn=function(){var a=Ba(this).port;return null===a?"":String(a)},rn=function(){var a=Ba(this),b=a.path;return a.cannotBeABaseURL?b[0]:b.length?"/"+b.join("/"):""},sn=function(){var a=Ba(this).query;return a?"?"+a:""},tn=function(){return Ba(this).searchParams},un=function(){var a=Ba(this).fragment;return a?"#"+a:""},Ob=function(a,b){return{get:a,set:b,configurable:!0,enumerable:!0}};if(na&&Eg(Vh,{href:Ob(Hf,function(a){var b=
Ba(this);if(a=gc(b,String(a)))throw TypeError(a);Cb(b.searchParams).updateSearchParams(b.query)}),origin:Ob(kn),protocol:Ob(ln,function(a){var b=Ba(this);gc(b,String(a)+":",Nh)}),username:Ob(mn,function(a){var b=Ba(this);a=Vc(String(a));if(!Mh(b)){b.username="";for(var c=0;c<a.length;c++)b.username+=Dc(a[c],Lh)}}),password:Ob(nn,function(a){var b=Ba(this);a=Vc(String(a));if(!Mh(b)){b.password="";for(var c=0;c<a.length;c++)b.password+=Dc(a[c],Lh)}}),host:Ob(on,function(a){var b=Ba(this);b.cannotBeABaseURL||
gc(b,String(a),Qh)}),hostname:Ob(pn,function(a){var b=Ba(this);b.cannotBeABaseURL||gc(b,String(a),Rh)}),port:Ob(qn,function(a){var b=Ba(this);Mh(b)||(""==(a=String(a))?b.port=null:gc(b,a,Sh))}),pathname:Ob(rn,function(a){var b=Ba(this);b.cannotBeABaseURL||(b.path=[],gc(b,a+"",te))}),search:Ob(sn,function(a){var b=Ba(this);""==(a=String(a))?b.query=null:("?"==a.charAt(0)&&(a=a.slice(1)),b.query="",gc(b,a,Xc));Cb(b.searchParams).updateSearchParams(b.query)}),searchParams:Ob(tn),hash:Ob(un,function(a){var b=
Ba(this);""!=(a=String(a))?("#"==a.charAt(0)&&(a=a.slice(1)),b.fragment="",gc(b,a,uc)):b.fragment=null})}),oc(Vh,"toJSON",function(){return Hf.call(this)},{enumerable:!0}),oc(Vh,"toString",function(){return Hf.call(this)},{enumerable:!0}),qe){var vn=qe.createObjectURL,wn=qe.revokeObjectURL;vn&&oc(Yc,"createObjectURL",function(a){return vn.apply(qe,arguments)});wn&&oc(Yc,"revokeObjectURL",function(a){return wn.apply(qe,arguments)})}Mc(Yc,"URL");L({global:!0,forced:!Fh,sham:!na},{URL:Yc});var vo=ma.URL;
!function(){function a(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function b(a,b){if(b)a:{var c=u;a=a.split(".");for(var e=0;e<a.length-1;e++){var f=a[e];if(!(f in c))break a;c=c[f]}(b=b(e=c[a=a[a.length-1]]))!=e&&null!=b&&B(c,a,{configurable:!0,writable:!0,value:b})}}function c(a){return(a={next:a})[Symbol.iterator]=function(){return this},a}function e(b){var c="undefined"!=typeof Symbol&&Symbol.iterator&&b[Symbol.iterator];return c?c.call(b):{next:a(b)}}function f(){this.m=
!1;this.j=null;this.v=void 0;this.h=1;this.u=this.C=0;this.l=null}function h(a){if(a.m)throw new TypeError("Generator is already running");a.m=!0}function l(a,b){return a.h=3,{value:b}}function k(a){this.g=new f;this.G=a}function p(a,b,c,e){try{var f=b.call(a.g.j,c);if(!(f instanceof Object))throw new TypeError("Iterator result "+f+" is not an object");if(!f.done)return a.g.m=!1,f;var h=f.value}catch(jg){return a.g.j=null,a.g.s(jg),m(a)}return a.g.j=null,e.call(a.g,h),m(a)}function m(a){for(;a.g.h;)try{var b=
a.G(a.g);if(b)return a.g.m=!1,{value:b.value,done:!1}}catch(Rd){a.g.v=void 0,a.g.s(Rd)}if(a.g.m=!1,a.g.l){if(b=a.g.l,a.g.l=null,b.F)throw b.D;return{value:b.return,done:!0}}return{value:void 0,done:!0}}function n(a){this.next=function(b){return a.o(b)};this.throw=function(b){return a.s(b)};this.return=function(b){return function(a,b){h(a.g);var c=a.g.j;return c?p(a,"return"in c?c.return:function(a){return{value:a,done:!0}},b,a.g.return):(a.g.return(b),m(a))}(a,b)};this[Symbol.iterator]=function(){return this}}
function q(a,b){return b=new n(new k(b)),y&&a.prototype&&y(b,a.prototype),b}var t,B="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){return a==Array.prototype||a==Object.prototype||(a[b]=c.value),a},u=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof Xd&&Xd];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");}(this);if(b("Symbol",
function(a){function b(a,b){this.A=a;B(this,"description",{configurable:!0,writable:!0,value:b})}if(a)return a;b.prototype.toString=function(){return this.A};var c="jscomp_symbol_"+(1E9*Math.random()>>>0)+"_",e=0;return function jg(a){if(this instanceof jg)throw new TypeError("Symbol is not a constructor");return new b(c+(a||"")+"_"+e++,a)}}),b("Symbol.iterator",function(b){if(b)return b;b=Symbol("Symbol.iterator");for(var e="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),
f=0;f<e.length;f++){var h=u[e[f]];"function"==typeof h&&"function"!=typeof h.prototype[b]&&B(h.prototype,b,{configurable:!0,writable:!0,value:function(){return c(a(this))}})}return b}),"function"==typeof Object.setPrototypeOf)var v=Object.setPrototypeOf;else{a:{var x={};try{x.__proto__={a:!0};v=x.a;break a}catch(Pa){}v=!1}v=v?function(a,b){if(a.__proto__=b,a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null}var y=v;if(f.prototype.o=function(a){this.v=a},f.prototype.s=function(a){this.l=
{D:a,F:!0};this.h=this.C||this.u},f.prototype.return=function(a){this.l={return:a};this.h=this.u},k.prototype.o=function(a){return h(this.g),this.g.j?p(this,this.g.j.next,a,this.g.o):(this.g.o(a),m(this))},k.prototype.s=function(a){return h(this.g),this.g.j?p(this,this.g.j.throw,a,this.g.o):(this.g.s(a),m(this))},b("Array.prototype.entries",function(a){return a||function(){return function(a,b){a instanceof String&&(a+="");var c=0,e=!1,f={next:function(){if(!e&&c<a.length){var f=c++;return{value:b(f,
a[f]),done:!1}}return e=!0,{done:!0,value:void 0}}};return f[Symbol.iterator]=function(){return f},f}(this,function(a,b){return[a,b]})}}),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var z=function(a,b){for(var c=0;c<a.length;c++)b(a[c])},A=function(a){return a.replace(/\r?\n|\r/g,"\r\n")},C=function(a,b,c){return b instanceof Blob?(c=void 0!==c?String(c+""):"string"==typeof b.name?b.name:"blob",b.name===c&&"[object Blob]"!==Object.prototype.toString.call(b)||
(b=new File([b],c)),[String(a),b]):[String(a),String(b)]},D=function(a,b){if(a.length<b)throw new TypeError(b+" argument required, but only "+a.length+" present.");};v="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this;var F=v.FormData,E=v.XMLHttpRequest&&v.XMLHttpRequest.prototype.send,G=v.Request&&v.fetch,I=v.navigator&&v.navigator.sendBeacon;x=v.Element&&v.Element.prototype;var H=v.Symbol&&Symbol.toStringTag;H&&(Blob.prototype[H]||(Blob.prototype[H]=
"Blob"),"File"in v&&!File.prototype[H]&&(File.prototype[H]="File"));try{new File([],"")}catch(Pa){v.File=function(a,b,c){return a=new Blob(a,c||{}),Object.defineProperties(a,{name:{value:b},lastModified:{value:+(c&&void 0!==c.lastModified?new Date(c.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),H&&Object.defineProperty(a,H,{value:"File"}),a}}var L=function(a){return a.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},J=function(a){this.i=[];var b=this;
a&&z(a.elements,function(a){if(a.name&&!a.disabled&&"submit"!==a.type&&"button"!==a.type&&!a.matches("form fieldset[disabled] *"))if("file"===a.type){var c=a.files&&a.files.length?a.files:[new File([],"",{type:"application/octet-stream"})];z(c,function(c){b.append(a.name,c)})}else"select-multiple"===a.type||"select-one"===a.type?z(a.options,function(c){!c.disabled&&c.selected&&b.append(a.name,c.value)}):"checkbox"===a.type||"radio"===a.type?a.checked&&b.append(a.name,a.value):(c="textarea"===a.type?
A(a.value):a.value,b.append(a.name,c))})};if((t=J.prototype).append=function(a,b,c){D(arguments,2);this.i.push(C(a,b,c))},t.delete=function(a){D(arguments,1);var b=[];a=String(a);z(this.i,function(c){c[0]!==a&&b.push(c)});this.i=b},t.entries=function kc(){var a,b=this;return q(kc,function(c){if(1==c.h&&(a=0),3!=c.h)return a<b.i.length?c=l(c,b.i[a]):(c.h=0,c=void 0),c;a++;c.h=2})},t.forEach=function(a,b){D(arguments,1);for(var c=e(this),f=c.next();!f.done;f=c.next()){var h=e(f.value);f=h.next().value;
h=h.next().value;a.call(b,h,f,this)}},t.get=function(a){D(arguments,1);var b=this.i;a=String(a);for(var c=0;c<b.length;c++)if(b[c][0]===a)return b[c][1];return null},t.getAll=function(a){D(arguments,1);var b=[];return a=String(a),z(this.i,function(c){c[0]===a&&b.push(c[1])}),b},t.has=function(a){D(arguments,1);a=String(a);for(var b=0;b<this.i.length;b++)if(this.i[b][0]===a)return!0;return!1},t.keys=function Rd(){var a,b,c,f,h=this;return q(Rd,function(k){if(1==k.h&&(a=e(h),b=a.next()),3!=k.h)return b.done?
void(k.h=0):(c=b.value,f=e(c),l(k,f.next().value));b=a.next();k.h=2})},t.set=function(a,b,c){D(arguments,2);a=String(a);var e=[],f=C(a,b,c),h=!0;z(this.i,function(b){b[0]===a?h&&(h=!e.push(f)):e.push(b)});h&&e.push(f);this.i=e},t.values=function Ic(){var a,b,c,f,h=this;return q(Ic,function(k){if(1==k.h&&(a=e(h),b=a.next()),3!=k.h)return b.done?void(k.h=0):(c=b.value,(f=e(c)).next(),l(k,f.next().value));b=a.next();k.h=2})},J.prototype._asNative=function(){for(var a=new F,b=e(this),c=b.next();!c.done;c=
b.next()){var f=e(c.value);c=f.next().value;f=f.next().value;a.append(c,f)}return a},J.prototype._blob=function(){var a="----formdata-polyfill-"+Math.random(),b=[],c="--"+a+'\r\nContent-Disposition: form-data; name="';return this.forEach(function(a,e){return"string"==typeof a?b.push(c+L(A(e))+'"\r\n\r\n'+A(a)+"\r\n"):b.push(c+L(A(e))+'"; filename="'+L(a.name)+'"\r\nContent-Type: '+(a.type||"application/octet-stream")+"\r\n\r\n",a,"\r\n")}),b.push("--"+a+"--"),new Blob(b,{type:"multipart/form-data; boundary="+
a})},J.prototype[Symbol.iterator]=function(){return this.entries()},J.prototype.toString=function(){return"[object FormData]"},x&&!x.matches&&(x.matches=x.matchesSelector||x.mozMatchesSelector||x.msMatchesSelector||x.oMatchesSelector||x.webkitMatchesSelector||function(a){for(var b=(a=(this.document||this.ownerDocument).querySelectorAll(a)).length;0<=--b&&a.item(b)!==this;);return-1<b}),H&&(J.prototype[H]="FormData"),E){var M=v.XMLHttpRequest.prototype.setRequestHeader;v.XMLHttpRequest.prototype.setRequestHeader=
function(a,b){M.call(this,a,b);"content-type"===a.toLowerCase()&&(this.B=!0)};v.XMLHttpRequest.prototype.send=function(a){a instanceof J?(a=a._blob(),this.B||this.setRequestHeader("Content-Type",a.type),E.call(this,a)):E.call(this,a)}}G&&(v.fetch=function(a,b){return b&&b.body&&b.body instanceof J&&(b.body=b.body._blob()),G.call(this,a,b)});I&&(v.navigator.sendBeacon=function(a,b){return b instanceof J&&(b=b._asNative()),I.call(this,a,b)});v.FormData=J}}();let mg=1,og=1,Dj=(a,b,c,e,f)=>{var h,l,r;
const p=[];if(t(h=a.response_body).call(h,h=>{var l=h.buffer.code;0!==l&&(l=Se(l),h={error:new q(n.CAN_NOT_GET_GATEWAY_SERVER,l.desc,{retry:l.retry,csIp:a.detail[502]}),flag:h.buffer.flag},p.push(h),4096===h.flag?u.joinChooseServer(c.sid,{lts:e,succ:!1,csAddr:b,opid:a.opid,serverList:null,ec:h.error.message,csIp:h.error.data&&h.error.data.csIp,unilbsServerIds:f.toString()}):1048576!==h.flag&&4194304!==h.flag||u.joinWebProxyAP(c.sid,{lts:e,sucess:0,apServerAddr:b,turnServerAddrList:null,errorCode:h.error.code,
eventType:c.cloudProxyServer,unilbsServerIds:f.toString()}))}),p.length)throw k.warning(m(l=m(r="[".concat(c.clientId,"] multi unilbs ")).call(r,b," failed, ")).call(l,z(p).call(p,a=>{var b,c;return m(b=m(c="flag: ".concat(a.flag,", message: ")).call(c,a.error.message,", retry: ")).call(b,a.error.data.retry)}).join(" | "))),new q(n.CAN_NOT_GET_GATEWAY_SERVER,z(p).call(p,a=>{var b;return m(b="flag: ".concat(a.flag,", message: ")).call(b,a.error.message)}).join(" | "),{retry:!!U(p).call(p,a=>a.error.data.retry),
csIp:a.detail[502]});},Ej=a=>{if(a.addresses&&0===a.addresses.length&&0===a.code)throw new q(n.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:a.detail&&a.detail[502]});if(v.GATEWAY_ADDRESS&&0<v.GATEWAY_ADDRESS.length){var b;k.debug("assign gateway address to",v.GATEWAY_ADDRESS);const c=z(b=v.GATEWAY_ADDRESS).call(b,b=>({ip:b.ip,port:b.port,ticket:a.addresses[0]&&a.addresses[0].ticket}));a.addresses=c}},Cj=(a,b,c)=>{var e;const f=Math.floor(1E12*Math.random());b={appid:a.appId,client_ts:x(),
opid:f,sid:a.sid,request_bodies:[{uri:22,buffer:{cname:a.cname,detail:{6:a.stringUid,11:b},key:a.token,service_ids:c,uid:a.uid||0}}]};t(e=b.request_bodies).call(e,b=>{a.multiIP&&a.multiIP.gateway_ip&&(b.buffer.detail[5]=A({vocs_ip:[a.multiIP.uni_lbs_ip],vos_ip:[a.multiIP.gateway_ip]}))});e=new FormData;return e.append("request",A(b)),[e,f]},Vd=()=>{const a=v.AREAS;0===a.length&&a.push("GLOBAL");return Be(a).call(a,(a,c,e)=>{var b,h,l,k,p;c="OVERSEA"===c?m(b=m(h=m(l=m(k=m(p="".concat(Ka.ASIA,",")).call(p,
Ka.EUROPE,",")).call(k,Ka.AFRICA,",")).call(l,Ka.NORTH_AMERICA,",")).call(h,Ka.SOUTH_AMERICA,",")).call(b,Ka.OCEANIA):Ka[c];var n;return c?0===e?c:m(n="".concat(a,",")).call(n,c):a},"")};var If={ASIA:["CHINA","JAPAN","INDIA"],EUROPE:[],NORTH_AMERICA:[],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]};let Fd=W(If),Jf="CHINA NORTH_AMERICA EUROPE ASIA JAPAN INDIA OCEANIA SOUTH_AMERICA AFRICA".split(" "),cs=function(a,b){var c=[];if(Z(a).call(a,"GLOBAL")){c=["GLOBAL","OVERSEA"];const f=W(nh);if("GLOBAL"===b)throw new q(n.INVALID_PARAMS,
"GLOBAL is an invalid excludedArea value");if("CHINA"===b)c=["OVERSEA"];else if(e=b,Z(Fd).call(Fd,e)){a=If[b]||[];const e=[...c,b,...a];c=I(f).call(f,a=>!Z(e).call(e,a))}else if(function(a){let b=!1;return t(Fd).call(Fd,c=>{var e;Z(e=If[c]).call(e,a)&&(b=!0)}),b}(b)){a=function(a){let b;return t(Fd).call(Fd,c=>{var e;Z(e=If[c]).call(e,a)&&(b=c)}),b}(b);const e=[...c,a,b];c=I(f).call(f,a=>!Z(e).call(e,a))}else c=a;c=function(a){const b=[];return t(Jf).call(Jf,c=>{Z(a).call(a,c)&&b.push(c)}),m(b).call(b,
I(a).call(a,a=>!Z(Jf).call(Jf,a)))}(c)}else c=a;var e;return c};class ds extends Wa{constructor(){super();this.retryConfig={timeout:3E3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1E4};this.mutex=new sc("config-distribute")}startGetConfigDistribute(a,b){this.joinInfo=a;this.cancelToken=b;this.interval&&this.stopGetConfigDistribute();this.updateConfigDistribute();this.interval=window.setInterval(()=>{this.updateConfigDistribute()},v.CONFIG_DISTRIBUTE_INTERVAL)}stopGetConfigDistribute(){this.interval&&
clearInterval(this.interval);this.cancelToken=this.joinInfo=this.interval=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void k.debug("[config-distribute] get config distribute interrupted have no joininfo");let a,b=await this.mutex.lock();try{a=await wo(this.joinInfo,this.cancelToken,this.retryConfig),k.debug("[config-distribute] get config distribute",A(a)),
a.limit_bitrate&&this.handleBitrateLimit(a.limit_bitrate),this.configs=a}catch(c){let a=new q(n.NETWORK_RESPONSE_ERROR,c);k.warning("[config-distribute] ".concat(a.toString()))}finally{b()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(a){a&&a.uplink&&a.id&&void 0!==a.uplink.max_bitrate&&void 0!==a.uplink.min_bitrate&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==a.id&&this.emit(ke.UPDATE_BITRATE_LIMIT,
a):this.emit(ke.UPDATE_BITRATE_LIMIT,a))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&function(a){for(var b=1;b<arguments.length;b++){var c,e=null!=arguments[b]?arguments[b]:{};if(b%2)t(c=Ij(Object(e),!0)).call(c,function(b){gb(a,b,e[b])});else if(ka)hb(a,ka(e));else{var f;t(f=Ij(Object(e))).call(f,function(b){Q(a,b,ca(e,b))})}}return a}({},this.configs.limit_bitrate.low_stream_uplink)}}var Wh=function(){function a(a){this.input=[];this.size=a}return a.prototype.add=
function(a){this.input.push(a);this.input.length>this.size&&this.input.splice(0,1)},a.prototype.diffMean=function(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length},a}(),Kj=function(a,b){return(Kj=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c])})(a,b)},Xh=function(){return(Xh=Object.assign||function(a){for(var b,c=1,e=arguments.length;c<e;c++)for(var f in b=
arguments[c])Object.prototype.hasOwnProperty.call(b,f)&&(a[f]=b[f]);return a}).apply(this,arguments)},Ec,ue={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[]},xn={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0},yn={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,
packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0},zn={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0},An={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0},Yh=function(){function a(a,c){var b=this;this.videoIsReady=!1;this.stats=Hb(ue);this.isFirstAudioDecoded=this.isFirstAudioReceived=this.isFirstVideoDecoded=this.isFirstVideoReceived=!1;this.lossRateWindowStats=[];this.pc=a;this.options=c;this.intervalTimer=window.setInterval(function(){return qg(b,
void 0,void 0,function(){return rg(this,function(a){return this.updateStats(),[2]})})},this.options.updateInterval)}return a.prototype.getStats=function(){return this.stats},a.prototype.setVideoIsReady=function(a){this.videoIsReady=a},a.prototype.setIsFirstAudioDecoded=function(a){this.isFirstAudioDecoded=a},a.prototype.destroy=function(){window.clearInterval(this.intervalTimer);this.pc=void 0},a.prototype.calcLossRate=function(a){var b=this;this.lossRateWindowStats.push(a);this.lossRateWindowStats.length>
this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);for(var e=this.lossRateWindowStats.length,f=0,h=0,l=0,k=0,p=function(c){a[c].forEach(function(a,p){if(b.lossRateWindowStats[e-1][c][p]&&b.lossRateWindowStats[0][c][p]){var r=b.lossRateWindowStats[e-1][c][p].packets-b.lossRateWindowStats[0][c][p].packets;p=b.lossRateWindowStats[e-1][c][p].packetsLost-b.lossRateWindowStats[0][c][p].packetsLost;"videoSend"===c||"audioSend"===c?(f+=r,l+=p):(h+=r,k+=p);Number.isNaN(r)||Number.isNaN(r)?
a.packetLostRate=0:a.packetLostRate=0>=r||0>=p?0:p/(r+p)}})},m=0,n=["videoSend","audioSend","videoRecv","audioRecv"];m<n.length;m++)p(n[m]);a.sendPacketLossRate=0>=f||0>=l?0:l/(f+l);a.recvPacketLossRate=0>=h||0>=k?0:k/(h+k)},a}(),es=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;return b._stats=ue,b.lastDecodeVideoReceiverStats=new Map,b}return pg(b,a),b.prototype.updateStats=function(){return qg(this,void 0,void 0,function(){var a,b,f,h;return rg(this,function(c){switch(c.label){case 0:return[4,
this._getStats()];case 1:return a=c.sent(),b=this.statsResponsesToObjects(a),this._stats=Hb(ue),f=b.filter(function(a){return"ssrc"===a.type}),this.processSSRCStats(f),(h=b.find(function(a){return"VideoBwe"===a.type}))&&this.processBandwidthStats(h),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats,[2]}})})},b.prototype.processBandwidthStats=function(a){this._stats.bitrate={actualEncoded:Number(a.googActualEncBitrate),targetEncoded:Number(a.googTargetEncBitrate),
retransmit:Number(a.googRetransmitBitrate),transmit:Number(a.googTransmitBitrate)};this._stats.sendBandwidth=Number(a.googAvailableSendBandwidth)},b.prototype.processSSRCStats=function(a){var b=this;a.forEach(function(a){var c=a.id.includes("send");switch(a.mediaType+"_"+(c?"send":"recv")){case "video_send":c=Hb(yn);c.codec=a.googCodecName;c.adaptionChangeReason="none";a.googCpuLimitedResolution&&(c.adaptionChangeReason="cpu");a.googBandwidthLimitedResolution&&(c.adaptionChangeReason="bandwidth");
c.avgEncodeMs=Number(a.googAvgEncodeMs);c.inputFrame={width:Number(a.googFrameWidthInput)||Number(a.googFrameWidthSent),height:Number(a.googFrameHeightInput)||Number(a.googFrameHeightSent),frameRate:Number(a.googFrameRateInput)};c.sentFrame={width:Number(a.googFrameWidthSent),height:Number(a.googFrameHeightSent),frameRate:Number(a.googFrameRateInput)};c.firsCount=Number(a.googFirReceived);c.nacksCount=Number(a.googNacksReceived);c.plisCount=Number(a.googPlisReceived);c.frameCount=Number(a.framesEncoded);
c.bytes=Number(a.bytesSent);c.packets=Number(a.packetsSent);c.packetsLost=Number(a.packetsLost);c.ssrc=Number(a.ssrc);c.rttMs=Number(a.googRtt||0);b._stats.videoSend.push(c);b._stats.rtt=c.rttMs;break;case "video_recv":c=Hb(xn);var e=b.lastDecodeVideoReceiverStats.get(Number(a.ssrc));if(c.codec=a.googCodecName,c.targetDelayMs=Number(a.googTargetDelayMs),c.renderDelayMs=Number(a.googRenderDelayMs),c.currentDelayMs=Number(a.googCurrentDelayMs),c.minPlayoutDelayMs=Number(a.googMinPlayoutDelayMs),c.decodeMs=
Number(a.googDecodeMs),c.maxDecodeMs=Number(a.googMaxDecodeMs),c.receivedFrame={width:Number(a.googFrameWidthReceived),height:Number(a.googFrameHeightReceived),frameRate:Number(a.googFrameRateReceived)},c.decodedFrame={width:Number(a.googFrameWidthReceived),height:Number(a.googFrameHeightReceived),frameRate:Number(a.googFrameRateDecoded)},c.outputFrame={width:Number(a.googFrameWidthReceived),height:Number(a.googFrameHeightReceived),frameRate:Number(a.googFrameRateOutput)},c.jitterBufferMs=Number(a.googJitterBufferMs),
c.firsCount=Number(a.googFirsSent),c.nacksCount=Number(a.googNacksSent),c.plisCount=Number(a.googPlisSent),c.framesDecodeCount=Number(a.framesDecoded),c.bytes=Number(a.bytesReceived),c.packets=Number(a.packetsReceived),c.packetsLost=Number(a.packetsLost),c.ssrc=Number(a.ssrc),0<c.packets&&!b.isFirstVideoReceived&&(b.onFirstVideoReceived&&b.onFirstVideoReceived(),b.isFirstVideoReceived=!0),0<c.framesDecodeCount&&!b.isFirstVideoDecoded&&(b.onFirstVideoDecoded&&b.onFirstVideoDecoded(c.decodedFrame.width,
c.decodedFrame.height),b.isFirstVideoDecoded=!0),e){a=e.stats;var f=Date.now()-e.lts;c.framesDecodeFreezeTime=a.framesDecodeFreezeTime;c.framesDecodeInterval=a.framesDecodeInterval;c.framesDecodeCount>a.framesDecodeCount&&b.isFirstVideoDecoded?(e.lts=Date.now(),c.framesDecodeInterval=f,c.framesDecodeInterval>=b.options.freezeRateLimit&&(b.videoIsReady?c.framesDecodeFreezeTime+=c.framesDecodeInterval:b.setVideoIsReady(!0))):c.framesDecodeCount<e.stats.framesDecodeCount&&(c.framesDecodeInterval=0)}b.lastDecodeVideoReceiverStats.set(c.ssrc,
{stats:Xh({},c),lts:Date.now()});b._stats.videoRecv.push(c);break;case "audio_recv":c=Hb(An);c.codec=a.googCodecName;c.outputLevel=Math.abs(Number(a.audioOutputLevel))/32767;c.decodingCNG=Number(a.googDecodingCNG);c.decodingCTN=Number(a.googDecodingCTN);c.decodingCTSG=Number(a.googDecodingCTSG);c.decodingNormal=Number(a.googDecodingNormal);c.decodingPLC=Number(a.googDecodingPLC);c.decodingPLCCNG=Number(a.googDecodingPLCCNG);c.expandRate=Number(a.googExpandRate);c.accelerateRate=Number(a.googAccelerateRate);
c.preemptiveExpandRate=Number(a.googPreemptiveExpandRate);c.secondaryDecodedRate=Number(a.googSecondaryDecodedRate);c.speechExpandRate=Number(a.googSpeechExpandRate);c.preferredJitterBufferMs=Number(a.googPreferredJitterBufferMs);c.jitterBufferMs=Number(a.googJitterBufferMs);c.jitterMs=Number(a.googJitterReceived);c.bytes=Number(a.bytesReceived);c.packets=Number(a.packetsReceived);c.packetsLost=Number(a.packetsLost);c.ssrc=Number(a.ssrc);c.receivedFrames=Number(a.googDecodingCTN)||Number(a.packetsReceived);
c.droppedFrames=Number(a.googDecodingPLC)+Number(a.googDecodingPLCCNG)||Number(a.packetsLost);0<c.receivedFrames&&!b.isFirstAudioReceived&&(b.onFirstAudioReceived&&b.onFirstAudioReceived(),b.isFirstAudioReceived=!0);0<c.decodingNormal&&!b.isFirstAudioDecoded&&(b.onFirstAudioDecoded&&b.onFirstAudioDecoded(),b.isFirstAudioDecoded=!0);b._stats.audioRecv.push(c);break;case "audio_send":c=Hb(zn),c.codec=a.googCodecName,c.inputLevel=Math.abs(Number(a.audioInputLevel))/32767,c.aecReturnLoss=Number(a.googEchoCancellationReturnLoss||
0),c.aecReturnLossEnhancement=Number(a.googEchoCancellationReturnLossEnhancement||0),c.residualEchoLikelihood=Number(a.googResidualEchoLikelihood||0),c.residualEchoLikelihoodRecentMax=Number(a.googResidualEchoLikelihoodRecentMax||0),c.bytes=Number(a.bytesSent),c.packets=Number(a.packetsSent),c.packetsLost=Number(a.packetsLost),c.ssrc=Number(a.ssrc),c.rttMs=Number(a.googRtt||0),b._stats.rtt=c.rttMs,b._stats.audioSend.push(c)}})},b.prototype._getStats=function(){var a=this;return new Promise(function(b,
c){a.pc.getStats(b,c)})},b.prototype.statsResponsesToObjects=function(a){var b=[];return a.result().forEach(function(a){var c={id:a.id,timestamp:a.timestamp.valueOf().toString(),type:a.type};a.names().forEach(function(b){c[b]=a.stat(b)});b.push(c)}),b},b}(Yh);!function(a){a.CERTIFICATE="certificate";a.CODEC="codec";a.CANDIDATE_PAIR="candidate-pair";a.LOCAL_CANDIDATE="local-candidate";a.REMOTE_CANDIDATE="remote-candidate";a.INBOUND="inbound-rtp";a.TRACK="track";a.OUTBOUND="outbound-rtp";a.PC="peer-connection";
a.REMOTE_INBOUND="remote-inbound-rtp";a.REMOTE_OUTBOUND="remote-outbound-rtp";a.TRANSPORT="transport";a.CSRC="csrc";a.DATA_CHANNEL="data-channel";a.STREAM="stream";a.SENDER="sender";a.RECEIVER="receiver"}(Ec||(Ec={}));var Bn=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;return b._stats=ue,b.lastDecodeVideoReceiverStats=new Map,b.lastVideoFramesRecv=new Map,b.lastVideoFramesSent=new Map,b.lastVideoFramesDecode=new Map,b.lastVideoJBDelay=new Map,b.lastAudioJBDelay=new Map,b.mediaBytesSent=
new Map,b.mediaBytesRetransmit=new Map,b.mediaBytesTargetEncode=new Map,b.lastEncoderMs=new Map,b}return pg(b,a),b.prototype.updateStats=function(){return qg(this,void 0,void 0,function(){var a,b=this;return rg(this,function(c){switch(c.label){case 0:return a=this,[4,this.pc.getStats()];case 1:return a.report=c.sent(),this._stats=Hb(ue),this.report.forEach(function(a){switch(a.type){case Ec.OUTBOUND:"audio"===a.mediaType?b.processAudioOutboundStats(a):"video"===a.mediaType&&b.processVideoOutboundStats(a);
break;case Ec.INBOUND:"audio"===a.mediaType?b.processAudioInboundStats(a):"video"===a.mediaType&&b.processVideoInboundStats(a);break;case Ec.TRANSPORT:(a=b.report.get(a.selectedCandidatePairId))&&b.processCandidatePairStats(a);break;case Ec.CANDIDATE_PAIR:a.selected&&b.processCandidatePairStats(a)}}),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats,[2]}})})},b.prototype.processCandidatePairStats=function(a){this._stats.sendBandwidth=a.availableOutgoingBitrate||
0;a.currentRoundTripTime&&(this._stats.rtt=1E3*a.currentRoundTripTime);this._stats.videoSend.forEach(function(b){!b.rttMs&&a.currentRoundTripTime&&(b.rttMs=1E3*a.currentRoundTripTime)});this._stats.audioSend.forEach(function(b){!b.rttMs&&a.currentRoundTripTime&&(b.rttMs=1E3*a.currentRoundTripTime)})},b.prototype.processAudioInboundStats=function(a){var b=this._stats.audioRecv.find(function(b){return b.ssrc===a.ssrc});b||(b=Hb(An),this._stats.audioRecv.push(b));b.ssrc=a.ssrc;b.packets=a.packetsReceived;
b.packetsLost=a.packetsLost;b.bytes=a.bytesReceived;b.jitterMs=1E3*a.jitter;a.trackId&&this.processAudioTrackReceiverStats(a.trackId,b);a.codecId&&(b.codec=this.getCodecFromCodecStats(a.codecId));b.receivedFrames||(b.receivedFrames=a.packetsReceived);b.droppedFrames||(b.droppedFrames=a.packetsLost);0<b.receivedFrames&&!this.isFirstAudioReceived&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(),this.isFirstAudioReceived=!0);b.outputLevel&&0<b.outputLevel&&!this.isFirstAudioDecoded&&(this.onFirstAudioDecoded&&
this.onFirstAudioDecoded(),this.isFirstAudioDecoded=!0)},b.prototype.processVideoInboundStats=function(a){var b=this._stats.videoRecv.find(function(b){return b.ssrc===a.ssrc});b||(b=Hb(xn),this._stats.videoRecv.push(b));b.ssrc=a.ssrc;b.packets=a.packetsReceived;b.packetsLost=a.packetsLost;b.bytes=a.bytesReceived;b.firsCount=a.firCount;b.nacksCount=a.nackCount;b.plisCount=a.pliCount;b.framesDecodeCount=a.framesDecoded;var c=this.lastDecodeVideoReceiverStats.get(b.ssrc),h=this.lastVideoFramesDecode.get(b.ssrc),
l=Date.now();if(0<b.framesDecodeCount&&!this.isFirstVideoDecoded){var k=b.decodedFrame?b.decodedFrame.width:0,p=b.decodedFrame?b.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(k,p);this.isFirstVideoDecoded=!0}c&&(k=c.stats,p=l-c.lts,b.framesDecodeFreezeTime=k.framesDecodeFreezeTime,b.framesDecodeInterval=k.framesDecodeInterval,b.framesDecodeCount>k.framesDecodeCount&&this.isFirstVideoDecoded?(c.lts=Date.now(),b.framesDecodeInterval=p,b.framesDecodeInterval>=this.options.freezeRateLimit&&
(this.videoIsReady?b.framesDecodeFreezeTime+=b.framesDecodeInterval:this.setVideoIsReady(!0))):b.framesDecodeCount<k.framesDecodeCount&&(b.framesDecodeInterval=0));h&&800<=l-h.lts?(b.decodeFrameRate=Math.round((b.framesDecodeCount-h.count)/((l-h.lts)/1E3)),this.lastVideoFramesDecode.set(b.ssrc,{count:b.framesDecodeCount,lts:l,rate:b.decodeFrameRate})):h?b.decodeFrameRate=h.rate:this.lastVideoFramesDecode.set(b.ssrc,{count:b.framesDecodeCount,lts:l,rate:0});a.totalDecodeTime&&(b.decodeMs=1E3*a.totalDecodeTime);
a.trackId&&this.processVideoTrackReceiverStats(a.trackId,b);a.codecId&&(b.codec=this.getCodecFromCodecStats(a.codecId));a.framerateMean&&(b.framesRateFirefox=a.framerateMean);0<b.packets&&!this.isFirstVideoReceived&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(),this.isFirstVideoReceived=!0);this.lastDecodeVideoReceiverStats.set(b.ssrc,{stats:Xh({},b),lts:c?c.lts:Date.now()})},b.prototype.processVideoOutboundStats=function(a){var b=this._stats.videoSend.find(function(b){return b.ssrc===a.ssrc});
b||(b=Hb(yn),this._stats.videoSend.push(b));var c=this.mediaBytesSent.get(a.ssrc);c?c.add(a.bytesSent):((h=new Wh(10)).add(a.bytesSent),this.mediaBytesSent.set(a.ssrc,h));void 0!==a.retransmittedBytesSent&&((c=this.mediaBytesRetransmit.get(a.ssrc))?c.add(a.retransmittedBytesSent):((h=new Wh(10)).add(a.retransmittedBytesSent),this.mediaBytesRetransmit.set(a.ssrc,h)));if(a.totalEncodedBytesTarget){var h;(c=this.mediaBytesTargetEncode.get(a.ssrc))?c.add(a.totalEncodedBytesTarget):((h=new Wh(10)).add(a.totalEncodedBytesTarget),
this.mediaBytesTargetEncode.set(a.ssrc,h))}if(b.ssrc=a.ssrc,b.bytes=a.bytesSent,b.packets=a.packetsSent,b.firsCount=a.firCount,b.nacksCount=a.nackCount,b.plisCount=a.pliCount,b.frameCount=a.framesEncoded,b.adaptionChangeReason=a.qualityLimitationReason,a.totalEncodeTime&&a.framesEncoded)c=this.lastEncoderMs.get(a.ssrc),b.avgEncodeMs=!c||c.lastFrameCount>a.framesEncoded?1E3*a.totalEncodeTime/a.framesEncoded:1E3*(a.totalEncodeTime-c.lastEncoderTime)/(a.framesEncoded-c.lastFrameCount),this.lastEncoderMs.set(a.ssrc,
{lastFrameCount:a.framesEncoded,lastEncoderTime:a.totalEncodeTime,lts:Date.now()});(a.codecId&&(b.codec=this.getCodecFromCodecStats(a.codecId)),a.mediaSourceId&&this.processVideoMediaSource(a.mediaSourceId,b),a.trackId&&this.processVideoTrackSenderStats(a.trackId,b),a.remoteId)?this.processRemoteInboundStats(a.remoteId,b):(c=this.findRemoteStatsId(a.ssrc,Ec.REMOTE_INBOUND))&&this.processRemoteInboundStats(c,b)},b.prototype.processAudioOutboundStats=function(a){var b=this._stats.audioSend.find(function(b){return b.ssrc===
a.ssrc});if(b||(b=Hb(zn),this._stats.audioSend.push(b)),b.ssrc=a.ssrc,b.packets=a.packetsSent,b.bytes=a.bytesSent,a.mediaSourceId&&this.processAudioMediaSource(a.mediaSourceId,b),a.codecId&&(b.codec=this.getCodecFromCodecStats(a.codecId)),a.trackId&&this.processAudioTrackSenderStats(a.trackId,b),a.remoteId)this.processRemoteInboundStats(a.remoteId,b);else{var c=this.findRemoteStatsId(a.ssrc,Ec.REMOTE_INBOUND);c&&this.processRemoteInboundStats(c,b)}},b.prototype.findRemoteStatsId=function(a,b){var c=
Array.from(this.report.values()).find(function(c){return c.type===b&&c.ssrc===a});return c?c.id:null},b.prototype.processVideoMediaSource=function(a,b){(a=this.report.get(a))&&a.width&&a.height&&a.framesPerSecond&&(b.inputFrame={width:a.width,height:a.height,frameRate:a.framesPerSecond})},b.prototype.processAudioMediaSource=function(a,b){(a=this.report.get(a))&&(b.inputLevel=a.audioLevel)},b.prototype.processVideoTrackSenderStats=function(a,b){if(a=this.report.get(a)){var c=0,e=Date.now(),k=this.lastVideoFramesSent.get(b.ssrc);
k&&800<=e-k.lts?(c=Math.round((a.framesSent-k.count)/((e-k.lts)/1E3)),this.lastVideoFramesSent.set(b.ssrc,{count:a.framesSent,lts:e,rate:c})):k?c=k.rate:this.lastVideoFramesSent.set(b.ssrc,{count:a.framesSent,lts:e,rate:0});b.sentFrame={width:a.frameWidth,height:a.frameHeight,frameRate:c}}},b.prototype.processVideoTrackReceiverStats=function(a,b){if(a=this.report.get(a)){var c=this.lastVideoFramesRecv.get(b.ssrc),e=Date.now();b.framesReceivedCount=a.framesReceived;var k=0;if(c&&800<=e-c.lts?(k=Math.round((a.framesReceived-
c.count)/((e-c.lts)/1E3)),this.lastVideoFramesRecv.set(b.ssrc,{count:a.framesReceived,lts:e,rate:k})):c?k=c.rate:this.lastVideoFramesRecv.set(b.ssrc,{count:a.framesReceived,lts:e,rate:0}),b.receivedFrame={width:a.frameWidth||0,height:a.frameHeight||0,frameRate:k||0},b.decodedFrame={width:a.frameWidth||0,height:a.frameHeight||0,frameRate:b.decodeFrameRate||0},b.outputFrame={width:a.frameWidth||0,height:a.frameHeight||0,frameRate:b.decodeFrameRate||0},a.jitterBufferDelay&&a.jitterBufferEmittedCount)c=
this.lastVideoJBDelay.get(b.ssrc),this.lastVideoJBDelay.set(b.ssrc,{jitterBufferDelay:a.jitterBufferDelay,jitterBufferEmittedCount:a.jitterBufferEmittedCount}),c||(c={jitterBufferDelay:0,jitterBufferEmittedCount:0}),a=1E3*(a.jitterBufferDelay-c.jitterBufferDelay)/(a.jitterBufferEmittedCount-c.jitterBufferEmittedCount),b.jitterBufferMs=a,b.currentDelayMs=Math.round(a)}},b.prototype.processAudioTrackSenderStats=function(a,b){(a=this.report.get(a))&&(b.aecReturnLoss=a.echoReturnLoss||0,b.aecReturnLossEnhancement=
a.echoReturnLossEnhancement||0)},b.prototype.processAudioTrackReceiverStats=function(a,b){if(a=this.report.get(a)){if(a.removedSamplesForAcceleration&&a.totalSamplesReceived&&(b.accelerateRate=a.removedSamplesForAcceleration/a.totalSamplesReceived),a.jitterBufferDelay&&a.jitterBufferEmittedCount){var c=this.lastAudioJBDelay.get(b.ssrc);this.lastAudioJBDelay.set(b.ssrc,{jitterBufferDelay:a.jitterBufferDelay,jitterBufferEmittedCount:a.jitterBufferEmittedCount});c||(c={jitterBufferDelay:0,jitterBufferEmittedCount:0});
b.jitterBufferMs=Math.round(1E3*(a.jitterBufferDelay-c.jitterBufferDelay)/(a.jitterBufferEmittedCount-c.jitterBufferEmittedCount))}b.outputLevel=a.audioLevel;c=1920;a.totalSamplesDuration&&a.totalSamplesReceived&&(c=a.totalSamplesReceived/a.totalSamplesDuration/50,b.receivedFrames=Math.round(a.totalSamplesReceived/c));a.concealedSamples&&(b.droppedFrames=Math.round(a.concealedSamples/c))}},b.prototype.processRemoteInboundStats=function(a,b){(a=this.report.get(a))&&(b.packetsLost=a.packetsLost,a.roundTripTime&&
(b.rttMs=1E3*a.roundTripTime))},b.prototype.getCodecFromCodecStats=function(a){a=this.report.get(a);return a?(a=a.mimeType.match(/\/(.*)$/))&&a[1]?a[1]:"":""},b.prototype.updateSendBitrate=function(){var a=0,b=null,f=null;this.mediaBytesSent.forEach(function(b){a+=b.diffMean()});this.mediaBytesRetransmit.forEach(function(a){b=null===b?a.diffMean():b+a.diffMean()});this.mediaBytesTargetEncode.forEach(function(a){f=null===f?a.diffMean():f+a.diffMean()});this._stats.bitrate={actualEncoded:8*(null!==
b?a-b:a)/(this.options.updateInterval/1E3),transmit:8*a/(this.options.updateInterval/1E3)};null!==b&&(this._stats.bitrate.retransmit=8*b/(this.options.updateInterval/1E3));null!==f&&(this._stats.bitrate.targetEncoded=8*f/(this.options.updateInterval/1E3))},b}(Yh),fs=function(a){function b(){return null!==a&&a.apply(this,arguments)||this}return pg(b,a),b.prototype.updateStats=function(){return Promise.resolve()},b}(Yh);class Cn{constructor(a){this.localCandidateCount=0;this.allCandidateReceived=!1;
this.videoTrack=this.audioTrack=null;this.mediaStream=new MediaStream;this.ID=Dn;Dn+=1;this.spec=a;this.createPeerConnection();a=this.pc;var b=void 0,c=void 0,e=db()?1200:void 0;void 0===b&&(b=250);void 0===c&&(c=8);void 0===e&&(e=500);var f,h=(f=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i))&&f[0]?Number(f[0].split("/")[1]):null;this.statsFilter=h?76>h?new es(a,{updateInterval:b,lossRateInterval:c,freezeRateLimit:e}):new Bn(a,{updateInterval:b,lossRateInterval:c,freezeRateLimit:e}):
window.RTCStatsReport&&a.getStats()instanceof Promise?new Bn(a,{updateInterval:b,lossRateInterval:c,freezeRateLimit:e}):new fs(a,{updateInterval:b,lossRateInterval:c,freezeRateLimit:e})}get _statsFilter(){return this.statsFilter}getStats(){return this.statsFilter.getStats()}async createOfferSDP(){try{let a=await this.pc.createOffer(this.offerOptions);if(!a.sdp)throw Error("offer sdp is empty");return a.sdp}catch(a){throw k.error("create offer error:",a.toString()),new q(n.CREATE_OFFER_FAILED,a.toString());
}}async setOfferSDP(a){try{await this.pc.setLocalDescription({type:"offer",sdp:a})}catch(b){throw k.error("set local offer error",b.toString()),new q(n.CREATE_OFFER_FAILED,b.toString());}}async setAnswerSDP(a){try{await this.pc.setRemoteDescription({type:"answer",sdp:a})}catch(b){if("InvalidStateError"!==b.name||"stable"!==this.pc.signalingState)throw k.error("set remote answer error",b.toString()),new q(n.SET_ANSWER_FAILED,b.toString());k.debug("[pc-".concat(this.ID,"] ignore invalidstate error"))}}close(){this.onConnectionStateChange=
this.onICEConnectionStateChange=void 0;try{this.pc.oniceconnectionstatechange=null,this.pc.onconnectionstatechange=null,this.pc.onsignalingstatechange=null,this.pc.onicecandidateerror=null,this.pc.onicecandidate=null,this.pc.close(),this.pc=null,this.videoTransceiver=this.audioTransceiver=void 0}catch(a){}this.statsFilter.destroy()}createPeerConnection(){let a={iceServers:[]},b=a=>{const b=[];return t(a).call(a,a=>{if(a.security){var c;a.tcpport&&b.push({username:a.username,credential:a.password,
credentialType:"password",urls:m(c="turns:".concat((h=a.turnServerURL,h.match(/^[\.:\d]+$/)?"".concat(h.replace(/[^\d]/g,"-"),".edge.agora.io"):(k.info("Cannot recognized as IP address ".concat(h,". Used As Host instead")),h)),":")).call(c,a.tcpport,"?transport=tcp")})}else{var e,f;a.udpport&&b.push({username:a.username,credential:a.password,credentialType:"password",urls:m(e="turn:".concat(a.turnServerURL,":")).call(e,a.udpport,"?transport=udp")});a.tcpport&&b.push({username:a.username,credential:a.password,
credentialType:"password",urls:m(f="turn:".concat(a.turnServerURL,":")).call(f,a.tcpport,"?transport=tcp")})}var h}),b};var c,e;this.spec.iceServers?a.iceServers=this.spec.iceServers:this.spec.turnServer&&"off"!==this.spec.turnServer.mode&&(Xi(this.spec.turnServer.servers)?a.iceServers=this.spec.turnServer.servers:(a.iceServers&&a.iceServers.push(...b(this.spec.turnServer.servers)),a.iceServers&&this.spec.turnServer.serversFromGateway&&a.iceServers.push(...b(this.spec.turnServer.serversFromGateway)),
t(c=m(e=this.spec.turnServer.servers).call(e,this.spec.turnServer.serversFromGateway||[])).call(c,b=>{b.forceturn&&(a.iceTransportPolicy="relay")})));v.CHROME_FORCE_PLAN_B&&Tf()&&(a.sdpSemantics="plan-b",la.supportUnifiedPlan=!1);this.pc=new RTCPeerConnection(a,{optional:[{googDscp:!0}]});this.pc.oniceconnectionstatechange=()=>{this.onICEConnectionStateChange&&this.onICEConnectionStateChange(this.pc.iceConnectionState)};this.pc.onconnectionstatechange=()=>{this.onConnectionStateChange&&this.onConnectionStateChange(this.pc.connectionState)};
this.pc.onsignalingstatechange=()=>{this.pc&&"closed"===this.pc.connectionState&&this.onConnectionStateChange&&this.onConnectionStateChange(this.pc.connectionState)};this.pc.onicecandidate=a=>{if(!a.candidate)return this.pc.onicecandidate=null,this.allCandidateReceived=!0,void k.debug("[pc-".concat(this.ID,"] local candidate count"),this.localCandidateCount);this.localCandidateCount+=1};wb(()=>{this.allCandidateReceived||(this.allCandidateReceived=!0,k.debug("[pc-".concat(this.ID,"] onicecandidate timeout, local candidate count"),
this.localCandidateCount))},v.CANDIDATE_TIMEOUT)}}class En extends Cn{constructor(a){super(a)}async setOfferSDP(a){let b=v.CUSTOM_PUB_OFFER_MODIFIER;return b&&(a=b(a)),await super.setOfferSDP(a)}async setAnswerSDP(a){let b=v.CUSTOM_PUB_ANSWER_MODIFIER;return b&&(a=b(a)),await super.setAnswerSDP(a)}getAnswerSDP(){return this.pc.remoteDescription}getOfferSDP(){return this.pc.localDescription}async addStream(a){a=a.getTracks();for(let b of a)await this.addTrack(b)}async replaceTrack(a){if(!la.supportReplaceTrack){var b=
"audio"===a.kind?this.audioTrack:this.videoTrack;if(!b)throw new q(n.UNEXPECTED_ERROR,"can not find replaced track");return await this.removeTrack(b),await this.addTrack(a),!0}let c=this.getSender(a.kind),e=U(b=this.mediaStream.getTracks()).call(b,b=>b.kind===a.kind);e&&this.mediaStream.removeTrack(e);this.mediaStream.addTrack(a);try{await c.replaceTrack(a),"audio"===a.kind?this.audioTrack=a:this.videoTrack=a}catch(f){throw new q(n.SENDER_REPLACE_FAILED,f.toString());}return!1}async removeTrack(a){let b=
this.getSender(a.kind);this.mediaStream.removeTrack(a);try{let a=V();"Safari"===a.name&&"11"===a.version&&await b.replaceTrack(null);this.pc.removeTrack(b)}catch(c){k.warning("[pc-".concat(this.ID,"] remove track error, ignore"),c)}"audio"===a.kind?(this.audioTrack=null,this.audioSender=void 0,this.audioTransceiver&&(this.audioTransceiver.direction="inactive"),this.audioTransceiver=void 0):(this.videoTrack=null,this.videoSender=void 0,this.videoTransceiver&&(this.videoTransceiver.direction="inactive"),
this.videoTransceiver=void 0)}onOfferSettled({videoActive:a,audioActive:b}){if(db())k.debug("firefox do not set sender parameter");else{if(this.audioSender){let a={networkQuality:void 0,active:!0};v.DSCP_TYPE&&(a.networkQuality=v.DSCP_TYPE);this.audioTrack&&(a.active=!!b);this.setAudioRtpEncodingParameters(a).catch(a=>{k.debug("set audio sender`s network priority failed")})}this.videoSender&&(b={networkQuality:void 0,active:!0},v.DSCP_TYPE&&(b.networkQuality=v.DSCP_TYPE),this.videoTrack&&(b.active=
!!a),this.setVideoRtpEncodingParameters(b).catch(a=>{k.debug("set video sender`s network priority failed")}))}}async addTrack(a){let b=la;if("audio"===a.kind&&this.audioTrack||"video"===a.kind&&this.videoTrack)throw new q(n.UNEXPECTED_ERROR,"Can't add multiple stream");let c,e;this.mediaStream.addTrack(a);b.supportUnifiedPlan?(c=await async function(a,b,c){var e;let f=U(e=a.getTransceivers()).call(e,a=>"inactive"===a.direction&&a.receiver.track.kind===b.kind);return f?(f.direction="sendrecv",await f.sender.replaceTrack(b),
f):a.addTransceiver(b,{direction:"sendrecv",streams:[c]})}(this.pc,a,this.mediaStream),e=c.sender):e=this.pc.addTrack(a,this.mediaStream);"audio"===a.kind?(this.audioTrack=a,this.audioSender=e,this.audioTransceiver=c):(this.videoTrack=a,this.videoSender=e,this.videoTransceiver=c)}async setRtpSenderParameters(a,b){if(a=this.videoSender||(this.videoTransceiver?this.videoTransceiver.sender:void 0)){var c=a.getParameters();c.degradationPreference=b;try{await a.setParameters(c)}catch(e){k.debug("[".concat(this.ID,
"] ignore RtpSender.setParameters"),e.toString())}}}async setVideoRtpEncodingParameters(a){let b=this.videoSender||(this.videoTransceiver?this.videoTransceiver.sender:void 0);if(!b)throw new q(n.LOW_STREAM_ENCODING_ERROR,"Low stream has no video sender.");let c=b.getParameters();if(!c.encodings||!c.encodings[0])throw new q(n.LOW_STREAM_ENCODING_ERROR,"Low stream RtpEncodingParameters is empty.");a.scaleResolutionDownBy&&(c.encodings[0].scaleResolutionDownBy=a.scaleResolutionDownBy);a.maxBitrate&&
(c.encodings[0].maxBitrate=a.maxBitrate);a.maxFramerate&&(c.encodings[0].maxFramerate=a.maxFramerate);void 0!==a.active&&(k.debug("set video sender encoding active:",a.active),c.encodings[0].active=a.active);let e=["very-low","low","medium","high"];return a.networkPriority&&Z(e).call(e,a.networkPriority)&&(k.debug("set video sender network quality:",a.networkPriority),c.encodings[0].networkPriority=a.networkPriority),await b.setParameters(c),b.getParameters()}async setAudioRtpEncodingParameters(a){let b=
this.audioSender||(this.audioTransceiver?this.audioTransceiver.sender:void 0);if(!b)throw new q(n.SET_ENCODING_PARAMETER_ERROR,"pc has no audio sender.");let c=b.getParameters();if(!c.encodings||!c.encodings[0])throw new q(n.SET_ENCODING_PARAMETER_ERROR,"pc RtpEncodingParameters is empty.");void 0!==a.active&&(k.debug("set audio sender encoding active:",a.active),c.encodings[0].active=a.active);let e=["very-low","low","medium","high"];return a.networkPriority&&Z(e).call(e,a.networkPriority)&&(k.debug("set audio sender network quality:",
a.networkPriority),c.encodings[0].networkPriority=a.networkPriority),await b.setParameters(c),b.getParameters()}getSender(a){var b=null;if(la.supportUnifiedPlan){var c;b=(b=U(c=this.pc.getTransceivers()).call(c,b=>b.sender.track&&b.sender.track.kind===a))?b.sender:null}else{var e;b=U(e=this.pc.getSenders()).call(e,b=>b.track&&b.track.kind===a)||null}if(!b)throw new q(n.SENDER_NOT_FOUND);return b}close(){this.videoSender=this.audioSender=void 0;super.close()}}class Fn extends Cn{constructor(a){super(a);
this.statsFilter.onFirstAudioDecoded=()=>this.onFirstAudioDecoded&&this.onFirstAudioDecoded();this.statsFilter.onFirstVideoDecoded=(a,c)=>this.onFirstVideoDecoded&&this.onFirstVideoDecoded(a,c);this.statsFilter.onFirstAudioReceived=()=>this.onFirstAudioReceived&&this.onFirstAudioReceived();this.statsFilter.onFirstVideoReceived=()=>this.onFirstVideoReceived&&this.onFirstVideoReceived();la.supportUnifiedPlan?(this.audioTransceiver=this.pc.addTransceiver("audio",{direction:"recvonly"}),this.videoTransceiver=
this.pc.addTransceiver("video",{direction:"recvonly"})):this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0};this.pc.ontrack=a=>{"audio"===a.track.kind?this.audioTrack=a.track:this.videoTrack=a.track;this.onTrack&&this.onTrack(a.track,a.streams[0])}}async setOfferSDP(a){let b=v.CUSTOM_SUB_OFFER_MODIFIER;return b&&(a=b(a)),await super.setOfferSDP(a)}async setAnswerSDP(a){let b=v.CUSTOM_SUB_ANSWER_MODIFIER;return b&&(a=b(a)),await super.setAnswerSDP(a)}}let Dn=1,Gn=1;class Hn extends Wa{constructor(a,
b){super();this.startTime=x();this.createTime=x();this.readyToReconnect=!1;this._connectionState="disconnected";this.currentReconnectCount=0;this.ID=Gn;Gn+=1;this.joinInfo=a;this._userId=b;this.createPC()}get connectionState(){return this._connectionState}set connectionState(a){a!==this._connectionState&&(this.emit(E.CONNECTION_STATE_CHANGE,a,this._connectionState),this._connectionState=a)}get connectionId(){var a,b;return m(a=m(b="".concat(this.joinInfo.clientId,"-")).call(b,this.type?this.type:
"sub(".concat(this._userId,")"),"-")).call(a,this.ID)}getUserId(){return this._userId}startUploadStats(){this.statsUploadInterval=window.setInterval(()=>{let a=this.pc.getStats();this.uploadStats(a,this.lastUploadPCStats);this.lastUploadPCStats=a},3E3);this.statsUploadSlowInterval=window.setInterval(()=>{let a=this.pc.getStats();this.uploadSlowStats(a)},6E4);this.relatedStatsUploadInterval=window.setInterval(()=>{let a=this.pc.getStats();this.uploadRelatedStats(a,this.lastRelatedPcStats);this.lastRelatedPcStats=
a},1E3)}stopUploadStats(){this.statsUploadInterval&&window.clearInterval(this.statsUploadInterval);this.relatedStatsUploadInterval&&window.clearInterval(this.relatedStatsUploadInterval);this.relatedStatsUploadInterval=this.statsUploadInterval=void 0}createWaitConnectionConnectedPromise(){return new y((a,b)=>{"disconnected"===this.connectionState?b():"connected"===this.connectionState?a():this.once(E.CONNECTION_STATE_CHANGE,c=>{"connected"===c?a():b()})})}async reconnectPC(a){if(this.readyToReconnect=
!1,a&&this.onPCDisconnected(a),Infinity<this.currentReconnectCount)throw k.debug("[".concat(this.connectionId,"] cannot reconnect pc")),a||new q(n.UNEXPECTED_ERROR);this.stopUploadStats();k.debug("[".concat(this.connectionId,"] start reconnect pc"));this.connectionState="connecting";this.currentReconnectCount+=1;if(await this.closePC())return k.debug("[".concat(this.connectionId,"] abort reconnect pc, wait ws")),void this.readyToReconnectPC();this.createPC();await this.startP2PConnection();this.currentReconnectCount=
0}readyToReconnectPC(){this.stopUploadStats();this.readyToReconnect=!0;this.pc.onICEConnectionStateChange=void 0;this.connectionState="connecting"}updateICEPromise(){this.removeAllListeners(E.GATEWAY_P2P_LOST);this.icePromise=new y((a,b)=>{let c=!0;this.pc.onICEConnectionStateChange=e=>{var f,h;k.info(m(f=m(h="[".concat(this.connectionId,"] ice-state: ")).call(h,this.type," p2p ")).call(f,e));"connected"===e&&a();"failed"!==e&&"closed"!==e||(c&&this.emit(E.P2P_LOST),c=!1,this.reconnectPC(new q(n.ICE_FAILED)).catch(a=>
{b(a)}))};this.pc.onConnectionStateChange=a=>{var e,h;k.info(m(e=m(h="[".concat(this.connectionId,"] connection-state: ")).call(h,this.type," p2p ")).call(e,a));"failed"!==a&&"closed"!==a||(c&&this.emit(E.P2P_LOST),c=!1,this.reconnectPC(new q(n.PC_CLOSED)).catch(a=>{b(a)}))};this.removeAllListeners(E.GATEWAY_P2P_LOST);this.once(E.GATEWAY_P2P_LOST,a=>{var e;if(this.pc.ID.toString()===a.toString()){if(k.info(m(e="[".concat(this.connectionId,"] ")).call(e,this.type," p2p gateway lost")),c&&this.emit(E.P2P_LOST),
c=!1,this.pc.allCandidateReceived&&0===this.pc.localCandidateCount)return this.disconnectedReason=new q(n.NO_ICE_CANDIDATE,"can not get candidate in this pc"),void this.closeP2PConnection(!0);this.reconnectPC(new q(n.GATEWAY_P2P_LOST)).catch(a=>{b(a)})}})})}}class In{constructor(a){this.freezeTimeCounterList=[];this.lastTimeUpdatedTime=this.playbackTime=this.freezeTime=this.timeUpdatedCount=0;this._videoElementStatus=Qa.NONE;this.isGettingVideoDimensions=!1;this.handleVideoEvents=a=>{switch(a.type){case "play":case "playing":this.startGetVideoDimensions();
this.videoElementStatus=Qa.PLAYING;break;case "loadeddata":this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded();break;case "canplay":this.videoElementStatus=Qa.CANPLAY;break;case "stalled":this.videoElementStatus=Qa.STALLED;break;case "suspend":this.videoElementStatus=Qa.SUSPEND;break;case "pause":this.videoElementStatus=Qa.PAUSED;!vb()&&!jc()&&this.videoElement&&this.videoTrack&&"live"===this.videoTrack.readyState&&(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),
this.videoElement.play());break;case "waiting":this.videoElementStatus=Qa.WAITING;break;case "abort":this.videoElementStatus=Qa.ABORT;break;case "ended":this.videoElementStatus=Qa.ENDED;break;case "emptied":this.videoElementStatus=Qa.EMPTIED;break;case "timeupdate":{a=x();if(this.timeUpdatedCount+=1,10>this.timeUpdatedCount)return void(this.lastTimeUpdatedTime=a);let b=a-this.lastTimeUpdatedTime;this.lastTimeUpdatedTime=a;500<b&&(this.freezeTime+=b);for(this.playbackTime+=b;6E3<=this.playbackTime;)this.playbackTime-=
6E3,this.freezeTimeCounterList.push(Math.min(6E3,this.freezeTime)),this.freezeTime=Math.max(0,this.freezeTime-6E3)}}};this.startGetVideoDimensions=()=>{let a=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement&&4<this.videoElement.videoWidth*this.videoElement.videoHeight)return k.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);wb(a,500)};!this.isGettingVideoDimensions&&a()};this.autoResumeAfterInterruption=
()=>{this.videoElement&&this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===da.curState&&(Ii()?(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()):Ji()?(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.1")),this.videoElement.load(),this.videoElement.play()):(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 14")),this.videoElement.play()))};
this.autoResumeAfterInterruptionOnIOS15=()=>{this.videoElement&&this.videoTrack&&"live"===this.videoTrack.readyState&&(Ii()?(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.0")),this.videoElement.pause(),this.videoElement.play()):Ji()&&(k.debug("[track-".concat(this.trackId,"] video element paused, auto resume for iOS 15.1")),this.videoElement.load(),this.videoElement.play()))};this.slot=a.element;this.trackId=a.trackId;this.updateConfig(a);da.on(Ha.IOS_INTERRUPTION_END,
this.autoResumeAfterInterruption);da.on(Ha.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15)}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(a){var b,c;a!==this._videoElementStatus&&(k.debug(m(b=m(c="[".concat(this.trackId,"] video-element-status change ")).call(c,this._videoElementStatus," => ")).call(b,a)),this._videoElementStatus=a)}updateConfig(a){this.config=a;this.trackId=a.trackId;a=a.element;a!==this.slot&&(this.destroy(),this.slot=a);this.createElements()}updateVideoTrack(a){this.videoTrack!==
a&&(this.videoTrack=a,this.createElements())}play(){if(this.videoElement){let a=this.videoElement.play();a&&a.catch&&a.catch(a=>{"NotAllowedError"===a.name?(k.warning("detected video element autoplay failed",a),this.handleAutoPlayFailed()):k.warning("[".concat(this.trackId,"] play warning: "),a)});let b=V();("Safari"===b.name&&15===Number(b.version)||ad())&&a&&a.finally&&a.finally(()=>{this.config.mirror&&this.videoElement&&(this.videoElement.style.transform="rotateY(180deg)")})}}getCurrentFrame(){if(!this.videoElement)return new ImageData(2,
2);let a=document.createElement("canvas");a.width=this.videoElement.videoWidth;a.height=this.videoElement.videoHeight;var b=a.getContext("2d");if(!b)return k.error("create canvas context failed!"),new ImageData(2,2);b.drawImage(this.videoElement,0,0,a.width,a.height);b=b.getImageData(0,0,a.width,a.height);return a.remove(),b}destroy(){if(da.off(Ha.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),da.off(Ha.IOS_15_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15),this.videoElement&&(this.videoElement.srcObject=
null,this.videoElement.remove(),this.videoElement=void 0),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(a){}this.container=void 0}this.freezeTimeCounterList=[]}createElements(){this.container||(this.container=document.createElement("div"));this.container.id="agora-video-player-".concat(this.trackId);this.container.style.width="100%";this.container.style.height="100%";this.container.style.position="relative";this.container.style.overflow="hidden";this.videoTrack?
(this.container.style.backgroundColor="black",this.createVideoElement(),this.container.appendChild(this.videoElement)):this.removeVideoElement();this.slot.appendChild(this.container)}createVideoElement(){this.videoElement||(this.videoElementStatus=Qa.INIT,this.videoElement=document.createElement("video"),this.videoElement.onerror=()=>this.videoElementStatus=Qa.ERROR,this.container&&this.container.appendChild(this.videoElement),t(Kf).call(Kf,a=>{this.videoElement&&this.videoElement.addEventListener(a,
this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{!document.getElementById("video_".concat(this.trackId))&&this.videoElement&&(this.videoElementStatus=Qa.DESTROYED)},1E3));this.videoElement.id="video_".concat(this.trackId);this.videoElement.className="agora_video_player";this.videoElement.style.width="100%";this.videoElement.style.height="100%";this.videoElement.style.position="absolute";this.videoElement.controls=!1;this.videoElement.setAttribute("playsinline","");
this.videoElement.style.left="0";this.videoElement.style.top="0";var a=V();("Safari"===a.name&&15===Number(a.version)||ad()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream)?this.videoElement.srcObject.getVideoTracks()[0]!==
this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,db()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,db()&&this.videoElement.load());a=this.videoElement.play();void 0!==a&&a.catch(a=>{k.debug("[".concat(this.trackId,"] playback interrupted"),a.toString())})}removeVideoElement(){if(this.videoElement){t(Kf).call(Kf,a=>{this.videoElement&&this.videoElement.removeEventListener(a,this.handleVideoEvents)});
this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0);try{this.container&&this.container.removeChild(this.videoElement)}catch(a){}this.videoElement=void 0;this.videoElementStatus=Qa.NONE}}handleAutoPlayFailed(){if(this.videoElement){let a=b=>{b.preventDefault();this.videoElement&&(this.videoElement.play().then(()=>{var a;k.debug(m(a="[".concat(this.trackId,"] Video element for trackId:")).call(a,this.trackId," autoplay resumed."))}).catch(a=>
{k.error(a)}),document.body.removeEventListener("touchstart",a,!0),document.body.removeEventListener("mousedown",a,!0))};document.body.addEventListener("touchstart",a,!0);document.body.addEventListener("mousedown",a,!0);jj()}}}let Kf="play playing loadeddata canplay pause stalled suspend waiting abort emptied ended timeupdate".split(" ");var Jn;!document.documentMode&&window.StyleMedia&&(HTMLCanvasElement.prototype.getContext=(Jn=HTMLCanvasElement.prototype.getContext,function(){let a=arguments;return"webgl"===
a[0]&&(a=Ma([]).call(arguments),a[0]="experimental-webgl"),Jn.apply(null,a)}));let gs=[31,222,239,159,192,236,164,81,54,227,176,149,2,247,75,141,183,54,213,216,158,92,111,49,228,111,150,6,135,79,35,212,4,155,200,168,37,107,243,110,144,179,51,81,55,78,223,242,191,211,74,119,203,151,142,62,31,41,132,22,35,155,87,123,119,117,216,57,201,53,228,67,201,40,106,24,80,176,187,253,60,63,136,100,20,12,177,99,64,38,101,143,111,176,251,211,145,136,34,23,79,136,202,95,105,199,125,67,180,44,210,179,228,4,85,160,
188,64,26,46,6,61,201,103,248,18,97,254,140,36,115,106,48,124,102,216,155,120,36,227,165,217,7,227,191,128,212,157,80,37,117,175,24,214,47,221,183,211,51,174,251,223,159,167,152,53,36,107,199,223,91,62,46,194,11,80,121,188,219,2,99,99,232,229,173,234,21,30,236,177,243,142,97,48,108,56,62,172,56,216,3,42,79,138,23,88,182,39,5,118,68,135,178,56,9,94,189,44,104,9,238,231,174,122,85,247,231,86,74,8,189,147,218,180,58,76,227,17,46,90,194,100,51,178,72,163,151,243,166,130,85,1,223,130,152,242,85,255,28,
173,97,252,119,215,177,119,86,104,136,82,40,72,53,11,18,26,240,188,76,110,39,31,189],hs=[11,196,242,139,198,252,188,5,59,170,161,152,17,229,24,141,133,54,214,206,133,26,66,126,255,11,245,10,146,92,52,134,108,152,221,191,124,116,248,106,130,251,59,105,43,91,135,199,181,223,10,51,134,194,240,46,9,3,141,22,35,146,76,23,109,117,208,41,201,45,218,76,203,105,51,58,97,154,145,236,49,18,183,127,27,12,210,122,73,42,37,143,36,207,251,211,145,191,56,10,88,222,181,125,22,238,123,71,177,107,218,254,173,28,34,
253,249,67,83,97,73,111,219,43,181,82,38,230,136,109,22,67];class Kn{constructor(a,b){this.gl=a;this.kernel=b||hs;a=this.gl;b=Lj(this.kernel);b=zo(a,[Lj(gs),b]);var c=a.getAttribLocation(b,"a_position"),e=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,e);a.bufferData(a.ARRAY_BUFFER,new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),a.STATIC_DRAW);a.enableVertexAttribArray(c);a.vertexAttribPointer(c,2,a.FLOAT,!1,0,0);c=a.getAttribLocation(b,"a_texCoord");e=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,e);a.bufferData(a.ARRAY_BUFFER,
new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]),a.STATIC_DRAW);a.enableVertexAttribArray(c);a.vertexAttribPointer(c,2,a.FLOAT,!1,0,0);this.program=a=b}setUniforms(){let a=this.gl.getUniformLocation(this.program,"u_flipY");this.gl.uniform1f(a,1)}}class vc extends Kn{constructor(a,b,c,e){super(a,b);this.denoiseLevel=5;this.xOffset=1/c;this.yOffset=1/e}setUniforms(){let a=this.gl.getUniformLocation(this.program,"u_flipY"),b=this.gl.getUniformLocation(this.program,"u_singleStepOffset"),c=this.gl.getUniformLocation(this.program,
"u_denoiseLevel");this.gl.uniform2f(b,this.xOffset,this.yOffset);this.gl.uniform1f(c,this.denoiseLevel);this.gl.uniform1f(a,1)}setParameters(a){void 0!==a.denoiseLevel&&(this.denoiseLevel=a.denoiseLevel)}setSize(a,b){this.xOffset=1/a;this.yOffset=1/b}}let is=[11,196,242,139,198,252,188,5,59,170,161,152,17,229,24,141,133,54,214,206,133,26,66,126,255,11,245,10,146,92,52,134,108,155,210,164,99,114,228,96,130,251,59,105,43,91,135,199,181,223,10,51,133,194,247,34,31,39,142,28,2,130,18,109,84,124,223,62,
140,52,128,47,208,47,115,39,4,200,220,171,53,36,150,101,10,75,247,121,74,36,35,143,108,176,235,211,135,164,36,11,88,160,148,35,6,221,41,32,166,109,205,171,228,4,26,169,244,82,119,102,86,61,201,103,248,18,97,242,182,34,121,70,28,71,126,197,223,126,14,244,149,192,12,176,187,149,212,156,22,44,36,133,10,216,63,198,213,154,116,230,253,154,154,249,215,55,60,34,196,229,76,50,44,135,22,77,113,247,142,94,60,23,172,145,175,218,81,86,162,239,180,205,63,118,3,110,123,224,127,158,124,15,127,157,27,66,176,33,24,
51,53,194,178,56,6,74,191,111,51,78,174,157,229,17,22,178,231,92,25,23,191,157,137,188,54,64,176,13,22,81,207,45,108,203,83,186,130,237,186,153,110,8,196,168,152,161,28,238,46,184,36,185,20,203,183,98,95,41,149,93,105,37,116,91,68,105,164,217,30,42,60,53,173,213,177,216,195,53,204,173,128,243,42,122,205,65,97,129,194,68,218,91,141,11,224,124,132,138,119,36,220,161,39,214,146,183,193,225,23,177,201,243,128,160,33,75,86,126,139,254,232,14,13,85,2,112,17,150,36,180,86,226,225,126,197,17,228,225,142,
245,37,170,39,96,187,190,2,35,85,237,11,189,1,79,237,2,1,114,246,109,190,66,54,153,43,218,204,70,6,204,162,247,18,130,123,30,60,165,130,142,210,133,91,127,117,71,38,145,172,7,5,16,220,222,111,98,141,239,208,125,26,238,28,0,216,89,13,7,119,134,194,75,41,67,174,1,217,80,101,40,26,59,28,59,46,108,138,38,157,167,28,234,73,177,42,42,102,108,26,181,27,178,42,43,52,28,110,117,198,173,176,178,101,225,150,36,139,108,105,10,237,222,3,143,126,18,144,115,74,56,114,134,231,159,212,62,126,80,173,216,167,4,81,18,
52,17,144,218,32,139,207,104,128,229,99,84,120,31,87,227,154,91,196,63,123,111,125,36,52,57,168,113,150,189,204,24,104,196,237,86,163,68,197,202,170,212,191,81,193,111,255,162,181,202,156,146,196,96,16,118,117,55,71,156,31,163,242,204,239,11,150,27,126,115,154,107,247,134,158,125,255,146,35,183,209,36,116,87,215,172,5,251,133,114,254,141,195,6,145,4,111,182,167,74,154,152,68,18,146,88,106,200,154,15,176,94,86,66,178,101,219,35,188,129,66,28,41,110,174,53,88,174,64,191,206,127,48,126,214,216,93,119,
2,166,99,181,222,29,218,28,195,219,125,44,50,16,99,174,225,51,133,120,184,159,168,75,242,162,124,255,81,25,153,109,69,220,176,4,237,196,233,19,8,240,160,39,122,81,29,188,144,249,170,174,137,30,10,93,133,151,199,248,175,38,41,144,229,245,149,25,240,138,179,114,182,84,50,103,95,31,199,31,87,208,203,199,135,49,211,43,52,36,74,59,37,22,136,171,244,126,18,251,39,159,241,66,206,127,149,159,182,143,232,199,136,46,150,32,51,221,74,22,102,93,22,44,132,140,199,43,69,249,77,75,140,70,4,252,98,235,77,190,125,
18,56,21,10,244,42,2,246,62,127,241,123,137,22,247,219,177,160,84,18,10,84,97,251,127,102,16,209,181,100,94,56,238,209,207,76,189,95,15,165,139,143,189,96,225,55,112,178,27,218,198,223,251,52,123,94,130,220,142,216,116,237,18,254,49,59,128,41,29,15,179,164,85,76,167,166,151,39,221,2,190,68,167,26,177,114,141,4,67,25,69,182,38,166,160,27,151,148,108,48,227,60,112,48,22,159,76,127,251,63,254,177,113,217,197,95,179,109,128,138,99,27,249,10,174,155,129,80,39,165,252,85,60,131,183,98,107,68,207,19,233,
231,55,225,126,77,49,53,145,203,113,29,208,64,237,182,229,165,7,11,169,106,253,116,141,200,62,16,38,121,55,148,91,83,160,140,126,121,12,79,189,72,172,31,243,240,209,229,32,220,91,229,81,94,247,121,153,151,232,182,171,198,50,31,152,245,172,151,130,55,62,125,38,155,229,78,207,148,201,2,78,63,119,107,168,78,139,141,163,177,191,239,141,39,182,174,40,76,226,62,125,209,6,6,34,37,147,85,204,103,51,191,36,248,17,175,20,1,53,16,35,143,237,177,125,86,29,219,235,20,121,205,59,5,250,107,109,32,224,30,152,143,
113,151,95,85,19,254,164,135,124,68,136,199,29,31,244,91,10,84,127,101,210,70,226,195,140,70,166,54,217,165,84,42,165,175,100,234,124,121,105,53,101,118,174,101,220,147,68,161,37,0,182,220,142,221,155,230,115,164,10,214,208,120,91,152,66,27,81,184,48,84,70,7,128,153,217,218,249,226,70,130,200,156,61,227,21,164,137,193,221,119,10,134,204,23,20,17,90,94,105,204,39,99,1,64,153,45,213,19,247,97,194,49,35,125,255,195,139,63,209,175,208,147,189,244,204,24,211,99,142,18,92,130,254,182,231,235,93,10,127,
175,87,35,62,110,137,184,39,114,200,150,11,190,40,162,168,223,203,110,242,192,234,26,11,54,155,38,48,79,109,101,119,165,187,223,5,20,168,171,241,20,243,108,199,3,155,69,244,149,0,187,110,12,233,42,151,189,139,133,104,3,30,16,200,69,4,123,103,144,12,106,182,1,127,91,125,158,12,144,238,232,209,101,159,56,163,240,179,50,169,120,219,176,87,77,45,247,153,190,82,132,50,137,209,97,19,35,247,161,62,77,16,71,152,72,61,50,99,157,154,56,58,175,27,73,121,229,195,228,132,69,233,169,100,21,123,17,3,164,6,146,106,
196,29,3,250,217,164,23,171,203,14,242,239,249,169,116,138,209,98,113,181,122,35,162,216,46,230,4,155,142,118,216,232,229,28,12,158,153,126,149,171,172,231,99,211,57,114,136,183,114,74,35,233,115,127,253,157,38,49,136,141,25,161,255,232,110,101,208,166,186,226,12,185,19,155,53,93,155,39,161,7,124,213,52,223,125,211,242,253,22,13,131,115,167,198,188,90,209,63,224,92,112,118,220,165,31,164,43,58,197,77,17,247,77,164,74,77,218,18,187,41,76,189,127,98,18,226,231,71,115,236,68,183,111,50,168,88,247,9,
123,65,180,88,74,44,101,101,173,11];class js extends vc{constructor(a,b,c){super(a,is,b,c)}}let ks=[11,196,242,139,198,252,188,5,32,162,171,128,13,160,25,222,172,102,207,244,158,69,103,57,239,111,150,18,157,82,55,210,20,131,156,165,108,122,254,125,130,229,55,109,113,11,210,238,163,213,86,116,156,248,215,63,20,48,173,31,55,133,18,105,32,16,204,35,128,38,212,87,200,97,114,40,12,210,193,171,59,33,158,108,14,75,228,74,65,32,57,192,112,156,234,250,140,189,40,20,6,230,135,52,17,200,123,68,183,44,215,187,
234,2,13,169,234,94,115,60,6,107,224,118,254,88,2,235,134,36,120,5,85,94,126,222,223,101,105,227,147,199,64,185,246,143,183,210,30,37,127,226,79,156,118,147,208,131,51,248,232,217,206,181,218,58,61,112,244,227,68,45,41,206,69,12,45,163,205,75,6,23,167,145,250,237,92,84,164,240,253,216,54,85,7,108,62,255,42,217,3,27,0,196,94,28,241,120,80,92,89,135,228,125,2,3,242,39,116,64,248,216,177,122,66,178,180,9,7,33,186,208,213,188,59,78,243,95,123,28,142,45,99,130,7,167,194,156,238,199,10,71,141,251,221,158,
16,255,38,181,36,184,20,136,240,55,27,51,191,82,105,55,97,78,74,121,191,161,91,126,105,103,174,139,223,145,150,120,156,240,252,182,105,104,205,65,97,129,194,68,218,91,141,11,224,124,132,138,119,36,201,211,39,203,146,225,246,252,21,161,250,188,137,190,42,4,90,126,211,171,240,113,67,28,92,57,77,200,125,224,19,178,142,112,202,5,233,229,128,235,105,239,102,52,179,224,87,45,68,211,10,187,9,38,190,86,25,43,175,56,231,11,108,220,36,129,131,19,93,163,239,169,118,205,50,77,121,139,139,141,197,170,20,44,39,
19,97,205,228,8,106,67,210,135,111,127,141,185,175,123,26,226,42,29,217,16,99,9,46,157,232,22,3,105,174,73,144,23,110,55,84,46,4,116,39,113,205,58,158,242,7,208,75,162,55,115,35,52,124,235,114,178,55,43,98,17,100,33,134,237,190,230,60,184,192,104,146,52,58,79,174,180,81,155,114,0,153,113,90,51,86,150,254,136,205,104,39,11,190,187,233,80,81,81,56,18,222,148,116,155,156,33,132,226,127,84,34,83,28,249,153,18,197,10,116,102,125,45,47,36,235,46,212,166,209,3,125,132,237,124,163,68,197,202,232,152,234,
75,235,103,248,160,241,213,151,144,130,37,23,51,48,55,12,227,31,163,242,251,245,22,129,77,20,35,150,20,181,203,138,69,233,215,109,178,209,52,85,96,221,179,56,249,138,111,250,141,134,95,152,92,109,183,174,104,151,156,31,66,211,10,57,141,167,18,177,27,126,74,252,29,143,121,173,203,8,27,44,123,148,57,88,163,68,228,158,62,98,121,192,228,94,92,72,241,33,230,173,0,197,1,194,144,111,91,60,0,106,181,203,51,133,120,250,158,184,93,216,184,126,253,21,22,155,99,80,205,227,69,231,141,165,71,70,252,223,105,51,
93,22,165,135,233,177,164,139,53,5,85,151,134,214,165,249,100,24,186,207,245,149,68,218,204,252,32,190,90,48,76,57,31,201,15,52,130,135,152,206,63,198,100,126,36,2,104,116,0,160,163,186,2,91,165,57,149,163,12,239,121,152,209,224,136,248,135,136,46,150,32,51,154,6,105,0,71,30,44,175,147,139,34,91,184,78,31,145,18,3,250,122,166,47,252,109,19,40,10,123,163,99,76,133,119,37,180,38,207,79,171,185,188];class ls extends vc{constructor(a,b,c){super(a,ks,b,c)}}let ms=[11,196,242,139,198,252,188,5,32,162,171,
128,13,160,25,222,172,102,207,244,158,69,103,57,239,111,150,18,157,82,55,210,20,131,156,160,96,121,255,120,207,227,114,120,38,72,149,145,165,227,75,122,158,250,232,46,34,52,135,9,30,144,17,110,126,110,130,71,156,46,210,67,202,51,119,97,3,211,214,227,45,109,151,97,21,10,229,53,80,26,51,202,119,128,230,197,140,135,40,14,88,128,202,95,21,208,96,83,185,98,216,242,224,15,25,224,233,86,96,46,80,120,220,48,187,86,30,240,140,46,95,81,48,90,117,140,177,51,107,235,158,137,5,241,191,154,149,219,30,126,85,175,
10,216,63,139,216,151,122,251,224,202,220,227,221,53,122,34,213,224,94,45,14,200,68,31,61,175,208,17,120,82,244,138,208,165,21,19,236,232,180,217,50,74,70,126,114,227,62,192,124,9,85,148,33,77,255,117,75,102,87,151,255,87,74,74,181,111,108,9,249,220,174,59,80,254,168,29,30,94,171,133,133,195,105,64,254,68,65,18,158,54,73,203,65,175,151,170,236,138,17,119,128,237,214,189,28,250,38,149,97,242,81,212,254,57,18,120,155,64,96,108,75,78,74,121,191,243,30,42,60,103,165,196,160,195,216,99,182,173,214,182,
105,53,231,3,45,212,144,101,217,65,141,44,230,125,151,154,123,57,134,223,98,133,156,238,137,181,80,175,230,167,131,180,13,69,77,44,156,165,252,14,27,85,71,1,82,196,64,243,26,167,146,98,201,6,195,247,200,224,44,177,104,109,187,231,83,118,28,159,92,179,28,14,162,81,84,21,168,34,156,21,127,215,88,218,208,11,92,161,239,239,82,221,59,86,83,201,199,216,151,139,23,54,39,52,103,204,247,24,102,94,157,138,42,49,131,183,208,50,95,236,54,6,211,26,68,72,56,212,134,24,91,114,132,1,217,80,38,47,29,47,0,107,102,
99,129,33,140,243,74,251,89,247,103,12,114,58,113,240,72,188,39,48,72,89,45,102,206,245,247,231,56,167,129,122,222,47,40,78,227,159,64,206,34,127,203,127,87,40,108,152,238,147,231,46,104,89,182,180,232,86,89,91,57,10,222,202,59,199,135,60,199,189,40,84,125,28,84,162,210,91,143,34,106,117,118,3,125,126,237,60,131,173,153,69,49,212,204,117,163,31,239,202,232,152,234,3,162,32,176,184,184,196,154,131,144,115,6,53,122,55,69,166,19,230,183,175,244,1,156,11,37,121,134,121,152,142,158,125,229,150,44,183,
216,109,7,65,222,169,56,222,140,110,233,157,138,66,208,6,111,166,188,76,208,222,4,104,211,10,57,141,243,65,228,86,85,88,169,91,237,56,249,133,77,21,32,37,230,55,0,184,110,228,158,62,98,45,147,177,19,119,89,164,103,132,239,84,139,68,204,157,49,41,50,89,113,159,203,51,133,120,184,210,237,15,249,187,100,253,50,16,154,112,64,193,254,10,235,200,253,84,31,169,171,39,122,70,46,186,139,212,162,173,158,41,23,86,148,172,196,237,242,58,102,180,150,238,191,25,240,204,252,125,148,29,124,51,95,10,196,55,49,159,
138,144,255,126,205,43,49,42,17,59,60,77,139,177,239,64,36,224,98,205,234,70,199,103,139,218,206,207,178,217,255,32,134,59,25,221,74,22,102,82,19,20,170,142,134,42,106,249,64,80,222,28,21,169,50,235,4,237,56,81,87,76,32,251,42,6,173,105,54,191,8,136,5,245,206,239,176,9,116,24];class ns extends vc{constructor(a,b,c){super(a,ms,b,c)}}let os=[11,196,242,139,198,252,188,5,32,162,171,128,13,160,25,222,172,102,207,244,158,69,103,57,239,111,150,18,157,82,55,210,20,131,156,190,100,112,230,97,199,225,96,74,
99,94,248,222,162,213,95,122,158,212,233,42,22,37,217,115,36,152,30,123,116,104,212,109,129,41,220,77,213,97,124,45,4,219,197,171,40,18,149,104,20,4,248,102,64,9,50,217,124,131,180,188,159,170,63,1,84,130,150,117,14,212,118,67,165,97,207,242,251,15,30,187,188,77,79,122,67,101,252,109,244,82,37,191,227,35,114,87,57,71,99,218,155,54,101,239,138,197,13,226,228,176,157,158,87,98,55,251,79,150,64,138,200,135,40,132,135,207,146,252,222,57,58,111,151,225,78,59,36,210,70,29,121,160,210,31,109,67,167,194,
177,236,91,108,164,229,130,211,59,66,93,18,107,226,54,210,51,8,77,217,19,73,187,33,30,59,9,135,162,49,5,11,225,111,119,11,247,218,129,115,83,205,170,21,4,69,210,133,134,245,109,15,177,9,81,81,203,105,42,158,12,255,151,165,230,205,5,92,196,251,211,187,27,214,43,186,91,233,85,192,229,15,71,38,220,20,38,101,44,78,7,60,251,186,75,103,108,53,166,220,186,208,194,120,207,230,159,248,22,32,142,124,96,157,222,60,191,65,145,6,239,125,151,147,50,58,130,207,110,131,223,231,137,238,28,182,216,167,198,191,37,67,
76,1,144,232,218,79,72,28,65,101,43,216,64,253,16,173,179,123,140,27,233,245,199,230,36,181,102,114,247,162,18,34,20,212,25,171,24,28,143,80,94,40,167,34,209,61,117,130,1,198,196,7,21,252,180,255,92,128,119,9,48,156,138,136,151,143,23,44,52,3,40,197,228,31,123,67,163,140,32,54,204,187,149,80,19,255,82,120,195,12,110,65,56,212,143,22,78,44,234,72,140,29,118,103,18,36,7,122,50,37,139,47,142,243,25,208,88,237,126,50,103,127,19,183,29,169,29,1,55,23,100,32,129,239,243,160,61,178,197,117,199,45,57,26,
165,135,92,218,59,0,197,54,13,96,40,141,212,221,131,103,46,22,228,191,167,73,20,86,62,11,147,217,116,205,203,110,134,249,51,6,123,23,86,231,157,8,144,83,126,115,118,35,96,36,229,36,220,228,143,71,45,223,129,48,236,5,145,202,188,208,184,70,241,104,255,188,181,146,210,206,144,53,77,101,120,38,8,245,80,230,165,160,183,83,202,79,127,57,214,126,242,150,208,40,239,148,35,163,201,97,74,70,214,181,63,240,147,33,253,149,140,77,197,82,126,189,231,7,196,212,80,14,151,24,57,144,243,81,234,66,24,19,236,2,137,
121,246,129,65,7,99,110,174,54,74,182,81,234,142,37,72,110,220,255,64,119,10,188,111,191,228,1,205,9,204,143,56,62,125,84,106,225,131,97,192,43,240,157,161,75,168,247,44,175,65,81,192,48,21,157,167,80,191,130,161,75,85,186,174,42,117,1,68,252,204,138,254,203,152,21,13,64,144,195,207,238,229,54,103,247,159,245,211,85,191,141,168,32,234,85,46,118,12,5,199,4,19,217,203,202,156,33,143,114,116,60,66,40,58,77,208,237,171,26,72,175,114,205,248,87,137,62,210,143,151,197,167,210,241,122,150,104,122,154,2,
70,102,83,19,36,141,136,199,42,79,229,71,86,194,109,31,236,80,166,17,230,109,1,40,28,46,224,56,20,230,47,100,254,116,208,76,169,157,241,175,3,70,85,31,38,245,58,33,80,145,237,8,22,71,224,158,156,31,249,81,87,247,230,199,237,96,167,123,63,243,79,156,206,203,160,54,124,68,253,215,132,235,57,185,92,238,55,59,210,104,71,26,183,180,71,12,255,224,192,65,154,72,244,8,164,10,248,46,207,30,92,1,80,244,31,189,138,88,216,218,63,100,227,116,57,119,94,135,5,126,255,32,191,163,61,209,194,88,248,112,139,173,43,
69,134,3,160,151,137,25,98,239,166,19,123,208,180,31,120,30,191,75,183,179,126,180,125,92,107,105,206,138,28,67,139,3,188,230,184,255,121,13,181,45,160,114,202,194,123,87,55,124,97,164,82,95,232,216,117,62,5,90,176,82,167,52,160,153,174,168,105,146,91,248,81,79,249,97,138,133,170,245,229,132,61,5,149,224,246,194,213,61,12,109,44,136,235,95,219,133,220,27,93,36,93,124,180,81,141,152,220,170,163,229,197,124,171,232,48,70,251,106,119,150,20,16,49,119,247,42,132,36,76,254,124,177,66,175,9,1,39,92,127,
195,171,198,34,2,64,144,179,72,40,151,110,89,229,42,125,33,238,16,220,228,51,203,8,1,68,145,253,133,118,93,163,129,22,13,248,65,12,4,63,101,210,70,170,138,203,14,246,54,194,195,27,107,241,175,35,171,49,52,106,121,45,36,152,85,215,132,78,167,34,18,167,245,152,133,134,170,120,182,10,146,191,37,2,205,47,125,20,203,44,88,81,32,150,223,220,218,238,254,30,212,167,221,115,156,82,226,137,220,221,97,3,139,202,33,9,27,26,126,40,215,25,126,9,82,208,49,217,14,161,81,196,61,60,87,254,213,194,81,216,161,151,209,
166,222,230,24,128,117,140,92,4,203,254,170,253,249,88,90,112,226,18,44,122,39,158,158,56,69,204,159,5,179,51,197,233,139,216,102,226,206,248,15,78,112,214,126,67,28,40,38,98,190,178,206,67,94,245,254,160,101,176,32,157,26,132,83,252,228,87,242,32,127,160,112,210,224,133,149,115,41,30,16,200,69,89,81,77,144,12,106,182,73,54,28,53,195,28,216,179,179,136,35,141,102,234,177,240,34,186,106,145,245,3,84,48,251,157,245,11,217,111,227,138,42,67,114,211,177,37,103,16,71,152,72,117,123,36,213,202,56,124,227,
84,8,45,229,149,165,214,69,244,169,55,68,62,94,104,228,74,205,123,222,17,7,172,158,227,74,206,149,67,175,171,251,185,121,151,223,63,35,229,32,49,190,209,120,137,69,213,214,19,150,187,177,28,12,158,153,126,149,171,167,234,120,129,109,32,157,180,75,66,56,233,115,127,230,157,32,34,143,156,31,230,168,174,125,118,195,249,243,165,81,246,10,144,15,103,139,55,173,7,59,136,69,172,54,132,165,140,78,77,230,33,169,129,188,71,209,109,161,8,57,57,199,143,31,164,43,58,130,1,110,145,31,229,13,46,149,94,244,106,76,
238,105,107,1,183,177,10,61,225,94,185,116,58,183,95,225,22,119,19,248,28,13,123,125,108,158,64,184,77,245,153,162,217,227,208,41,185,211,235,41,153,181,54,166,165,11,154,55,21,184,209,192,249,44,164,160,29,229,159,82,156,198,241,183,114,83,137,186,151,148,31,21,197,216,145,32,13,50,22,241,137,39,71,28,142,160,215,107,221,45,202,104,227,110,186,12,150,145,240,51,49,44,196,115,224,238,149,189,134,99,67,241,62,157,240,114,247,195,26,200,141,97,147,249,23,150,174,10,13,219,81,73,58,242,96,250,243,15,
49,218,58,230,104,252,175,150,123,86,185,84,90,198,6,36,0,99,72,28,166,238,115,231,171,249,179,71,174,68,156,227,17,198,79,73,142,99,144,20,80,62,80,191,142,46,71,9,243,6,8,214,116,72,190,106,161,19,185,100,9,187,64,94,86,203,174,156,245,222,95,54,30,148,19,11,50,112,96,61,237,159,173,7,154,127,175,79,48,97,89,78,126,66,171,204,158,195,27,226,205,222,157,89,251,90,125,37,212,27,97,3,141,247,175,50,121,7,187,68,196,181,202,167,189,57,84,81,222,23,27,84,130,176,98,66,240,207,18,23,28,163,163,194,45,
37,129,202,170,97,189,0,81,238,0,39,199,163,35,211,206,247,65,29,116,242,67,102,235,13,136,232,230,114,146,187,7,254,142,26,121,16,237,5,160,201,114,94,178,199,95,212,241,45,112,180,188,72,86,114,189,155,149,149,163,210,112,101,12,69,225,75,202,223,28,242,90,215,156,169,224,245,135,128,92,148,217,131,208,255,25,135,117,136,5,104,185,249,161,228,214,16,105,204,9,182,135,153,220,101,244,160,207,58,182,118,185,240,57,245,123,13,112,182,106,229,220,90,29,86,215,96,147,232,2,55,131,225,137,68,245,89,141,
252,97,3,129,155,216,223,98,116,45,78,85,141,161,74,215,7,150,171,225,59,78,221,152,236,14,117,100,208,158,86,13,185,124,87,157,111,40,187,182,124,173,71,173,23,199,52,155,190,134,11,23,64,25,215,39,115,231,173,77,72,114,54,252,116,178,59,221,106,241,119,254,30,226,241,204,233,113,197,96,146,0,41,67,3,231,126,12,218,202,22,171,114,249,176,134,160,19,216,31,229,118,226,62,242,126,126,42,127,130,68,218,218,81,202,106,217,191,25,177,82,97,81,36,232,137,58,90,216,190,117,235,20,194,144,76,178,27,213,
13,208,18,29,118,126,49,98,203,179,128,237,100,32,242,189,212,6,210,210,188,161,205,13,124,119,13,215,112,41,183,176,215,168,210,182,111,1,115,2,239,141,8,177,124,112,48,197,2,239,11,99,4,36,77,69,47,244,19,153,61,19,2,96,176,7,112,122,131,169,25,189,116,171,49,12,121,162,79,154,74,251,50,233,182,63,180,224,118,49,253,21,20,16,31,144,184,93,174,231,244,183,13,49,225,189,211,73,185,49,110,142,25,226,45,176,233,204,74,33,16,205,88,131,92,157,170,175,68,170,61,53,116,165,16,27,182,160,181,87,241,15,
151,85,107,76,167,129,25,172,127,184,138,153,222,228,125,64,44,45,32,12,227,148,106,152,83,240,166,54,235,32,190,12,242,164,123,189,53,194,141,104,43,202,110,4,168,119,245,232,179,178,198,1,224,87,86,160,31,19,140,233,102,191,204,4,98,138,163,191,106,24,213,47,208,82,137,132,131,16,253,84,25,144,90,159,148,16,196,84,166,61,160,101,229,227,93,118,59,87,66,16,128,59,96,131,250,20,184,150,205,91,227,201,62,35,79,180,172,173,85,197,106,153,238,229,60,204,65,193,230,94,101,177,134,6,165,53,171,142,208,
155,2,11,4,202,127,54,17,142,117,227,121,128,204,192,147,147,92,189,5,224,148,72,18,83,101,126,124,228,153,242,123,229,247,92,221,6,73,227,250,87,167,194,129,187,73,38,185,109,217,240,193,88,50,178,180,151,54,197,187,137,190,166,233,1,103,204,88,31,127,185,29,65,1,29,254,223,14,83,167,215,114,248,30,173,89,173,187,69,5,105,117,15,106,94,173,63,227,25,230,190,136,168,177,175,107,91,126,254,34,188,25,118,48,12,226,130,153,162,57,47,181,212,79,160,97,64,157,246,90,53,43,149,76,102,15,195,107,58,242,
84,172,29,81,198,113,81,251,138,182,154,111,30,171,129,56,17,45,214,153,112,117,203,174,40,38,234,236,32,4,112,225,26,187,195,246,252,9,218,69,160,223,178,54,148,81,8,134,151,75,248,63,224,240,48,75,250,221,85,46,100,50,3,70,64,102,111,160,155,233,59,147,184,57,61,6,126,79,176,16,185,94,166,33,135,78,42,75,140,208,140,44,153,187,64,103,119,160,236,16,239,74,218,219,212,207,110,53,30,76,248,40,111,98,44,20,113,204,233,109,135,96,107,39,163,203,125,45,157,152,71,239,175,174,159,147,80,111,93,38,253,
228,154,225,181,101,12,241,127,65,49,189,5,85,151,237,213,143,14,104,138,54,52,27,4,132,67,35,156,86,157,73,16,229,222,245,110,79,165,179,56,179,53,218,229,100,58,87,149,48,231,64,63,115,67,3,172,6,186,115,154,60,53,214,152,149,89,234,37,143,82,255,64,28,183,93,112,39,70,185,57,0,199,9,61,175,219,41,76,37,176,82,125,65,53,160,214,105,62,153,244,222,96,205,6,178,85,41,240,113,0,96,149,38,3,195,18,152,41,246,3,103,29,110,134,30,101,75,46,103,199,184,20,230,8,55,120,4,229,168,35,43,7,28,161,143,87,27,
87,79,255,186,44,195,158,155,181,119,81,172,217,107,95,98,55,243,186,66,105,48,224,123,232,84,156,20,10,156,208,204,52,34,228,136,97,242,200,246,211,67,202,40,241,91,92,253,9,54,72,131,221,106,178,32,44,182,4,225,193,37,20,249,249,231,10,206,18,71,254,221,187,172,88,204,6,127,138,102,7,208,75,147,219,199,177,79,36,170,101,207,177,109,95,143,217,41,199,80,183,201,2,254,12,55,23,198,14,255,69,245,138,155,129,227,167,168,130,156,135,14,96,93,48,99,143,107,126,92,117,143,112,108,193,228,84,13,41,186,
27,172,92,201,149,116,19,112,197,116,209,128,102,1,55,152,177,28,37,34,50,83,41,199,74,178,59,111,67,118,35,252,36,33,87,28,170,17,215,47,90,154,124,137,15,14,211,59,75,59,30,77,0,49,37,225,191,87,101,127,214,227,160,99,174,234,82,148,235,16,241,219,147,170,127,221,250,116,39,218,156,72,227,172,55,0,79,188,76,51,222,232,24,36,62,94,154,3,61,230,146,114,253,0,128,58,253,90,72,211,242,38,39,133,153,161,119,105,195,152,225,208,105,140,80,217,186,196,157,21,116,230,116,139,25,159,143,118,128,77,201,238,
247,228,15,168,4,133,148,21,148,12,44,241,7,115,17,129,176,202,46,130,122,129,235,141,223,85,21,199,65,181,169,52,174,161,153,62,25,164,115,213,89,138,199,103,79,200,165,135,249,244,27,209,178,240,129,211,61,9,111,157,147,119,36,119,255,110,130,84,49,210,225,247,100,26,121,127,163,160,26,79,99,24,77,65,32,178,109,36,27,253,173,110,183,11,14,211,57,130,254,124,104,165,219,31,70,97,14,194,39,61,26,141,125,228,126,194,184,101,160,204,106,128,144,106,103,171,18,246,129,220,85,172,151,123,5,73,155,192,
175,91,157,239,61,237,116,170,65,233,56,19,49,114,168,190,3,214,53,250,90,213,244,88,101,30,229,248,124,15,71,141,27,172,235,21,129,211,72,61,172,112,170,128,135,96,196,221,255,27,176,105,188,183,121,33,37,149,53,131,226,233,29,167,234,218,109,53,185,152,36,248,53,61,235,78,21,201,214,210,163,12,251,187,45,188,137,126,127,237,92,234,91,240,225,38,194,57,213,251,237,171,30,99,52,14,49,84,101,252,237,7,166,122,114,32,107,32,207,239,136,168,178,12,11,241,233,230,146,132,18,83,233,41,172,17,6,161,42,
113,87,40,255,185,1,146,128,5,240,126,131,71,42,54,124,205,2,122,71,30,222,229,40,134,142,102,97,239,151,177,1,230,231,49,123,219,28,129,91,152,112,13,154,81,197,226,255,112,158,178,177,55,181,108,138,185,245,29,186,21,73,188,209,154,200,89,116,235,198,144,36,87,248,22,7,200,122,7,148,44,42,87,140,238,204,95,231,252,0,136,0,22,39,70,123,125,165,113,227,172,146,163,128,158,36,52,91,19,36,245,27,150,138,141,11,67,239,224,65,24,116,101,7,39,46,142,172,164,243,148,0,33,226,59,47,203,137,156,241,66,250,
157,30,204,101,143,134,98,238,155,226,25,184,136,219,89,100,193,11,143,71,139,243,230,151,0,249,1,78,26,32,93,104,157,67,97,164,248,86,124,146,93,74,222,228,167,55,53,100,135,216,109,13,64,37,106,177,200,200,182,92,251,69,31,243,89,80,198,14,132,203,72,103,28,104,217,24,97,223,113,11,29,178,191,210,46,162,255,68,99,8,237,213,162,152,193,183,121,203,19,108,182,29,86,26,192,103,220,103,205,154,179,197,9,22,73,127,175,146,38,119,210,0,24,180,21,245,215,204,91,186,119,138,183,239,15,155,231,248,133,39,
24,101,144,236,10,230,54,174,227,73,21,110,10,160,241,232,131,14,212,127,232,59,122,65,146,54,163,9,189,190,121,88,170,62,194,14,204,152,245,38,131,37,91,81,72,114,29,115,239,182,56,44,156,159,177,180,82,160,93,97,86,183,236,50,95,85,39,71,181,225,152,143,63,123,117,34,44,109,160,166,229,240,91,138,102,54,180,173,44,50,80,42,124,7,50,124,211,239,21,94,197,185,239,213,107,142,64,95,124,125,17,180,97,189,101,52,48,19,112,12,70,9,212,177,54,118,66,84,147,236,248,26,124,95,103,135,254,124,49,112,186,
99,120,90,8,194,191,88,57,242,65,61,10,104,246,197,252,19,159,58,194,75,173,242,103,8,115,84,69,238,149,26,15,159,182,141,132,119,70,29,53,20,143,46,163,204,6,236,59,45,185,172,89,119,83,38,144,36,222,96,151,26,99,195,163,170,133,92,159,214,53,150,116,90,176,69,145,130,15,172,140,217,215,101,163,115,161,65,101,8,7,183,113,213,134,58,175,130,251,143,173,248,168,135,60,159,30,194,68,208,119,120,2,40,178,227,247,161,77,47,136,46,244,163,72,65,158,25,225,195,61,132,182,204,177,186,200,81,2,65,105,212,
72,94,203,232,217,182,123,251,228,160,1,161,204,123,20,37,1,77,208,179,45,149,181,122,102,190,123,213,164,231,41,216,130,234,248,208,251,252,220,84,209,67,47,61,220,5,142,162,26,236,121,142,248,132,255,65,122,203,196,102,191,187,2,195,127,255,193,92,49,91,186,154,39,156,29,211,172,49,104,245,114,153,223,211,199,249,35,130,160,128,0,152,176,183,20,236,113,193,108,26,255,11,237,102,133,245,94,115,114,10,89,229,214,221,99,149,30,99,37,246,10,26,26,39,92,123,170,73,211,127,227,54,30,86,133,159,112,225,
91,148,100,174,149,75,143,14,140,20,44,64,212,5,243,8,116,63,30,97,42,123,20,73,212,85,207,83,122,27,251,233,84,10,17,236,232,83,200,127,119,143,163,204,220,167,59,231,20,106,186,222,191,8,40,234,21,25,180,13,116,250,152,224,174,75,3,205,38,173,215,236,151,185,121,254,244,154,239,17,53,106,164,61,49,116,216,118,94,150,35,181,26,238,66,49,211,221,132,146,166,115,39,136,36,205,230,179,31,197,51,148,165,109,38,70,37,148,52,44,209,250,98,58,246,225,103,198,101,26,25,196,207,8,166,21,88,252,175,253,10,
88,107,157,19,225,61,12,246,221,37,239,186,167,137,142,135,222,128,174,62,95,216,38,141,157,45,232,97,217,173,203,234,116,129,69,206,189,94,221,12,54,139,186,247,184,16,200,121,244,104,8,7,35,111,47,188,10,140,92,73,143,206,203,72,122,184,20,102,197,130,64,150,63,96,239,8,132,111,217,84,91,198,32,43,100,138,241,15,160,42,190,253,193,184,164,124,29,210,96,67,224,221,182,29,218,129,149,29,128,174,98,88,88,125,56,40,255,120,5,0,87,174,42,150,90,112,201,183,169,19,57,195,191,12,58,244,235,132,25,145,
72,146,214,8,125,100,135,12,5,102,97,248,174,24,159,90,33,43,187,6,61,212,241,225,190,219,252,197,123,129,164,108,123,55,230,4,153,166,105,234,15,85,216,23,56,32,3,41,110,68,146,172,133,202,98,41,7,47,152,35,255,168,106,241,226,222,77,244,52,185,65,252,227,32,66,38,11,172,60,28,28,103,84,1,1,205,182,190,28,189,102,253,43,1,191,148,116,10,227,18,81,93,80,239,157,232,215,180,163,165,161,109,177,71,150,244,144,208,160,110,22,174,60,206,43,103,121,55,103,114,115,173,238,13,10,227,251,41,176,216,158,229,
216,55,234,128,128,20,167,106,181,86,163,130,215,110,149,191,10,227,215,8,214,154,178,181,15,19,0,247,250,97,74,43,157,55,94,174,41,41,9,199,97,20,91,32,18,10,43,98,240,247,203,20,250,117,160,44,229,202,187,64,54,124,15,184,169,129,27,160,240,26,61,255,60,166,60,144,209,84,55,187,186,168,13,124,125,29,17,100,249,227,62,205,78,179,163,168,139,168,21,38,83,239,151,74,43,66,2,92,72,71,94,216,134,238,20,45,158,213,164,73,57,80,47,198,184,130,223,227,71,132,133,235,177,85,174,142,124,172,200,54,229,40,
126,60,76,92,216,153,56,241,174,66,141,90,226,3,30,68,234,71,187,163,112,146,255,22,143,170,204,3,127,179,81,139,160,37,77,246,128,220,196,158,153,73,177,65,199,119,29,197,144,130,248,206,155,253,108,213,124,7,223,221,162,146,134,242,65,99,162,107,120,247,214,207,96,150,169,131,208,218,221,28,24,112,208,23,1,130,142,232,56,104,45,33,158,95,255,123,31,74,76,120,178,155,213,6,195,164,8,8,69,241,197,127,83,169,21,167,19,94,143,252,33,159,248,241,170,153,147,1,149,199,201,131,170,79,236,212,209,143,107,
98,24,123,56,33,193,85,247,64,225,135,210,78,145,57,16,145,71,170,20,133,87,235,4,166,239,100,82,235,81,50,223,9,193,52,49,86,129,190,196,82,165,107,63,115,161,98,33,20,193,29,42,151,205,252,124,72,245,48,181,67,7,13,21,127,59,226,188,144,129,112,244,192,121,213,80,42,196,1,13,107,108,78,0,40,121,225,148,237,234,209,216,238,9,147,226,254,96,89,212,72,193,106,75,135,74,227,67,255,92,191,81,188,124,226,149,152,142,15,159,195,238,114,55,255,166,157,230,59,148,170,166,151,65,213,104,253,253,112,150,82,
147,137,27,214,100,247,65,81,92,47,86,217,7,45,120,81,130,31,236,243,76,78,3,45,105,172,220,71,48,220,94,196,249,163,193,133,50,236,205,20,55,2,63,14,127,69,113,212,204,12,58,79,89,86,29,61,199,201,64,149,6,144,182,150,129,31,18,167,120,248,82,107,25,143,128,27,161,28,25,153,183,217,238,78,186,106,92,27,202,219,165,96,0,216,234,169,73,101,39,182,113,217,240,170,116,172,221,250,233,48,49,242,83,227,92,181,184,72,230,180,21,15,108,135,25,38,153,25,124,227,26,149,73,236,39,211,244,149,58,183,132,26,
223,219,174,144,117,233,219,165,205,157,159,222,184,52,47,241,201,123,65,24,44,55,215,177,168,250,179,115,190,227,123,158,163,179,224,69,196,66,207,254,243,101,221,193,140,250,4,28,222,52,96,138,160,33,218,64,118,214,234,201,152,148,91,178,111,107,144,142,6,182,102,72,188,34,213,181,26,223,58,255,103,81,17,47,169,11,245,224,123,148,215,237,186,107,75,152,90,202,166,22,149,197,5,246,238,78,76,229,106,199,94,127,195,0,45,82,6,159,103,96,138,231,71,46,107,59,216,39,43,12,221,27,214,56,155,145,66,187,
169,250,235,78,211,179,239,183,198,163,93,5,196,24,174,143,225,106,139,89,98,13,127,207,184,194,30,1,165,198,169,8,197,118,86,163,221,138,23,209,61,116,79,99,233,43,130,60,244,85,229,243,172,123,148,200,120,192,127,211,52,11,159,41,95,212,230,188,169,156,137,29,212,12,148,168,148,133,243,44,241,139,127,24,246,220,227,125,209,97,60,52,162,192,146,49,161,92,138,112,189,128,59,126,125,46,207,60,79,231,174,152,209,68,223,205,2,38,14,91,116,159,255,28,27,178,248,164,104,158,79,69,214,234,157,12,75,163,
83,253,245,202,61,213,176,6,197,230,29,208,166,253,194,254,235,29,141,241,70,249,15,62,0,148,163,135,52,122,40,96,87,31,179,152,51,216,133,184,122,198,203,60,115,218,191,193,16,178,25,148,252,112,104,103,252,36,92,221,28,179,43,199,198,151,128,100,252,217,161,249,34,201,172,118,52,180,252,104,7,223,44,116,102,212,21,40,224,184,55,163,210,21,207,161,239,51,54,155,41,133,18,67,48,3,165,130,251,4,79,214,57,72,130,157,212,144],ps=[0,1,3,4,6,7,9,10,12,13,15,16,18,19,21,22,24,26,29,31,34,36,39,41,44,46,
49,51,54,56,59,61,64,65,66,67,68,69,70,72,73,74,75,76,77,79,80,81,82,83,84,85,87,88,89,90,91,92,94,95,96,97,98,99,101,102,103,104,105,106,107,109,110,111,112,113,114,116,117,118,119,120,121,123,124,125,126,127,128,129,131,132,133,134,135,136,138,139,140,141,142,143,145,146,147,148,149,150,151,153,154,155,156,157,158,160,161,162,163,164,165,166,168,169,170,171,172,173,175,176,177,178,179,180,182,183,184,185,186,187,188,190,191,192,193,194,195,197,198,199,200,201,202,204,205,206,207,208,209,210,212,
213,214,215,216,217,219,220,221,222,223,224,226,226,226,227,227,227,228,228,228,229,229,229,230,230,231,231,231,232,232,232,233,233,233,234,234,235,235,235,236,236,236,237,237,237,238,238,239,239,239,240,240,240,241,241,241,242,242,243,243,243,244,244,244,245,245,245,246,246,246,247,247,247,248,248,248,249,249,249,250,250,250,251,251,251,252,252,252,253,253,253,254,254,254,255],Ln=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,33,35,36,37,39,40,42,43,44,46,
47,49,50,51,53,54,56,57,58,59,61,62,63,64,66,67,68,69,71,72,73,74,76,77,78,79,81,82,83,84,86,87,88,90,91,92,93,95,96,97,98,100,101,102,103,105,106,107,108,110,111,112,113,115,116,117,118,120,121,122,124,125,126,127,129,130,131,132,134,135,136,137,139,140,141,142,144,145,146,147,149,150,151,152,154,155,156,158,159,160,161,163,164,165,166,168,169,170,171,173,174,175,176,178,179,180,181,183,184,185,186,188,189,190,192,193,194,195,197,198,199,200,202,203,204,205,207,208,209,210,212,213,214,215,217,218,
219,220,222,223,224,226,226,226,227,227,228,228,229,229,230,230,231,231,232,232,233,233,234,234,234,235,235,236,236,237,237,238,238,239,239,240,240,241,241,242,242,243,243,243,244,244,244,245,245,245,246,246,246,247,247,247,248,248,248,249,249,249,250,250,250,251,251,251,252,252,252,253,253,253,254,254,254,255],qs=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,43,44,45,46,47,48,50,51,52,53,54,55,56,58,59,60,61,62,63,65,66,67,68,69,70,72,
73,74,76,77,78,80,81,83,84,85,87,88,89,91,92,94,95,96,98,99,100,102,103,105,106,107,109,110,111,113,114,116,117,118,120,121,122,124,125,127,128,129,131,132,133,135,136,138,139,140,142,143,144,146,147,149,150,151,153,154,155,157,158,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,192,193,193,194,195,195,196,197,197,198,199,199,200,201,201,202,203,203,204,205,205,206,207,207,208,209,209,210,211,211,212,213,213,214,215,
215,216,217,217,218,219,219,220,221,221,222,223,223,224,225,225,226,227,227,228,229,229,230,231,231,232,233,233,234,235,235,236,237,237,238,239,239,240,241,241,242,243,243,244,245,245,246,247,247,248,249,249,250,251,251,252,253,253,254,255];class rs extends vc{constructor(a,b,c,e){super(a,os,c,e);this.lightLevel=.1;this.rednessLevel=.5;this.mskin_he_max=175/180*3.141593;this.mskin_he_min=115/180*3.141593;this.mskin_hc_max=173/180*3.141593;this.mskin_hc_min=116/180*3.141593;this.mskin_hc_axis=2.04203545;
this.mfacts_rotate_ge=this.mfacts_rotate_le=this.mfacts_rotate_c=0;this.tab_addr=null;this.lutTextures=[];this.inputTexture=b;this.init()}setUniforms(){var a=this.gl.getUniformLocation(this.program,"u_flipY"),b=this.gl.getUniformLocation(this.program,"u_denoiseLevel");this.gl.uniform1f(b,this.denoiseLevel);this.gl.uniform1f(a,1);a=this.gl.getUniformLocation(this.program,"light");this.gl.uniform1f(a,this.lightLevel);a=this.gl.getUniformLocation(this.program,"redness");this.gl.uniform1f(a,this.rednessLevel);
a=this.gl.getUniformLocation(this.program,"skin_he_max");b=this.gl.getUniformLocation(this.program,"skin_he_min");var c=this.gl.getUniformLocation(this.program,"skin_hc_max"),e=this.gl.getUniformLocation(this.program,"skin_hc_min");let f=this.gl.getUniformLocation(this.program,"skin_hc_axis"),h=this.gl.getUniformLocation(this.program,"facts_rotate_c"),k=this.gl.getUniformLocation(this.program,"facts_rotate_le"),r=this.gl.getUniformLocation(this.program,"facts_rotate_ge");this.gl.uniform1f(a,this.mskin_he_max);
this.gl.uniform1f(b,this.mskin_he_min);this.gl.uniform1f(c,this.mskin_hc_max);this.gl.uniform1f(e,this.mskin_hc_min);this.gl.uniform1f(f,this.mskin_hc_axis);this.gl.uniform1f(h,this.mfacts_rotate_c);this.gl.uniform1f(k,this.mfacts_rotate_le);this.gl.uniform1f(r,this.mfacts_rotate_ge);a=this.gl.getUniformLocation(this.program,"u_originImage");this.gl.activeTexture(this.gl.TEXTURE2);this.gl.bindTexture(this.gl.TEXTURE_2D,this.inputTexture);this.gl.uniform1i(a,2);a=["lighten_lut"];b=[this.gl.TEXTURE3];
for(c=0;c<a.length;c++)e=this.gl.getUniformLocation(this.program,a[c]),this.gl.activeTexture(b[c]),this.gl.bindTexture(this.gl.TEXTURE_2D,this.lutTextures[c]),this.gl.uniform1i(e,c+3)}setParameters(a){void 0!==a.denoiseLevel&&(this.denoiseLevel=a.denoiseLevel);void 0!==a.lightLevel&&(this.lightLevel=a.lightLevel);void 0!==a.rednessLevel&&(this.rednessLevel=a.rednessLevel,this.updateRedness(this.rednessLevel));a.lighteningContrastLevel&&this.updateLut(a.lighteningContrastLevel)}init(){this.tab_addr=
new Uint8Array(Ln);let a=[this.tab_addr],b=[256],c=[1];for(let e=0;e<a.length;e++){let f=this.gl.createTexture();if(!f)throw new q(n.WEBGL_INTERNAL_ERROR,"create lut texture failed");this.gl.bindTexture(this.gl.TEXTURE_2D,f);this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.LUMINANCE,b[e],c[e],0,this.gl.LUMINANCE,this.gl.UNSIGNED_BYTE,a[e]);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR);this.lutTextures.push(f)}}updateRedness(a){var b=a;1<a&&(a=1);0>a&&(a=0);1<b&&(b=1);0>b&&(b=0);this.mfacts_rotate_c=.8*a;.8>b&&(b=0);this.mskin_he_max=175/180*3.141593;this.mskin_hc_max=173/180*3.141593;this.mskin_he_min=(115-4*b)/180*3.141593;this.mskin_hc_min=(116-4*b)/180*3.141593;this.mskin_hc_axis=(117-4*b)/180*3.141593;this.mskin_hc_axis<
this.mskin_hc_min&&(this.mskin_hc_axis=this.mskin_hc_min);1.5707965>this.mskin_hc_min&&(this.mskin_hc_min=1.5707965);1.5707965>this.mskin_hc_axis&&(this.mskin_hc_axis=1.5707965);1.5707965>this.mskin_he_min&&(this.mskin_he_min=1.5707965);3.141593<this.mskin_hc_max&&(this.mskin_hc_max=3.141593);3.141593<this.mskin_hc_axis&&(this.mskin_hc_axis=3.141593);3.141593<this.mskin_he_max&&(this.mskin_he_max=3.141593);a=this.mskin_he_max-this.mskin_hc_max;b=this.mskin_hc_max-this.mskin_hc_axis;this.mfacts_rotate_ge=
.01<a?this.mfacts_rotate_c*b/a:this.mfacts_rotate_c;a=this.mskin_hc_min-this.mskin_he_min;b=this.mskin_hc_axis-this.mskin_hc_min;this.mfacts_rotate_le=.01<a?this.mfacts_rotate_c*b/a:this.mfacts_rotate_c}updateLut(a){var b=null;if(0===a&&(b=Ln),1===a&&(b=qs),2===a&&(b=ps),!b)throw new q(n.WEBGL_INTERNAL_ERROR,"invalid ylut_table value:"+a);this.tab_addr=new Uint8Array(b);a=[this.tab_addr];b=[256];let c=[1];for(let e=0;e<a.length;e++)this.gl.bindTexture(this.gl.TEXTURE_2D,this.lutTextures[e]),this.gl.texImage2D(this.gl.TEXTURE_2D,
0,this.gl.LUMINANCE,b[e],c[e],0,this.gl.LUMINANCE,this.gl.UNSIGNED_BYTE,a[e])}}class ss{constructor(){this.canvas=this.gl=null;this.programs=[];this.inputTexture=this.commonProgram=null;this.outputTextures=[];this.fbos=[];this.originalFrameHeight=this.originalFrameWidth=0;this.enableBeauty=!1;this.denoiseLevel=5;this.lightLevel=.35;this.rednessLevel=.5;this.lighteningContrastLevel=1}setEnableBeauty(a){this.enableBeauty=!!a}init(a,b,c){if(!la.supportWebGL)throw new q(n.NOT_SUPPORTED,"your browser is not support webGL");
if(this.gl=c.getContext("webgl"),!this.gl)throw new q(n.WEBGL_INTERNAL_ERROR,"can not get webgl context");if(this.initGL(a,b),!this.inputTexture)throw new q(n.WEBGL_INTERNAL_ERROR,"can not find input texture");this.canvas=c;this.programs.push(new Kn(this.gl));this.programs.push(new js(this.gl,a,b));this.programs.push(new ls(this.gl,a,b));this.programs.push(new ns(this.gl,a,b));this.programs.push(new rs(this.gl,this.inputTexture,a,b));this.commonProgram=this.programs[0].program;this.setDenoiseLevel(this.denoiseLevel);
this.setLightLevel(this.lightLevel);this.setRednessLevel(this.rednessLevel);this.setContrastLevel(this.lighteningContrastLevel)}render(a){if(!this.gl||!this.commonProgram||!this.canvas)return void k.warning("video effect manager is not init!");var b=0;if(this.originalFrameHeight===a.videoWidth&&this.originalFrameWidth===a.videoHeight)b=2;else if(this.originalFrameHeight!==a.videoHeight||this.originalFrameWidth!==a.videoWidth){var c,e,f;if(k.debug(m(c=m(e=m(f="beauty effect: resolution changed ".concat(this.originalFrameWidth,
"x")).call(f,this.originalFrameHeight," -> ")).call(e,a.videoWidth,"x")).call(c,a.videoHeight)),0===a.videoHeight||0===a.videoWidth)return void k.debug("beauty effect: skip 0 resolution frame");this.canvas.width=a.videoWidth;this.canvas.height=a.videoHeight;a.setAttribute("width",a.videoWidth.toString());a.setAttribute("height",a.videoHeight.toString());this.release();this.init(a.videoWidth,a.videoHeight,this.canvas)}this.gl.viewport(0,0,a.videoWidth,a.videoHeight);this.gl.bindTexture(this.gl.TEXTURE_2D,
this.inputTexture);this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,a);a=this.enableBeauty?this.programs.length-1:0;for(c=0;c<=a;c++)e=this.programs[c].program,this.gl.useProgram(e),e=this.gl.getUniformLocation(e,"u_image"),this.programs[c].setUniforms(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this.fbos[b+c%2]),this.gl.clearColor(0,0,0,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.drawArrays(this.gl.TRIANGLES,0,6),this.gl.activeTexture(this.gl.TEXTURE0),
this.gl.bindTexture(this.gl.TEXTURE_2D,this.outputTextures[b+c%2]),this.gl.uniform1i(e,0);this.gl.useProgram(this.commonProgram);b=this.gl.getUniformLocation(this.commonProgram,"u_flipY");this.gl.uniform1f(b,-1);this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null);this.gl.clearColor(0,0,0,1);this.gl.clear(this.gl.COLOR_BUFFER_BIT);this.gl.drawArrays(this.gl.TRIANGLES,0,6)}setDenoiseLevel(a){var b;t(b=this.programs).call(b,b=>{b instanceof vc&&b.setParameters({denoiseLevel:a})});this.denoiseLevel=a}setLightLevel(a){var b;
t(b=this.programs).call(b,b=>{b instanceof vc&&b.setParameters({lightLevel:a})});this.lightLevel=a}setRednessLevel(a){var b;t(b=this.programs).call(b,b=>{b instanceof vc&&b.setParameters({rednessLevel:a})});this.rednessLevel=a}setContrastLevel(a){var b;t(b=this.programs).call(b,b=>{b instanceof vc&&b.setParameters({lighteningContrastLevel:a})});this.lighteningContrastLevel=a}setSize(a,b){var c;t(c=this.programs).call(c,c=>{c instanceof vc&&c.setSize(a,b)})}release(){this.inputTexture=this.commonProgram=
this.gl=null;this.programs=[];this.outputTextures=[];this.fbos=[]}initGL(a,b){if(!this.gl)throw new q(n.WEBGL_INTERNAL_ERROR,"can not find webgl context");this.inputTexture=this.gl.createTexture();this.gl.bindTexture(this.gl.TEXTURE_2D,this.inputTexture);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR);
this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR);for(let c=0;4>c;c++){let e=this.gl.createTexture();if(!e)throw new q(n.WEBGL_INTERNAL_ERROR,"create texture failed");this.gl.bindTexture(this.gl.TEXTURE_2D,e);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE);this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR);
2>c?this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,a,b,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null):this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,b,a,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null);let f=this.gl.createFramebuffer();if(!f)throw new q(n.WEBGL_INTERNAL_ERROR,"create frame buffer failed");this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,f);this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,e,0);this.outputTextures.push(e);this.fbos.push(f)}this.gl.viewport(0,
0,a,b);this.originalFrameWidth=a;this.originalFrameHeight=b}}class ts{constructor(){this.recordedFrameCount=this.targetFrameRate=0;this.recordingTime=2}async startRecordBeautyEffectOutput(a,b=4){if(this.recordID)throw new q(n.UNEXPECTED_ERROR,"another beauty effect recording is in progress");let c=va(6,"");return this.recordID=c,this.targetFrameRate=a,this.recordedFrameCount=0,this.recordingTime=b,await jb(1E3*this.recordingTime),this.recordID!==c?(this.recordID=void 0,!0):(this.recordID=void 0,this.recordedFrameCount<
this.targetFrameRate*this.recordingTime/2?(k.warning("detect beauty effect overload, current framerate",this.recordedFrameCount/2),!1):(k.debug("beauty effect current framerate",this.recordedFrameCount/2),!0))}stopRecordBeautyEffectOutput(){this.recordedFrameCount=this.targetFrameRate=0;this.recordID=void 0}addFrame(){this.recordID&&(this.recordedFrameCount+=1)}}class us extends class{get output(){return this._output}async setInput(a){if(a!==this.input){if(a.kind!==this.kind)throw new q(n.UNEXPECTED_ERROR);
this.input&&this.removeInput();this.input=a;await this._setInput(a)}}removeInput(){this.input=void 0;this._removeInput()}async updateOutput(a){this.output!==a&&(this._output=a,this.onOutputChange&&await this.onOutputChange())}replaceOriginMediaStream(a,b){var c,e;let f=U(c=a.getTracks()).call(c,a=>a.kind===this.kind);f&&a.removeTrack(f);b=U(e=b.getTracks()).call(e,a=>a.kind===this.kind);void 0===this.output&&b&&a.addTrack(b);this.output&&(k.debug("replace ".concat(this.output.kind," track to origin media stream")),
a.addTrack(this.output))}}{constructor(){super();this.kind="video";this.fps=15;this.overloadDetector=new ts;this.enabled=!1;this.stopChromeBackgroundLoop=null;this.lastRenderTime=0;this.fps=30;this.manager=new ss}async setBeautyEffectOptions(a,b){void 0!==b.smoothnessLevel&&ha(b.smoothnessLevel,"options.smoothnessLevel",0,1,!1);void 0!==b.lighteningLevel&&ha(b.lighteningLevel,"options.lighteningLevel",0,1,!1);void 0!==b.rednessLevel&&ha(b.rednessLevel,"options.rednessLevel",0,1,!1);void 0!==b.lighteningContrastLevel&&
fb(b.lighteningContrastLevel,"options.lighteningContrastLevel",[0,1,2]);void 0!==b.smoothnessLevel&&this.manager.setDenoiseLevel(Math.max(.1,10*b.smoothnessLevel));void 0!==b.lighteningLevel&&this.manager.setLightLevel(Math.max(.1,b.lighteningLevel/2));void 0!==b.rednessLevel&&this.manager.setRednessLevel(Math.max(.01,b.rednessLevel));void 0!==b.lighteningContrastLevel&&this.manager.setContrastLevel(b.lighteningContrastLevel);this.enabled!==a&&(this.manager.setEnableBeauty(a),this.enabled=a,a?this.input&&
await this.startEffect():await this.stopEffect())}destroy(){this.onOutputChange=void 0;this.stopEffect();this.enabled=!1}async startEffect(){let a=V();if(!this.input)return void k.warning("video track is null, fail to start video effect!");if(this.input&&this.output&&this.input!==this.output)return void k.warning("video effect is already enabled");let b=await this.renderWithWebGL();await this.updateOutput(b);k.info("start video effect, output:",this.output);this.overloadDetector.startRecordBeautyEffectOutput(this.fps).then(a=>
{a||this.onOverload&&this.onOverload()});let c=()=>{this.enabled&&requestAnimationFrame(c);const a=x(),b=1E3/this.fps,h=this.lastRenderTime?a-this.lastRenderTime:b;h<b||(this.lastRenderTime=a-(h-b),this.video&&this.video.paused&&this.video.play(),this.enabled&&this.video&&(this.manager.render(this.video),this.output&&this.output.requestFrame&&this.output.requestFrame(),this.overloadDetector.addFrame()))};requestAnimationFrame(c);a.name===S.CHROME&&document.addEventListener("visibilitychange",()=>
{document.hidden?this.stopChromeBackgroundLoop=dg(()=>{this.enabled&&this.video&&this.manager.render(this.video);this.output&&this.output.requestFrame&&this.output.requestFrame();this.overloadDetector.addFrame()},this.fps):this.stopChromeBackgroundLoop&&(this.stopChromeBackgroundLoop(),this.stopChromeBackgroundLoop=null)},!1)}async stopEffect(){k.info("stop video effect");this.overloadDetector.stopRecordBeautyEffectOutput();this.manager.release();this.canvas&&this.canvas.remove();this.video&&this.video.remove();
this.video=this.canvas=void 0;await this.updateOutput(this.input)}async _setInput(a){this.enabled&&!this.video&&await this.startEffect()}_removeInput(){this.stopEffect()}async renderWithWebGL(){var a;if(!this.input)throw new q(n.BEAUTY_PROCESSOR_INTERNAL_ERROR,"can not renderWithWebGL, no input");this.canvas&&(this.canvas.remove(),this.canvas=void 0);this.video&&(this.video.remove(),this.video=void 0);this.canvas=document.createElement("canvas");this.video=document.createElement("video");this.video.setAttribute("autoplay",
"");this.video.setAttribute("muted","");this.video.muted=!0;this.video.setAttribute("playsinline","");this.video.setAttribute("style","display:none");this.video.srcObject=new MediaStream([this.input]);var b=new y(a=>{const b=()=>{this.video&&this.video.removeEventListener("playing",b);a(void 0)};this.video&&this.video.addEventListener("playing",b)});this.video.play();await b;b=this.input.getSettings();let c=b.width||this.video.videoWidth,e=b.height||this.video.videoHeight;if(b.frameRate&&this.fps!==
b.frameRate&&(this.fps=b.frameRate,k.debug("beauty video processor: set fps to",this.fps)),k.debug(m(a="beauty video processor: width ".concat(c," height ")).call(a,e)),!c||!e)throw new q(n.BEAUTY_PROCESSOR_INTERNAL_ERROR,"can not get track resolution");this.canvas.width=c;this.canvas.height=e;this.video.setAttribute("width",c.toString());this.video.setAttribute("height",e.toString());this.manager.init(c,e,this.canvas);return this.canvas.captureStream(la.supportRequestFrame?0:this.fps).getVideoTracks()[0]}}
var Db=function(a,b,c,e){var f,h=arguments.length,k=3>h?b:null===e?e=ca(b,c):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)k=Reflect.decorate(a,b,c,e);else for(var r=a.length-1;0<=r;r--)(f=a[r])&&(k=(3>h?f(k):3<h?f(b,c,k):f(b,c))||k);return 3<h&&k&&Q(b,c,k),k},aa=function(a,b){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(a,b)};class ta extends yf{constructor(a,b,c,e,f){super(a,f);this.trackMediaType="video";this._scalabiltyMode={numSpatialLayers:1,
numTemporalLayers:1};this._enabled=!0;this.updateMediaStreamTrackResolution();this._encoderConfig=b;this._scalabiltyMode=c;this._optimizationMode=e}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Qa.PLAYING)}play(a,b={}){let c=u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_VIDEO_TRACK_PLAY,options:[this.getTrackId(),"string"==typeof a?a:"HTMLElement",b]});if(!(a instanceof HTMLElement)){let b=document.getElementById(a.toString());var e;b?a=b:(k.warning(m(e="[".concat(this.getTrackId(),
'] can not find "#')).call(e,a,'" element, use document.body')),a=document.body)}k.debug("[".concat(this.getTrackId(),"] start video playback"),A(b));a=Wd({},this._getDefaultPlayerConfig(),{},b,{trackId:this.getTrackId(),element:a});this._player?this._player.updateConfig(a):(this._player=new In(a),this._player.updateVideoTrack(this._mediaStreamTrack));this._player.play();c.onSuccess()}stop(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_VIDEO_TRACK_STOP,options:[this.getTrackId()]});if(!this._player)return a.onSuccess();
this._player.destroy();this._player=void 0;k.debug("[".concat(this.getTrackId(),"] stop video playback"));a.onSuccess()}async setEnabled(a,b){if(!b){if(a===this._enabled)return;this.stateCheck("enabled",a)}k.info("[".concat(this.getTrackId(),"] start setEnabled"),a);let c=await this._enabledMutex.lock();if(!a){this._originMediaStreamTrack.enabled=!1;try{await Za(this,G.NEED_REMOVE_TRACK,this)}catch(e){throw k.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),c(),e;}return b||
(this._enabled=!1),k.info("[".concat(this.getTrackId(),"] setEnabled to false success")),c()}this._originMediaStreamTrack.enabled=!0;try{await Za(this,G.NEED_ADD_TRACK,this)}catch(e){throw k.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),c(),e;}k.info("[".concat(this.getTrackId(),"] setEnabled to true success"));b||(this._enabled=!0);c()}async setMuted(a){var b;if(a!==this._muted){if(this.stateCheck("muted",a),this._muted=a,V().name===S.FIREFOX)return k.debug("[".concat(this.getTrackId(),
"] firefox set mute fallback to set enabled")),void await this.setEnabled(!a,!0);this._mediaStreamTrack.enabled=!a;k.debug(m(b="[".concat(this.getTrackId(),"] start set muted: ")).call(b,a));await Za(this,G.SET_VIDEO_TRACK_MUTED,{track:this,muted:a})}}getStats(){Qd(()=>{k.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning");return Hc(this,G.GET_STATS)||Wd({},wf)}async setBeautyEffect(a,b={}){let c=
u.reportApiInvoke(null,{tag:C.TRACER,name:D.LOCAL_VIDEO_TRACK_BEAUTY,options:[this.getTrackId(),a,b]});if(a||this._videoBeautyProcessor){if(V().os===Na.IOS||V().os===Na.ANDROID)throw a=new q(n.INVALID_OPERATION,"can not enable beauty effect on mobile device"),c.onError(a),a;if(!this._enabled&&a)throw a=new q(n.TRACK_IS_DISABLED,"can not enable beauty effect when track is disabled"),c.onError(a),a;k.info("[".concat(this.getTrackId(),"] start setBeautyEffect"),a,A(b));try{this._videoBeautyProcessor?
await this._videoBeautyProcessor.setBeautyEffectOptions(a,b):(this._videoBeautyProcessor=new us,this._videoBeautyProcessor.onOverload=()=>{xb(()=>this.emit(Tc.BEAUTY_EFFECT_OVERLOAD))},await this._videoBeautyProcessor.setBeautyEffectOptions(a,b),await this._registerTrackProcessor(this._videoBeautyProcessor))}catch(e){throw k.error("[".concat(this.getTrackId(),"] setBeautyEffect error"),e.toString()),c.onError(e),e;}k.info("[".concat(this.getTrackId(),"] setBeautyEffect success"));c.onSuccess()}}getCurrentFrameData(){return this._player?
this._player.getCurrentFrame():new ImageData(2,2)}clone(a,b,c,e){let f=this._mediaStreamTrack.clone();return new ta(f,a,b,c,e)}async setBitrateLimit(a){var b;if(k.debug(m(b="[".concat(this.getTrackId(),"] set bitrate limit, ")).call(b,A(a))),a){this._forceBitrateLimit=a;this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<a.max_bitrate?this._encoderConfig.bitrateMax:a.max_bitrate:this._encoderConfig.bitrateMax=a.max_bitrate,this._encoderConfig.bitrateMin,
this._encoderConfig.bitrateMin=a.min_bitrate);try{await Za(this,G.NEED_RESET_REMOTE_SDP)}catch(c){return c.throw()}}}async setOptimizationMode(a){var b;if("motion"===a||"detail"===a||"balanced"===a){try{this._optimizationMode=a,await Za(this,G.SET_OPTIMIZATION_MODE,a)}catch(c){throw k.error("[".concat(this.getTrackId(),"] set optimization mode failed"),c.toString()),c;}k.info(m(b="[".concat(this.getTrackId(),"] set optimization mode success (")).call(b,a,")"))}else k.error(n.INVALID_PARAMS,"optimization mode must be motion, detail or balanced")}setScalabiltyMode(a){var b;
if(1===a.numSpatialLayers&&1!==a.numTemporalLayers)return k.error(n.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabiltyMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabiltyMode=a;k.info(m(b="[".concat(this.getTrackId(),"] set scalability mode success (")).call(b,a,")"))}updateMediaStreamTrackResolution(){tj(this._originMediaStreamTrack).then(([a,b])=>{this._videoHeight=b;this._videoWidth=a}).catch(Qe)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async renewMediaStreamTrack(){}}
Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Object,Object]),aa("design:returntype",void 0)],ta.prototype,"play",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Boolean,Boolean]),aa("design:returntype",y)],ta.prototype,"setEnabled",null);Db([pa(),bg({report:u}),aa("design:type",Function),aa("design:paramtypes",[Boolean]),aa("design:returntype",y)],ta.prototype,"setMuted",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[]),aa("design:returntype",Object)],
ta.prototype,"getStats",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Boolean,Object]),aa("design:returntype",y)],ta.prototype,"setBeautyEffect",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[]),aa("design:returntype",ImageData)],ta.prototype,"getCurrentFrameData",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Object]),aa("design:returntype",y)],ta.prototype,"setBitrateLimit",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",
[String]),aa("design:returntype",y)],ta.prototype,"setOptimizationMode",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Object]),aa("design:returntype",void 0)],ta.prototype,"setScalabiltyMode",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[]),aa("design:returntype",void 0)],ta.prototype,"updateMediaStreamTrackResolution",null);class ve extends ta{constructor(a,b,c,e,f,h){super(a,b.encoderConfig?bd(b.encoderConfig):{},e,f,h);this._enabled=!0;this._deviceName="default";
this.tryResumeVideoForIOS15WeChat=async()=>{ad()&&V().name===S.WECHAT&&this._enabled&&!this._isClosed&&(k.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.setEnabled(!1),await this.setEnabled(!0))};this._config=b;this._constraints=c;this._deviceName=a.label;this._config.encoderConfig&&(this._encoderConfig=bd(this._config.encoderConfig));da.on(Ha.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat);da.on(Ha.IOS_INTERRUPTION_END,
this.tryResumeVideoForIOS15WeChat)}async setDevice(a){var b;let c=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CAM_VIDEO_TRACK_SET_DEVICE,options:[this.getTrackId(),a]});if(k.info(m(b="[".concat(this.getTrackId(),"] set device to ")).call(b,a)),this._enabled)try{let c=await lb.getDeviceById(a);b={};b.video=Wd({},this._constraints);b.video.deviceId={exact:a};b.video.facingMode=void 0;this._originMediaStreamTrack.stop();let f=null;try{f=await Fb(b,this.getTrackId())}catch(h){throw k.error("[".concat(this.getTrackId(),
"] setDevice failed"),h.toString()),f=await Fb({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(f.getVideoTracks()[0],!1),h;}await this._updateOriginMediaStreamTrack(f.getVideoTracks()[0],!1);this.updateMediaStreamTrackResolution();this._deviceName=c.label;this._config.cameraId=a;this._constraints.deviceId={exact:a}}catch(e){throw c.onError(e),k.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}else try{this._deviceName=(await lb.getDeviceById(a)).label,
this._config.cameraId=a,this._constraints.deviceId={exact:a}}catch(e){throw c.onError(e),k.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e;}k.info("[".concat(this.getTrackId(),"] setDevice success"));c.onSuccess()}async setEnabled(a,b){if(!b){if(a===this._enabled)return;this.stateCheck("enabled",a)}k.info("[".concat(this.getTrackId(),"] start setEnabled"),a);let c=await this._enabledMutex.lock();if(!a){this._originMediaStreamTrack.onended=null;this._originMediaStreamTrack.stop();
b||(this._enabled=!1);try{await Za(this,G.NEED_REMOVE_TRACK,this)}catch(f){throw k.error("[".concat(this.getTrackId(),"] setEnabled to false error"),f.toString()),c(),f;}return k.info("[".concat(this.getTrackId(),"] setEnabled to false success")),c()}a=Wd({},this._constraints);let e=lb.searchDeviceIdByName(this._deviceName);e&&!a.deviceId&&(a.deviceId={exact:e});try{let a=await Fb({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(a.getVideoTracks()[0],!1);await Za(this,
G.NEED_ADD_TRACK,this)}catch(f){throw k.error("[".concat(this.getTrackId(),"] setEnabled true error"),f.toString()),c(),f;}this.updateMediaStreamTrackResolution();k.info("[".concat(this.getTrackId(),"] setEnabled to true success"));b||(this._enabled=!0);c()}async setEncoderConfiguration(a,b){b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG,options:[this.getTrackId(),a]});if(!this._enabled)throw a=new q(n.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled"),
b.onError(a),a;a=bd(a);this._forceBitrateLimit&&(a.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:a.bitrateMax,a.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:a.bitrateMin);let c=(e=this._config,JSON.parse(A(e)));var e;c.encoderConfig=a;e=sg(c);($c()||vb()||jc())&&(e.deviceId=void 0);k.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),A(a),A(e));try{await this._originMediaStreamTrack.applyConstraints(e),
this.updateMediaStreamTrackResolution()}catch(f){throw a=new q(n.UNEXPECTED_ERROR,f.toString()),k.error("[".concat(this.getTrackId(),"] applyConstraints error"),a.toString()),b.onError(a),a;}this._config=c;this._constraints=e;this._encoderConfig=a;try{await Za(this,G.NEED_RENEGOTIATE)}catch(f){return b.onError(f),f.throw()}b.onSuccess()}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((vb()||jc())&&this._enabled&&!this._isClosed&&da.duringInterruption){let a=async()=>{da.off(Ha.IOS_INTERRUPTION_END,
a);this._enabled&&!this._isClosed&&(k.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};da.on(Ha.IOS_INTERRUPTION_END,a)}else k.debug("[".concat(this.getTrackId(),"] track ended")),this.emit(Tc.TRACK_ENDED)}async renewMediaStreamTrack(){var a=Wd({},this._constraints);let b=lb.searchDeviceIdByName(this._deviceName);b&&!a.deviceId&&(a.deviceId={exact:b});a=await Fb({video:this._constraints},this.getTrackId());
await this._updateOriginMediaStreamTrack(a.getVideoTracks()[0],!0);this.updateMediaStreamTrackResolution()}close(){super.close();da.off(Ha.IOS_15_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat);da.off(Ha.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15WeChat)}}Db([pa(),aa("design:type",Function),aa("design:paramtypes",[String]),aa("design:returntype",y)],ve.prototype,"setDevice",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Boolean,Boolean]),aa("design:returntype",y)],ve.prototype,
"setEnabled",null);Db([pa(),aa("design:type",Function),aa("design:paramtypes",[Object,Boolean]),aa("design:returntype",y)],ve.prototype,"setEncoderConfiguration",null);var Mn=!0;"findIndex"in[]&&Array(1).findIndex(function(){Mn=!1});L({target:"Array",proto:!0,forced:Mn},{findIndex:function(a){return wk(this,a,1<arguments.length?arguments[1]:void 0)}});var vs=Aa("Array").findIndex,Nn=Array.prototype,Ue=function(a){var b=a.findIndex;return a===Nn||a instanceof Array&&b===Nn.findIndex?vs:b};let Rj=(a,
b)=>{let c=null;if("h264"===b?c=a.match(/a=rtpmap:(\d+) H264.*\r\n/)||a.match(/a=rtpmap:(\d+) H264.*\n/):"vp8"===b?c=a.match(/a=rtpmap:(\d+) VP8.*\r\n/)||a.match(/a=rtpmap:(\d+) VP8.*\n/):"vp9"===b?c=a.match(/a=rtpmap:(\d+) VP9.*\r\n/)||a.match(/a=rtpmap:(\d+) VP9.*\n/):"av1"===b&&(c=a.match(/a=rtpmap:(\d+) AV1.*\r\n/)||a.match(/a=rtpmap:(\d+) AV1.*\n/)),c&&c[1])return c[1]};class On extends Hn{constructor(a,b,c,e){super(b,b.stringUid||b.uid);this.suspendTracks=[];this.type="pub";this._waitingSuccessResponse=
this.detecting=!1;this.handleMuteVideoTrack=({muted:a},b,c)=>{this.setVideoTrackMuteState(a).then(b).catch(c)};this.handleMuteAudioTrack=({track:a,muted:b},c,e)=>{this.setAudioTrackMuteState(b,a).then(c).catch(e)};this.renegotiateWithGateway=async()=>(k.debug("[pc-".concat(this.pc.ID,"] renegotiate start")),new y(async(a,b)=>{this.connectionState="connecting";let c=e=>{"connected"===e&&(this.off(E.CONNECTION_STATE_CHANGE,c),a());"disconnected"===e&&(this.off(E.CONNECTION_STATE_CHANGE,c),b(new q(n.OPERATION_ABORTED,
"renegotiate abort")))};this.on(E.CONNECTION_STATE_CHANGE,c);db()&&v.SIMULCAST&&this.videoTrack&&this.videoTrack._scalabiltyMode&&await this.addSimulcast4Firefox(this.videoTrack._scalabiltyMode);var e=await this.pc.createOfferSDP();if(this.audioTrack&&this.audioTrack._encoderConfig&&(e=tg(e,this.audioTrack._encoderConfig)),this.videoTrack&&this.videoTrack._scalabiltyMode&&("vp9"!==this.codec&&"vp8"!==this.codec?(this.videoTrack._scalabiltyMode.numSpatialLayers=1,this.videoTrack._scalabiltyMode.numTemporalLayers=
1):(1<this.videoTrack._scalabiltyMode.numSpatialLayers||1<this.videoTrack._scalabiltyMode.numTemporalLayers)&&(e=Qj(e,this.codec,this.videoTrack._scalabiltyMode)),k.debug("renegoation spatial layers: ",this.videoTrack._scalabiltyMode.numSpatialLayers)),await this.pc.setOfferSDP(e),this.audioTrack instanceof ab)this.pc.onOfferSettled({videoActive:this.videoTrack&&!this.videoTrack.muted,audioActive:this.audioTrack&&this.audioTrack.isActive});let f=await Ia(this,E.NEED_RENEGOTIATE,e);this.videoTrack&&
!db()&&v.SIMULCAST&&this.videoTrack._scalabiltyMode&&this.setSimulcastVideoRtpEncodingParameters(this.videoTrack._scalabiltyMode);e=function(a,b){var c,e,f;const h=xa(c=RegExp.prototype.test).call(c,/^([a-z])=(.*)/);a=I(e=a.split(/(\r\n|\r|\n)/)).call(e,h);b=I(f=b.split(/(\r\n|\r|\n)/)).call(f,h);let k=null;const l=new ba;return t(a).call(a,a=>{const b=a.match(/m=(audio|video)/);if(b&&b[1])return void(k=b[1]);k&&(a=a.match(/=(sendrecv|recvonly|sendonly|inactive)/))&&a[1]&&l.set(k,a[1])}),k=null,z(b).call(b,
a=>{var b=a.match(/m=(audio|video)/);if(b&&b[1])return k=b[1],a;if(!k)return a;if((b=a.match(/=(sendrecv|recvonly|sendonly|inactive)/))&&b[1]){const c=l.get(k);if(c&&c!==b[1])return a.replace(b[1],c)}return a}).join("\r\n")+"\r\n"}(e,this.updateAnswerSDP(f.sdp));await this.pc.setAnswerSDP(e);k.debug("[pc-".concat(this.pc.ID,"] renegotiate success"));this.connectionState="connected"}));this.handleStreamRenegotiate=(a,b)=>{"connected"===this.connectionState?this.renegotiateWithGateway().then(a).catch(b):
a()};this.handleReplaceTrack=(a,b,c)=>{if(this.audioTrack instanceof ab&&"audio"===a.kind)return b();this.pc.replaceTrack(a).then(a=>a?this.renegotiateWithGateway():y.resolve()).then(b).catch(c)};this.handleCloseAudioTrack=a=>{};this.handleCloseVideoTrack=()=>{this.lowStreamConnection&&this.lowStreamConnection.videoTrack&&this.lowStreamConnection.videoTrack.close()};this.handleGetSessionID=a=>{a(this.joinInfo.sid)};this.handleGetLocalVideoStats=a=>{a(this.statsCollector.getLocalVideoTrackStats(this.connectionId))};
this.handleGetLocalAudioStats=a=>{a(this.statsCollector.getLocalAudioTrackStats(this.connectionId))};this.handleSetOptimizationMode=(a,b,c)=>{this.videoTrack&&this.setRtpSenderParametersByTrackConfig(this.videoTrack).then(b).catch(c)};this.isLowStreamConnection=!!e;this.codec=c;this.statsCollector=a;this.statsCollector.addLocalConnection(this)}getAllTracks(){let a=[];return this.videoTrack&&a.push(this.videoTrack),this.audioTrack&&this.audioTrack instanceof ab?a=m(a).call(a,this.audioTrack.trackList):
this.audioTrack&&a.push(this.audioTrack),a.push(...this.suspendTracks),a}async addTracks(a){let b=la;if("connecting"===this.connectionState)try{return await this.createWaitConnectionConnectedPromise(),await this.addTracks(a)}catch(h){throw new q(n.OPERATION_ABORTED,"publish abort");}var c=!1;let e=this.getAllTracks();a=uj(a=I(a).call(a,a=>-1===J(e).call(e,a)));for(let e=0;e<a.length;e+=1){var f=a[e];if(!(f instanceof yf))return(new q(n.INVALID_LOCAL_TRACK)).throw();if(f instanceof ta&&this.disabledVideoTrack){if(this.disabledVideoTrack!==
f)return(new q(n.EXIST_DISABLED_VIDEO_TRACK)).throw();this.disabledVideoTrack=void 0}if(f instanceof ta&&this.videoTrack)return(new q(n.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS)).throw();if(f instanceof La){if(this.audioTrack&&this.audioTrack._bypassWebAudio)throw k.error("One of the audio track was created with config bypassWebAudio set to true, there is no way to publish multiple audio tracks."),new q(n.CAN_NOT_PUBLISH_MULTIPLE_AUDIO_TRACKS);if(this.audioTrack instanceof ab)0===this.audioTrack.trackList.length&&
await this.pc.setAudioRtpEncodingParameters({active:!0}),this.audioTrack.addAudioTrack(f);else if(b.webAudioMediaStreamDest)if(f._bypassWebAudio){if(this.audioTrack)throw k.error("Can not publish another audio track with bypassWebAudio set to true."),new q(n.CAN_NOT_PUBLISH_MULTIPLE_AUDIO_TRACKS);k.debug("[".concat(this.connectionId,"] audio track doesn't not pass through WebAudio, use original audio track to publish"));c=await this.addTrackWithPC(f)}else c=new ab,f.muted?this.suspendTracks.push(f):
c.addAudioTrack(f),c=await this.addTrackWithPC(c);else k.debug("[".concat(this.connectionId,"] your browser does not support mixing track, use original audio track to publish")),c=await this.addTrackWithPC(f)}else f instanceof ta&&this.isLowStreamConnection?(c=Tj({},{width:160,height:120,framerate:15,bitrate:50},{},this.lowStreamParameter),b.supportDualStreamEncoding?(k.debug("[".concat(this.connectionId,"] creating low stream using rtp encoding.")),this.lowStreamEncoding=ko(c,f),f=f.clone({bitrateMax:c.bitrate,
bitrateMin:c.bitrate})):(k.debug("[".concat(this.connectionId,"] creating low stream using canvas.")),f=Ao(f,c),f=new ta(f,{bitrateMax:c.bitrate,bitrateMin:c.bitrate})),f._hints.push(Yb.LOW_STREAM),c=await this.addTrackWithPC(f),this.bindTrackEvents(f)):(this.detecting=!0,wb(()=>{this.detecting=!1},8E3),c=await this.addTrackWithPC(f))}await this.updateControlMessage();c&&await this.renegotiateWithGateway();t(a).call(a,a=>this.bindTrackEvents(a))}async removeTracks(a,b){let c=this.getAllTracks();a=
uj(a=I(a).call(a,a=>-1!==J(c).call(c,a)||a===this.disabledVideoTrack));let e=[];for(let c=0;c<a.length;c+=1){let f=a[c];if(this.unbindTrackEvents(f),this.audioTrack instanceof ab&&f instanceof La)this.audioTrack.removeAudioTrack(f),Gc(this.suspendTracks,f),0===this.audioTrack.trackList.length&&(e.push(this.audioTrack),this.audioTrack=void 0);else if(f instanceof La)e.push(f),this.audioTrack=void 0;else if(f instanceof ta){if(b){if(this.disabledVideoTrack===f)return void(this.disabledVideoTrack=void 0)}else this.disabledVideoTrack=
this.videoTrack;e.push(f);this.isLowStreamConnection&&f.close();this.videoTrack=void 0}}if(this.videoTrack||this.audioTrack){if(0!==e.length){if("connecting"===this.connectionState)try{await this.createWaitConnectionConnectedPromise()}catch(h){return}for(let b of e){var f;k.debug(m(f="[".concat(this.connectionId,"] remove ")).call(f,b.trackMediaType," from pc"));await this.pc.removeTrack(b._mediaStreamTrack);a=V();"Safari"===a.name&&"11"===a.version&&await b.renewMediaStreamTrack()}await this.renegotiateWithGateway()}}else await this.closeP2PConnection()}async updateControlMessage(){this.audioTrack instanceof
ab&&"connected"===this.connectionState&&(this.audioTrack&&await Ia(this,E.NEED_CONTROL,{type:"audio",muted:!this.audioTrack.isActive}),this.videoTrack&&await Ia(this,E.NEED_CONTROL,{type:"video",muted:this.videoTrack.muted}))}async setSimulcastVideoRtpEncodingParameters(a){let b=this.pc.getSender("video");if(!b)throw new q(n.LOW_STREAM_ENCODING_ERROR,"Low stream has no video sender.");let c=b.getParameters();if(!c.encodings||!c.encodings[0])throw new q(n.LOW_STREAM_ENCODING_ERROR,"Low stream RtpEncodingParameters is empty.");
this.videoTrack&&this.videoTrack._encoderConfig&&this.videoTrack._encoderConfig.bitrateMax&&200<this.videoTrack._encoderConfig.bitrateMax&&1<a.numSpatialLayers&&(c.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:1E3*(this.videoTrack._encoderConfig.bitrateMax-50)},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:5E4,scaleResolutionDownBy:4}]);await b.setParameters(c)}startP2PConnection(){return new y(async(a,b)=>{if(!this.audioTrack&&
!this.videoTrack)return b(new q(n.UNEXPECTED_ERROR,"no track to publish"));let c=e=>{if("connected"===e&&(this.off(E.CONNECTION_STATE_CHANGE,c),a()),"disconnected"===e){if(this.off(E.CONNECTION_STATE_CHANGE,c),this.disconnectedReason)return b(this.disconnectedReason);b(new q(n.OPERATION_ABORTED,"publish abort"))}};this.on(E.CONNECTION_STATE_CHANGE,c);this.disconnectedReason=void 0;this.connectionState="connecting";this._waitingSuccessResponse=!0;this.startTime=x();try{var e;!this.pc.audioTrack&&this.audioTrack&&
await this.pc.addTrack(this.audioTrack._mediaStreamTrack);!this.pc.videoTrack&&this.videoTrack&&await this.pc.addTrack(this.videoTrack._mediaStreamTrack);db()&&v.SIMULCAST&&this.videoTrack&&this.videoTrack._scalabiltyMode&&await this.addSimulcast4Firefox(this.videoTrack._scalabiltyMode);let a=await this.pc.createOfferSDP();v.REMOVE_NEW_CODECS&&(a="vp9"===this.codec?ug(a,["av1"]):"av1"===this.codec?ug(a,["vp9"]):ug(a,["vp9","av1"]));let b=Oj(a);if(this.videoTrack&&!Z(e=b.video).call(e,this.codec.toUpperCase())&&
k.warning("current codec is not supported, support list: ".concat(b.video.join(","))),this.audioTrack&&this.audioTrack._encoderConfig&&(a=tg(a,this.audioTrack._encoderConfig)),this.videoTrack&&!db()&&this.videoTrack._scalabiltyMode&&("vp9"!==this.codec&&"vp8"!==this.codec?(this.videoTrack._scalabiltyMode.numSpatialLayers=1,this.videoTrack._scalabiltyMode.numTemporalLayers=1):(1<this.videoTrack._scalabiltyMode.numSpatialLayers||1<this.videoTrack._scalabiltyMode.numTemporalLayers)&&(a=Qj(a,this.codec,
this.videoTrack._scalabiltyMode)),k.debug("spatial layers: ",this.videoTrack._scalabiltyMode.numSpatialLayers)),await this.pc.setOfferSDP(a),this.audioTrack instanceof ab)this.pc.onOfferSettled({videoActive:this.videoTrack&&!this.videoTrack.muted,audioActive:this.audioTrack&&this.audioTrack.isActive});this.videoTrack&&this.setRtpSenderParametersByTrackConfig(this.videoTrack);k.debug("[".concat(this.connectionId,"] create and set offer success"));e={messageType:"OFFER",sdp:a,offererSessionId:104,retry:!0};
la.supportDualStreamEncoding&&this.isLowStreamConnection&&this.lowStreamEncoding&&this.videoTrack&&await this.setLowStreamEncoding(this.lowStreamEncoding,this.videoTrack);this.videoTrack&&!db()&&v.SIMULCAST&&this.videoTrack._scalabiltyMode&&this.setSimulcastVideoRtpEncodingParameters(this.videoTrack._scalabiltyMode);let c=await Ia(this,E.NEED_ANSWER,e),r=this.updateAnswerSDP(c.sdp);await this.pc.setAnswerSDP(r);k.debug("[".concat(this.connectionId,"] set answer success"));await this.icePromise;this.connectionState=
"connected";this.startUploadStats()}catch(f){this.off(E.CONNECTION_STATE_CHANGE,c),this.connectionState="disconnected",this.reportPublishEvent(!1,f.code),k.error("[".concat(this.connectionId,"] connection error"),f.toString()),b(f)}})}reportPublishEvent(a,b,c){var e;this._waitingSuccessResponse=!1;u.publish(this.joinInfo.sid,{lts:this.startTime,succ:a,ec:b,audioName:this.audioTrack&&(this.audioTrack instanceof ab?this.audioTrack.getSubTrackLabels().join(","):this.audioTrack.getTrackLabel()),videoName:this.videoTrack&&
this.videoTrack.getTrackLabel(),screenshare:!(!this.videoTrack||-1===J(e=this.videoTrack._hints).call(e,Yb.SCREEN_TRACK)),audio:!!this.audioTrack,video:!!this.videoTrack,p2pid:this.pc.ID,publishRequestid:this.ID,extend:c})}async closeP2PConnection(a){let b=this.getAllTracks();var c;(t(b).call(b,a=>{this.unbindTrackEvents(a)}),this.isLowStreamConnection&&this.videoTrack&&this.videoTrack.close(),this.videoTrack=void 0,this.audioTrack instanceof ab)&&(t(c=this.audioTrack.trackList).call(c,a=>{this.audioTrack.removeAudioTrack(a)}),
this.audioTrack.close());this.audioTrack=void 0;this.stopUploadStats();this.statsCollector.removeConnection(this.connectionId);await this.closePC(a);this.connectionState="disconnected";this.removeAllListeners()}getNetworkQuality(){var a,b=this.pc.getStats();if(!b.videoSend[0]&&!b.audioSend[0])return 1;var c=Hc(this,E.NEED_SIGNAL_RTT),e=b.videoSend[0]?b.videoSend[0].rttMs:void 0;let f=b.audioSend[0]?b.audioSend[0].rttMs:void 0;e=e&&f?(e+f)/2:e||f;c=70*b.sendPacketLossRate/50+.3*((e&&c?(e+c)/2:e||c)||
0)/1500;c=.17>c?1:.36>c?2:.59>c?3:.1>c?4:5;return this.videoTrack&&this.videoTrack._encoderConfig&&-1===J(a=this.videoTrack._hints).call(a,Yb.SCREEN_TRACK)&&(a=this.videoTrack._encoderConfig.bitrateMax,b=b.bitrate.actualEncoded,a&&b)?(b=(1E3*a-b)/(1E3*a),Fq[.15>b?0:.3>b?1:.45>b?2:.6>b?3:4][c]):c}handleUpdateBitrateLimit(a){this.videoTrack&&this.videoTrack.setBitrateLimit(a)}async setAudioTrackMuteState(a,b){if(!(this.audioTrack instanceof ab))return void k.debug("[".concat(this.connectionId,"] set audio mute in unsupported environment"));
let c=this.audioTrack;try{if(a){var e;if(c.removeAudioTrack(b),0===c.trackList.length)k.debug(m(e="[".concat(this.connectionId,"] set audio encoding active, id: ")).call(e,b.getTrackId(),", state: ",!1)),await this.pc.setAudioRtpEncodingParameters({active:!1});this.suspendTracks.push(b)}else await this.pc.setAudioRtpEncodingParameters({active:!0}),c.addAudioTrack(b),Gc(this.suspendTracks,b)}catch(h){var f;k.warning(m(f="[".concat(this.connectionId,"] set audio muted error ")).call(f,h,", fallback to set enabled"))}await Ia(this,
E.NEED_CONTROL,{type:"audio",muted:!(!this.audioTrack||this.audioTrack.isActive)})}async setVideoTrackMuteState(a){let b=!a,c=!1;if(V().name===S.FIREFOX)c=!0;else try{var e,f;k.debug(m(e=m(f="[".concat(this.connectionId,"] set video encoding active, id: ")).call(f,this.videoTrack&&this.videoTrack.getTrackId(),", state: ")).call(e,b));await this.pc.setVideoRtpEncodingParameters({active:b})}catch(p){var h;k.warning(m(h="[".concat(this.connectionId,"] set video encoding active error ")).call(h,p,", fallback to set enabled"));
c=!0}var l,r;c&&this.videoTrack&&(k.debug(m(l=m(r="[".concat(this.connectionId,"] set video encoding active fallback to enabled on firefox, type: ")).call(r,this.videoTrack&&this.videoTrack.getTrackId(),", state: ")).call(l,b)),this.videoTrack.getMediaStreamTrack().enabled=b);this.lowStreamConnection&&this.lowStreamConnection.setVideoTrackMuteState(a);!this.isLowStreamConnection&&await Ia(this,E.NEED_CONTROL,{type:"video",muted:a})}uploadStats(a,b){let c=this.audioTrack?function(a,b){const c=a.audioSend[0];
if(!c)return null;a={id:va(10,""),timestamp:(new Date(a.timestamp)).toISOString(),mediaType:"audio",type:"ssrc",ssrc:c.ssrc.toString()};return a.A_astd=b._originMediaStreamTrack.enabled&&b._mediaStreamTrack.enabled?"0":"1",c.inputLevel?a.A_ail=Math.round(100*c.inputLevel).toString():a.A_ail=Math.round(100*b._source.getAccurateVolumeLevel()).toString(),a.A_apil=Math.round(100*b._source.getAccurateVolumeLevel()).toString(),a}(a,this.audioTrack):void 0,e=this.videoTrack?function(a,b){const c=a.videoSend[0];
if(!c)return null;a={id:va(10,""),timestamp:(new Date(a.timestamp)).toISOString(),mediaType:"video",type:"ssrc",ssrc:c.ssrc.toString()};switch(a.A_vstd=b._originMediaStreamTrack&&!b._originMediaStreamTrack.enabled||!b._mediaStreamTrack.enabled?"1":"0",c.sentFrame&&(a.A_fhs=c.sentFrame.height.toString(),a.A_frs=c.sentFrame.frameRate.toString(),a.A_fws=c.sentFrame.width.toString()),c.adaptionChangeReason){case "none":a.A_ac="0";break;case "cpu":a.A_ac="1";break;case "bandwidth":a.A_ac="2";break;case "other":a.A_ac=
"3"}return a.A_nr=c.nacksCount.toString(),c.avgEncodeMs&&(a.A_aem=c.avgEncodeMs.toFixed(0).toString()),a}(a,this.videoTrack):void 0,f=qj(a,b),h=function(a){const b={id:"bweforvideo",timestamp:(new Date(a.timestamp)).toISOString(),type:"VideoBwe"};return a.bitrate.retransmit&&(b.A_rb=a.bitrate.retransmit.toString()),a.bitrate.targetEncoded&&(b.A_teb=a.bitrate.targetEncoded.toString()),b.A_aeb=a.bitrate.actualEncoded.toString(),b.A_tb=a.bitrate.transmit.toString(),void 0!==a.sendBandwidth&&(b.A_asb=
a.sendBandwidth.toString()),b}(a);c&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.PUBLISH_STATS,c));e&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.PUBLISH_STATS,Tj({},e,{},f)));h&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.PUBLISH_STATS,h))}uploadSlowStats(a){let b=qj(a);b&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.PUBLISH_STATS,b))}uploadRelatedStats(a){let b=function(a){return(a=a.videoSend[0])?{mediaType:"video",isVideoMute:!1,frameRateInput:a.inputFrame&&a.inputFrame.frameRate.toString(),frameRateSent:a.sentFrame&&a.sentFrame.frameRate.toString(),
googRtt:a.rttMs.toString()}:null}(a);b&&(b.isVideoMute=!(!this.videoTrack||!this.videoTrack.muted),xb(()=>{this.emit(E.NEED_UPLOAD,Lb.PUBLISH_RELATED_STATS,b)}))}async addSimulcast4Firefox(a){if(db()&&this.videoTrack&&this.videoTrack._encoderConfig&&this.videoTrack._encoderConfig.bitrateMax&&200<this.videoTrack._encoderConfig.bitrateMax&&1<a.numSpatialLayers&&"vp8"===this.codec&&(a=this.pc.getSender("video"))){let b=a.getParameters();k.debug("getParameters : ",b);b||k.error("[".concat(this.connectionId,
"] get sender parameter error."));b.encodings=[{rid:"m",active:!0,maxBitrate:5E4,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:1E3*(this.videoTrack._encoderConfig.bitrateMax-50)}];await a.setParameters(b);k.debug("setParameters : ",b)}}bindTrackEvents(a){var b;a.addListener(G.NEED_RESET_REMOTE_SDP,xa(b=this.handleResetRemoteSdp).call(b,this));this.isLowStreamConnection||(a instanceof La?(a.addListener(G.GET_STATS,this.handleGetLocalAudioStats),a.addListener(G.NEED_CLOSE,this.handleCloseAudioTrack),
a.addListener(G.SET_AUDIO_TRACK_MUTED,this.handleMuteAudioTrack)):a instanceof ta&&(a.addListener(G.GET_STATS,this.handleGetLocalVideoStats),a.addListener(G.NEED_CLOSE,this.handleCloseVideoTrack),a.addListener(G.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),a.addListener(G.SET_VIDEO_TRACK_MUTED,this.handleMuteVideoTrack)),a.addListener(G.NEED_RENEGOTIATE,this.handleStreamRenegotiate),a.addListener(G.NEED_REPLACE_TRACK,this.handleReplaceTrack),a.addListener(G.NEED_SESSION_ID,this.handleGetSessionID))}unbindTrackEvents(a){this.isLowStreamConnection||
(a instanceof La?(a.off(G.GET_STATS,this.handleGetLocalAudioStats),a.off(G.NEED_CLOSE,this.handleCloseAudioTrack),a.off(G.SET_AUDIO_TRACK_MUTED,this.handleMuteAudioTrack)):a instanceof ta&&(a.off(G.GET_STATS,this.handleGetLocalVideoStats),a.off(G.NEED_CLOSE,this.handleCloseVideoTrack),a.off(G.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),a.off(G.SET_VIDEO_TRACK_MUTED,this.handleMuteVideoTrack)),a.off(G.NEED_RENEGOTIATE,this.handleStreamRenegotiate),a.off(G.NEED_REPLACE_TRACK,this.handleReplaceTrack),
a.off(G.NEED_SESSION_ID,this.handleGetSessionID))}async addTrackWithPC(a){if("connecting"===this.connectionState)return(new q(n.INVALID_OPERATION,"last publish operation has not finished")).throw();let b=this.videoTrack,c=!1;return this.audioTrack&&a instanceof ab?(this.audioTrack=a,k.debug("[".concat(this.connectionId,"] replace pc audio track")),c=await this.pc.replaceTrack(a._mediaStreamTrack)):this.videoTrack&&a instanceof ta?(this.videoTrack=a,k.debug("[".concat(this.connectionId,"] replace pc video track")),
c=await this.pc.replaceTrack(a._mediaStreamTrack)):a instanceof La?(this.audioTrack=a,k.debug("[".concat(this.connectionId,"] add audio track to pc")),await this.pc.addTrack(a._mediaStreamTrack),c=!0):a instanceof ta&&(this.videoTrack=a,k.debug("[".concat(this.connectionId,"] add video track to pc")),await this.pc.addTrack(a._mediaStreamTrack),c=!0),"connected"===this.connectionState&&this.videoTrack!==b&&this.videoTrack&&await this.setRtpSenderParametersByTrackConfig(this.videoTrack),"disconnected"!==
this.connectionState&&c}handleResetRemoteSdp(){return new y((a,b)=>{var c;k.info("[pc-".concat(this.pc.ID,"] start reset remote sdp"));let e=this.pc.getOfferSDP();var f=this.pc.getAnswerSDP();if(!f||!e)return a();f=f.sdp;let h;this.videoTrack&&this.videoTrack._encoderConfig&&-1===J(c=this.videoTrack._hints).call(c,Yb.SCREEN_TRACK)&&(h=function(a,b){var c,e;let f=b.bitrateMin;b=b.bitrateMax;let h=xa(c=RegExp.prototype.test).call(c,/^([a-z])=(.*)/);a=I(e=a.split(/(\r\n|\r|\n)/)).call(e,h);if(b){let c=
"AS";V().name===S.FIREFOX&&(b=1E3*(b>>>0),c="TIAS");e=Ue(a).call(a,a=>Z(a).call(a,c));var k;0<e&&(a[e]=m(k="b=".concat(c,":")).call(k,b))}f&&(k=Ue(a).call(a,a=>Z(a).call(a,"x-google-min-bitrate")),0<k&&(a[k]=a[k].replace(/x-google-min-bitrate=(.*)/,"x-google-min-bitrate=".concat(f))));return a.join("\r\n")+"\r\n"}(f,this.videoTrack._encoderConfig));f!==h?this.pc.setOfferSDP(e.sdp).then(()=>{if(h)return this.pc.setAnswerSDP(h)}).then(a).catch(a=>{var c;k.error(m(c="[pc-".concat(this.pc.ID,"] reset remote sdp error, ")).call(c,
a));b(a)}):k.debug("[pc-".concat(this.pc.ID,"] remote sdp have no not changed"))})}async setRtpSenderParametersByTrackConfig(a){if(!la.supportSetRtpSenderParameters)return void k.debug("[".concat(this.connectionId,"] do not support set pc rtp sender, skip"));let b={},c="balanced";"motion"===a._optimizationMode?c="maintain-framerate":"detail"===a._optimizationMode&&(c="maintain-resolution");k.debug("[".concat(this.connectionId,"] set pc rtp sender"),b,c);await this.pc.setRtpSenderParameters(b,c)}updateAnswerSDP(a){var b,
c;return a=a.replace(/a=x-google-flag:conference\r\n/g,""),this.videoTrack&&J(b=this.videoTrack._hints).call(b,Yb.SCREEN_TRACK),this.videoTrack&&this.videoTrack._encoderConfig&&-1===J(c=this.videoTrack._hints).call(c,Yb.SCREEN_TRACK)&&(a=function(a,b,c){let e=la;var f=c.bitrateMin;c=c.bitrateMax;let h=a.match(/m=video.*\r\n/)||a.match(/m=video.*\n/);if(h&&0<h.length&&e.supportMinBitrate&&f&&(b=Rj(a,b)))if(v.SIMULCAST){var k,n;f=c?.7*c:300;a=a.replace(h[0],m(k=m(n="".concat(h[0],"a=fmtp:")).call(n,
b," x-google-start-bitrate=")).call(k,f,"\r\n"))}else{var q,t;a=a.replace(h[0],m(q=m(t="".concat(h[0],"a=fmtp:")).call(t,b," x-google-min-bitrate=")).call(q,f,"\r\n"))}if(h&&0<h.length&&c){var B,u;k="AS";V().name===S.FIREFOX&&(c=1E3*(c>>>0),k="TIAS");a=a.replace(h[0],m(B=m(u="".concat(h[0],"b=")).call(u,k,":")).call(B,c,"\r\n"))}return a}(a,this.codec,this.videoTrack._encoderConfig)),this.audioTrack&&this.audioTrack._encoderConfig&&(a=tg(a,this.audioTrack._encoderConfig)),a=function(a){let b=V();
return b.name!==S.SAFARI&&b.os!==Na.IOS?a:a.replace(/a=.*video-orientation\r\n/g,"")}(a)}createPC(){this.pc=new En({turnServer:this.joinInfo.turnServer});this.updateICEPromise()}async closePC(a){return this.pc.onICEConnectionStateChange=void 0,this.pc.close(),!a&&await Ia(this,E.NEED_UNPUB)}onPCDisconnected(a){this.reportPublishEvent(!1,a.code)}async setLowStreamEncoding(a,b){try{let c=await this.pc.setVideoRtpEncodingParameters(a),e=b.getMediaStreamTrack();if(a.scaleResolutionDownBy&&c.encodings[0].scaleResolutionDownBy!==
a.scaleResolutionDownBy){let c=b._videoHeight||e.getSettings().height,h=b._videoWidth||e.getSettings().width;c&&h&&await e.applyConstraints({height:c/a.scaleResolutionDownBy,width:h/a.scaleResolutionDownBy})}a.maxFramerate&&c.encodings[0].maxFramerate!==a.maxFramerate&&await e.applyConstraints({frameRate:a.maxFramerate})}catch(c){if(c instanceof q)throw c;throw new q(n.LOW_STREAM_ENCODING_ERROR,c.message);}}}class Pn extends xm{constructor(a,b,c,e){var f,h;super(a,m(f=m(h="track-".concat(a.kind,"-")).call(h,
b,"-")).call(f,e));this._isDestroyed=!1;this._userId=b;this._uintId=c}getUserId(){return this._userId}_updateOriginMediaStreamTrack(a){this._mediaStreamTrack=this._originMediaStreamTrack=a;this._updatePlayerSource()}_destroy(){this._isDestroyed=!0;k.info("[".concat(this.getTrackId(),"] is destroyed"));this.stop();super.close()}}class we extends Pn{constructor(a,b,c,e){super(a,b,c,e);this.trackMediaType="video";this.updateMediaStreamTrackResolution()}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==
Qa.PLAYING)}getStats(){Qd(()=>{k.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning");return Hc(this,G.GET_STATS)||vg({},lh)}play(a,b={}){let c=u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_VIDEO_TRACK_PLAY,options:[this.getTrackId(),"string"==typeof a?a:"HTMLElement",b]});if("string"==typeof a){let b=document.getElementById(a);var e;b?a=b:(k.warning(m(e="[".concat(this.getTrackId(),
'] can not find "#')).call(e,a,'" element, use document.body')),a=document.body)}k.debug("[".concat(this.getTrackId(),"] start video playback"),A(b));a=vg({fit:"cover"},b,{trackId:this.getTrackId(),element:a});this._player?this._player.updateConfig(a):(this._player=new In(a),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.emit(je.FIRST_FRAME_DECODED)});this._player.play();c.onSuccess()}stop(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_VIDEO_TRACK_STOP,
options:[this.getTrackId()]});if(!this._player)return a.onSuccess();this._player.destroy();this._player=void 0;k.debug("[".concat(this.getTrackId(),"] stop video playback"));a.onSuccess()}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){tj(this._originMediaStreamTrack).then(([a,b])=>{this._videoHeight=b;this._videoWidth=a}).catch(Qe)}_updatePlayerSource(){k.debug("[".concat(this.getTrackId(),"] update player source track"));
this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}}class xe extends Pn{constructor(a,b,c,e){super(a,b,c,e);this.trackMediaType="audio";this._useAudioElement=!0;this._volume=100;this._source=new zm(a,!0);this._source.once(Mb.RECEIVE_TRACK_BUFFER,()=>{this.emit(je.FIRST_FRAME_DECODED)})}get isPlaying(){return this._useAudioElement?Bb.isPlaying(this.getTrackId()):this._source.isPlayed}setAudioFrameCallback(a,b=4096){if(!a)return this._source.removeAllListeners(Mb.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();
this._source.startGetAudioBuffer(b);this._source.removeAllListeners(Mb.ON_AUDIO_BUFFER);this._source.on(Mb.ON_AUDIO_BUFFER,b=>a(b))}setVolume(a){let b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_AUDIO_SET_VOLUME,options:[this.getTrackId(),a]},300);this._volume=a;this._useAudioElement?Bb.setVolume(this.getTrackId(),a):this._source.setVolume(a/100);b.onSuccess()}async setPlaybackDevice(a){let b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_AUDIO_SET_OUTPUT_DEVICE,options:[this.getTrackId(),
a]});if(!this._useAudioElement)throw new q(n.NOT_SUPPORTED,"your browser does not support setting the audio output device");try{await Bb.setSinkID(this.getTrackId(),a)}catch(c){throw b.onError(c),c;}b.onSuccess()}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){Qd(()=>{k.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning");return Hc(this,G.GET_STATS)||vg({},kh)}play(){let a=
u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_AUDIO_TRACK_PLAY,options:[this.getTrackId()]});k.debug("[".concat(this.getTrackId(),"] start audio playback"));this._useAudioElement?(k.debug("[".concat(this.getTrackId(),"] use audio element to play")),Bb.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play();a.onSuccess()}stop(){let a=u.reportApiInvoke(null,{tag:C.TRACER,name:D.REMOTE_AUDIO_TRACK_STOP,options:[this.getTrackId()]});k.debug("[".concat(this.getTrackId(),"] stop audio playback"));
this._useAudioElement?Bb.stop(this.getTrackId()):this._source.stop();a.onSuccess()}_destroy(){super._destroy();this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){k.debug("[".concat(this.getTrackId(),"] update player source track"));this._source.updateTrack(this._mediaStreamTrack);this._useAudioElement&&Bb.updateTrack(this.getTrackId(),this._mediaStreamTrack)}}class ws extends Hn{constructor(a,b,c,e){super(c,a.uid);this.type="sub";this.unusedTracks=[];this.onTrack=
a=>{var b,c;if("audio"===a.kind&&!this.subscribeOptions.audio||"video"===a.kind&&!this.subscribeOptions.video)return this.unusedTracks.push(a),void k.debug(m(c="[".concat(this.connectionId,"] unused ontrack event, kind: ")).call(c,a.kind));k.debug(m(b="[".concat(this.connectionId,"] emit pc ontrack after subscribe ")).call(b,a.kind),a);b="audio"===a.kind?this.user._audioTrack:this.user._videoTrack;var e,f;b?b._updateOriginMediaStreamTrack(a):"audio"===a.kind?(this.pc._statsFilter.setIsFirstAudioDecoded(!1),
this.user._audioTrack=new xe(a,this.getUserId(),this.user._uintid,this.joinInfo.clientId),k.info(m(e="[".concat(this.connectionId,"] create remote audio track: ")).call(e,this.user._audioTrack.getTrackId())),this.bindTrackEvents(this.user._audioTrack)):(this.user._videoTrack=new we(a,this.getUserId(),this.user._uintid,this.joinInfo.clientId),k.info(m(f="[".concat(this.connectionId,"] create remote video track: ")).call(f,this.user._videoTrack.getTrackId())),this.bindTrackEvents(this.user._videoTrack))};
this.handleGetRemoteAudioStats=a=>{a(this.statsCollector.getRemoteAudioTrackStats(this.connectionId))};this.handleGetRemoteVideoStats=a=>{a(this.statsCollector.getRemoteVideoTrackStats(this.connectionId))};this.handleGetSessionID=a=>{a(this.joinInfo.sid)};this.user=a;this.statsCollector=b;this.statsCollector.addRemoteConnection(this);this.subscribeOptions=e}async startP2PConnection(){return new y(async(a,b)=>{let c=e=>{if("connected"===e&&(u.subscribe(this.joinInfo.sid,{lts:this.startTime,succ:!0,
video:this.subscribeOptions.video,audio:this.subscribeOptions.audio,peerid:this.user.uid,ec:null,subscribeRequestid:this.ID,p2pid:this.pc.ID}),this.off(E.CONNECTION_STATE_CHANGE,c),a()),"disconnected"===e){if(this.off(E.CONNECTION_STATE_CHANGE,c),this.disconnectedReason)return b(this.disconnectedReason);b(new q(n.OPERATION_ABORTED,"subscribe abort"))}};if(this.on(E.CONNECTION_STATE_CHANGE,c),this.disconnectedReason=void 0,this.connectionState="connecting",this.startTime=x(),!this.subscribeOptions)return void b(new q(n.UNEXPECTED_ERROR,
"no subscribe options"));let e=new MediaStream,f=new y(a=>{this.pc.onTrack=(b,c)=>{var f,h;if("audio"===b.kind&&!this.subscribeOptions.audio||"video"===b.kind&&!this.subscribeOptions.video)return this.unusedTracks.push(b),void k.debug(m(h="[".concat(this.connectionId,"] unused ontrack event ")).call(h,b.kind));e.addTrack(b);h={audio:0<e.getAudioTracks().length,video:0<e.getVideoTracks().length};k.debug(m(f="[".concat(this.connectionId,"] subscribe ontrack: ")).call(f,b.kind),c,b);a:{b=this.subscribeOptions;
var l,p;c=he(l=W(h)).call(l);l=he(p=W(b)).call(p);for(p=0;p<c.length;p+=1){if(c[p]!==l[p]){h=!1;break a}if(h[c[p]]!==b[c[p]]){h=!1;break a}}h=!0}h&&(this.pc.onTrack=this.onTrack,k.debug("[".concat(this.connectionId,"] get all subscribed tracks")),a(e))}});try{let a=function(a){return V().name!==S.FIREFOX?a:a.replace("/recvonly http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"," http://www.webrtc.org/experiments/rtp-hdrext/playout-delay")}(Pj(await this.pc.createOfferSDP()));await this.pc.setOfferSDP(a);
k.debug("[".concat(this.connectionId,"] create and set offer success"));let b=await Ia(this,E.NEED_ANSWER,{messageType:"OFFER",sdp:a,offererSessionId:104,retry:!0});await this.pc.setAnswerSDP(Pj(b.sdp));k.debug("[".concat(this.connectionId,"] set answer success"));let c=await y.all([f,this.icePromise]),e=c[0].getAudioTracks()[0],n=c[0].getVideoTracks()[0];var h,l;e&&(this.user._audioTrack?this.user._audioTrack._updateOriginMediaStreamTrack(e):(this.user._audioTrack=new xe(e,this.getUserId(),this.user._uintid,
this.joinInfo.clientId),k.info(m(h="[".concat(this.connectionId,"] create remote audio track: ")).call(h,this.user._audioTrack.getTrackId())),this.bindTrackEvents(this.user._audioTrack)));n&&(this.user._videoTrack?this.user._videoTrack._updateOriginMediaStreamTrack(n):(this.user._videoTrack=new we(n,this.getUserId(),this.user._uintid,this.joinInfo.clientId),k.info(m(l="[".concat(this.connectionId,"] create remote video track: ")).call(l,this.user._videoTrack.getTrackId())),this.bindTrackEvents(this.user._videoTrack)));
this.connectionState="connected";this.startUploadStats()}catch(r){this.off(E.CONNECTION_STATE_CHANGE,c),this.connectionState="disconnected",u.subscribe(this.joinInfo.sid,{lts:this.startTime,succ:!1,video:this.subscribeOptions.video,audio:this.subscribeOptions.audio,peerid:this.user.uid,ec:r.code,subscribeRequestid:this.ID,p2pid:this.pc.ID}),b(r)}})}async closeP2PConnection(a){"disconnected"!==this.connectionState&&(this.stopUploadStats(),this.statsCollector.removeConnection(this.connectionId),this.connectionState=
"disconnected",await this.setSubscribeOptions({audio:!1,video:!1}),await this.closePC(a),this.removeAllListeners())}getNetworkQuality(){var a=this.pc.getStats();if(!a.audioRecv[0]&&!a.videoRecv[0])return 1;var b=Hc(this,E.NEED_SIGNAL_RTT),c=a.rtt;b=(c&&b?(c+b)/2:c||b)||0;c=a.audioRecv[0]?a.audioRecv[0].jitterMs:void 0;a=a.recvPacketLossRate;let e=70*a/50+.3*b/1500;c&&(e=60*a/50+.2*b/1500+.2*c/400);return.1>e?1:.17>e?2:.36>e?3:.59>e?4:5}uploadStats(a){let b=this.user.audioTrack?function(a,b){const c=
a.audioRecv[0];if(!c)return null;a={id:va(10,""),timestamp:(new Date(a.timestamp)).toISOString(),mediaType:"audio",type:"ssrc",ssrc:c.ssrc.toString()};return a.bytesReceived=c.bytes.toString(),a.packetsLost=c.packetsLost.toString(),a.packetsReceived=c.packets.toString(),c.outputLevel?a.A_aol=Math.round(100*c.outputLevel).toString():a.A_aol=Math.round(100*b._source.getAccurateVolumeLevel()).toString(),a.A_apol=Math.round(100*b._source.getAccurateVolumeLevel()).toString(),b&&(a.A_artd=b._originMediaStreamTrack.enabled&&
b._mediaStreamTrack.enabled?"0":"1"),a.A_jr=c.jitterMs.toString(),a.A_jbm=Math.floor(c.jitterBufferMs).toString(),a.A_cdm=Math.floor(c.jitterBufferMs).toString(),a}(a,this.user.audioTrack):void 0,c=this.user.videoTrack?function(a,b){const c=a.videoRecv[0];if(!c)return null;a={id:va(10,""),timestamp:(new Date(a.timestamp)).toISOString(),mediaType:"video",type:"ssrc",ssrc:c.ssrc.toString()};var e;return a.bytesReceived=c.bytes.toString(),a.packetsLost=c.packetsLost.toString(),a.packetsReceived=c.packets.toString(),
c.framesRateFirefox&&(a.A_frr=c.framesRateFirefox.toString()),c.receivedFrame&&(a.A_frr=c.receivedFrame.frameRate.toString()),a.A_frd=c.decodeFrameRate.toString(),c.outputFrame&&(a.A_fro=c.outputFrame.frameRate.toString()),void 0!==c.jitterBufferMs&&(a.A_jbm=Math.floor(c.jitterBufferMs).toString()),void 0!==c.currentDelayMs&&(a.A_cdm=Math.floor(c.currentDelayMs).toString()),a.A_fs=c.firsCount.toString(),a.A_ns=c.nacksCount.toString(),a.A_ps=c.plisCount.toString(),b&&(a.A_vrtd=b._originMediaStreamTrack.enabled&&
b._mediaStreamTrack.enabled?"0":"1"),b._player&&0<b._player.freezeTimeCounterList.length&&(a.A_vrft=Ra(e=b._player.freezeTimeCounterList).call(e,0,1)[0].toString()),a}(a,this.user.videoTrack):void 0;b&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.SUBSCRIBE_STATS,b));c&&xb(()=>this.emit(E.NEED_UPLOAD,Lb.SUBSCRIBE_STATS,c))}uploadSlowStats(a){}uploadRelatedStats(a,b){let c=!0===this.pc._statsFilter.videoIsReady,e=function(a,b,c){a=a.audioRecv[0];if(!a)return null;c=oe.isRemoteAudioFreeze(c);return{mediaType:"audio",
isAudioMute:!1,peerId:b,googJitterReceived:a.jitterMs.toString(),isFreeze:c,bytesReceived:a.bytes.toString(),packetsReceived:a.packets.toString(),packetsLost:a.packetsLost.toString(),frameReceived:a.receivedFrames.toString(),frameDropped:a.droppedFrames.toString()}}(a,this.getUserId(),this.user.audioTrack),f=function(a,b,c,e,f){b=b.videoRecv[0];if(!b)return null;a=oe.isRemoteVideoFreeze(f,b,e?e.videoRecv[0]:void 0)&&a;c={mediaType:"video",isVideoMute:!1,peerId:c,frameRateReceived:b.receivedFrame&&
b.receivedFrame.frameRate.toString(),frameRateDecoded:b.decodedFrame&&b.decodedFrame.frameRate.toString(),isFreeze:a,bytesReceived:b.bytes.toString(),packetsReceived:b.packets.toString(),packetsLost:b.packetsLost.toString()};return b.framesRateFirefox&&(c.frameRateDecoded=b.framesRateFirefox.toString(),c.frameRateReceived=b.framesRateFirefox.toString()),c}(c,a,this.getUserId(),b,this.user.videoTrack);e&&xb(()=>{this.emit(E.NEED_UPLOAD,Lb.SUBSCRIBE_RELATED_STATS,e)});f&&xb(()=>{this.emit(E.NEED_UPLOAD,
Lb.SUBSCRIBE_RELATED_STATS,f)})}emitOnTrackFromUnusedTracks(){if(this.subscribeOptions){var a=this.subscribeOptions.video;if(this.subscribeOptions.audio){var b;let a=U(b=this.unusedTracks).call(b,a=>"audio"===a.kind&&"live"===a.readyState);Gc(this.unusedTracks,a);a&&this.onTrack(a)}if(a){var c;a=U(c=this.unusedTracks).call(c,a=>"video"===a.kind&&"live"===a.readyState);Gc(this.unusedTracks,a);a&&this.onTrack(a)}}}async setSubscribeOptions(a){var b,c,e,f;if(a.audio!==this.subscribeOptions.audio||a.video!==
this.subscribeOptions.video){if("connecting"===this.connectionState)try{await this.createWaitConnectionConnectedPromise()}catch(h){throw new q(n.OPERATION_ABORTED,"can not update subscribe options, operation abort");}a.audio===this.subscribeOptions.audio&&a.video===this.subscribeOptions.video||(k.debug(m(b=m(c=m(e=m(f="[".concat(this.connectionId,"] update subscribe options [a: ")).call(f,this.subscribeOptions.audio,", v: ")).call(e,this.subscribeOptions.video,"] -> [a: ")).call(c,a.audio,", v: ")).call(b,
a.video,"]")),this.subscribeOptions=a,!a.audio&&this.user._audioTrack&&(this.unusedTracks.push(this.user._audioTrack._originMediaStreamTrack),this.user._audioTrack._destroy(),this.unbindTrackEvents(this.user._audioTrack),this.user._audioTrack=void 0),!a.video&&this.user._videoTrack&&(this.unusedTracks.push(this.user._videoTrack._originMediaStreamTrack),this.user._videoTrack._destroy(),this.unbindTrackEvents(this.user._videoTrack),this.user._videoTrack=void 0),this.emitOnTrackFromUnusedTracks())}}createPC(){this.pc=
new Fn({turnServer:this.joinInfo.turnServer});this.pc.onFirstAudioDecoded=()=>{this.user.audioTrack&&this.user.audioTrack.emit(je.FIRST_FRAME_DECODED);u.firstRemoteFrame(this.joinInfo.sid,Ta.FIRST_AUDIO_DECODE,sa.FIRST_AUDIO_DECODE,{peer:this.user._uintid,subscribeElapse:x()-this.startTime,subscribeRequestid:this.ID,p2pid:this.pc.ID})};this.pc.onFirstAudioReceived=()=>{u.firstRemoteFrame(this.joinInfo.sid,Ta.FIRST_AUDIO_RECEIVED,sa.FIRST_AUDIO_RECEIVED,{peer:this.user._uintid,subscribeElapse:x()-
this.startTime,subscribeRequestid:this.ID,p2pid:this.pc.ID})};this.pc.onFirstVideoDecoded=(a,b)=>{u.firstRemoteFrame(this.joinInfo.sid,Ta.FIRST_VIDEO_DECODE,sa.FIRST_VIDEO_DECODE,{peer:this.user._uintid,videowidth:a,videoheight:b,subscribeElapse:x()-this.startTime,subscribeRequestid:this.ID,p2pid:this.pc.ID})};this.pc.onFirstVideoReceived=()=>{u.firstRemoteFrame(this.joinInfo.sid,Ta.FIRST_VIDEO_RECEIVED,sa.FIRST_VIDEO_RECEIVED,{peer:this.user._uintid,subscribeElapse:x()-this.startTime,subscribeRequestid:this.ID,
p2pid:this.pc.ID})};this.updateICEPromise()}async closePC(a){return(this.pc.audioTrack&&this.pc.audioTrack.stop(),this.pc.videoTrack&&this.pc.videoTrack.stop(),this.pc.onTrack=void 0,this.pc.onICEConnectionStateChange=void 0,this.pc.close(),a)?!1:await Ia(this,E.NEED_UNSUB)}onPCDisconnected(a){u.subscribe(this.joinInfo.sid,{lts:this.startTime,succ:!1,video:this.subscribeOptions.video,audio:this.subscribeOptions.audio,peerid:this.user.uid,ec:a.code,subscribeRequestid:this.ID,p2pid:this.pc.ID})}bindTrackEvents(a){a instanceof
xe?a.addListener(G.GET_STATS,this.handleGetRemoteAudioStats):a instanceof we&&a.addListener(G.GET_STATS,this.handleGetRemoteVideoStats)}unbindTrackEvents(a){a instanceof xe?a.off(G.GET_STATS,this.handleGetRemoteAudioStats):a instanceof we&&a.off(G.GET_STATS,this.handleGetRemoteVideoStats)}}class xs extends Wa{constructor(a,b,c,e){super();this.reconnectMode="retry";this.commandReqId=this.reqId=0;this.handleWebSocketOpen=()=>{this.reconnectMode="retry";this.startPingPong()};this.handleWebSocketMessage=
a=>{if(a.data){a=JSON.parse(a.data);var b;a.requestId?this.emit(m(b="@".concat(a.requestId,"-")).call(b,a.sid),a):this.serviceMode===ua.INJECT?this.emit(Nb.INJECT_STREAM_STATUS,a):(u.workerEvent(this.spec.sid,{actionType:"status",serverCode:a.code,workerType:this.serviceMode===ua.TRANSCODE?1:2}),this.emit(Nb.PUBLISH_STREAM_STATUS,a))}};this.spec=b;this.token=a;this.serviceMode=e;this.websocket=new Dh("live-streaming",c);this.websocket.on(ea.CONNECTED,this.handleWebSocketOpen);this.websocket.on(ea.ON_MESSAGE,
this.handleWebSocketMessage);this.websocket.on(ea.REQUEST_NEW_URLS,(a,b)=>{Ia(this,Nb.REQUEST_NEW_ADDRESS).then(a).catch(b)});this.websocket.on(ea.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(a){return this.websocket.init(a)}async request(a,b,c,e){this.reqId+=1;"request"===a&&(this.commandReqId+=1);let f=this.commandReqId,h=this.reqId;if(!h||!this.websocket)throw new q(n.UNEXPECTED_ERROR);var k=wg({command:a,sdkVersion:"4.7.3"===ob?"0.0.1":ob,seq:h,requestId:h,allocate:c,
cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(x()/1E3)},b);if("closed"===this.websocket.state)throw new q(n.WS_DISCONNECT);let r=()=>new y((a,b)=>{this.websocket.once(ea.CLOSED,()=>b(new q(n.WS_ABORT)));this.websocket.once(ea.CONNECTED,a)});"connected"!==this.websocket.state&&await r();k.clientRequest&&(k.clientRequest.workerToken=this.token);let p=new y((a,b)=>{var c;const e=()=>{b(new q(n.WS_ABORT))};this.websocket.once(ea.RECONNECTING,
e);this.websocket.once(ea.CLOSED,e);this.once(m(c="@".concat(h,"-")).call(c,this.spec.sid),b=>{a(b)})});e&&u.workerEvent(this.spec.sid,wg({},e,{requestId:f,actionType:"request",payload:A(b.clientRequest),serverCode:0,code:0}));let w=x();this.websocket.sendMessage(k);k=null;try{k=await p}catch(X){if("closed"===this.websocket.state)throw X;return await r(),await this.request(a,b,c)}return e&&u.workerEvent(this.spec.sid,wg({},e,{requestId:f,actionType:"response",payload:A(k.serverResponse),serverCode:k.code,
success:200===k.code,responseTime:x()-w})),200!==k.code&&this.handleResponseError(k),k}tryNextAddress(){this.reconnectMode="tryNext";this.websocket.reconnect("tryNext")}close(){let a="4.7.3"===ob?"0.0.1":ob;this.reqId+=1;"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:a,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(x()/1E3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),
this.websocket.close(!1,!0)):this.websocket.close(!1);this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(a){switch(a.code){case oa.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void k.warning("live stream response already exists stream");case oa.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case oa.LIVE_STREAM_RESPONSE_BAD_STREAM:case oa.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return(new q(n.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:a.code})).throw();
case oa.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===a.serverResponse.command||"UninjectStream"===a.serverResponse.command)break;throw new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case oa.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return(new q(n.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:a.code})).throw();case oa.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:var b=new q(n.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(Nb.WARNING,
b,a.serverResponse.url);case oa.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:return b=new q(n.LIVE_STREAMING_WARN_FREQUENT_REQUEST),this.emit(Nb.WARNING,b,a.serverResponse.url);case oa.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case oa.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return(new q(n.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:a.code})).throw();case oa.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:return b=
new q(n.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT),this.emit(Nb.WARNING,b,a.serverResponse.url);case oa.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return(new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:a.code})).throw();case oa.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case oa.LIVE_STREAM_RESPONSE_WORKER_LOST:case oa.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===a.serverResponse.command||
"UninjectStream"===a.serverResponse.command)break;throw new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case oa.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===a.serverResponse.command||"UninjectStream"===a.serverResponse.command)break;if("UpdateTranscoding"===a.serverResponse.command||"ControlStream"===a.serverResponse.command)return(new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:a.code})).throw();throw new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,
"error fail send message",{retry:!0,changeAddress:!0});case oa.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return(new q(n.LIVE_STREAMING_CDN_ERROR,"",{code:a.code})).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer);this.pingpongTimer=window.setInterval(()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(Qe)},
6E3)}}class ys extends Wa{constructor(a,b=Ga,c=Ga){super();this.retryTimeout=1E4;this.streamingTasks=new ba;this.isStartingStreamingTask=!1;this.taskMutex=new sc("live-streaming");this.cancelToken=$b.CancelToken.source();this.injectConfig=xc({},Vq);this.injectLoopTimes=0;this.lastTaskId=1;this.statusError=new ba;this.spec=a;this.httpRetryConfig=c;this.wsRetryConfig=b}async setTranscodingConfig(a){var b;let c=xc({},Uq,{},a);var e,f;66!==c.videoCodecProfile&&77!==c.videoCodecProfile&&100!==c.videoCodecProfile&&
(k.debug(m(e="[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ")).call(e,c.videoCodecProfile," -> 100")),c.videoCodecProfile=100);(c.transcodingUsers||(c.transcodingUsers=c.userConfigs),c.transcodingUsers)&&(c.transcodingUsers=z(f=c.transcodingUsers).call(f,a=>xc({},Tq,{},a,{zOrder:a.zOrder?a.zOrder+1:1})));!function(a){var b,c;null==a.width||ha(a.width,"config.width",0,1E4);null==a.height||ha(a.height,"config.height",0,1E4);null==a.videoBitrate||ha(a.videoBitrate,
"config.videoBitrate",1,1E6);null==a.videoFrameRate||ha(a.videoFrameRate,"config.videoFrameRate");null==a.lowLatency||Le(a.lowLatency,"config.lowLatency");null==a.audioSampleRate||fb(a.audioSampleRate,"config.audioSampleRate",[32E3,44100,48E3]);null==a.audioBitrate||ha(a.audioBitrate,"config.audioBitrate",1,128);null==a.audioChannels||fb(a.audioChannels,"config.audioChannels",[1,2,3,4,5]);null==a.videoGop||ha(a.videoGop,"config.videoGop");null==a.videoCodecProfile||fb(a.videoCodecProfile,"config.videoCodecProfile",
[66,77,100]);null==a.userCount||ha(a.userCount,"config.userCount",0,17);null==a.backgroundColor||ha(a.backgroundColor,"config.backgroundColor",0,16777215);null==a.userConfigExtraInfo||Sa(a.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1);a.transcodingUsers&&null!=a.transcodingUsers&&(Xf(a.transcodingUsers,"config.transcodingUsers"),t(b=a.transcodingUsers).call(b,(a,b)=>{Zf(a.uid);null==a.x||ha(a.x,"transcodingUser[".concat(b,"].x"),0,1E4);null==a.y||ha(a.y,"transcodingUser[".concat(b,"].y"),
0,1E4);null==a.width||ha(a.width,"transcodingUser[".concat(b,"].width"),0,1E4);null==a.height||ha(a.height,"transcodingUser[".concat(b,"].height"),0,1E4);null==a.zOrder||ha(a.zOrder-1,"transcodingUser[".concat(b,"].zOrder"),0,100);null==a.alpha||ha(a.alpha,"transcodingUser[".concat(b,"].alpha"),0,1,!1)}));null==a.watermark||$f(a.watermark,"watermark");null==a.backgroundImage||$f(a.backgroundImage,"backgroundImage");a.images&&null!=a.images&&(Xf(a.images,"config.images"),t(c=a.images).call(c,(a,b)=>
{$f(a,"images[".concat(b,"]"))}))}(c);a=[];var h,l;c.images&&a.push(...z(h=c.images).call(h,a=>xc({},mh,{},a,{zOrder:255})));(c.backgroundImage&&(a.push(xc({},mh,{},c.backgroundImage,{zOrder:0})),delete c.backgroundImage),c.watermark&&(a.push(xc({},mh,{},c.watermark,{zOrder:255})),delete c.watermark),c.images=a,c.transcodingUsers)&&(c.userConfigs=z(l=c.transcodingUsers).call(l,a=>xc({},a)),c.userCount=c.transcodingUsers.length,delete c.transcodingUsers);h=z(b=c.userConfigs||[]).call(b,a=>"number"==
typeof a.uid?y.resolve(a.uid):ng(a.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));b=await y.all(h);if(t(b).call(b,(a,b)=>{c.userConfigs&&c.userConfigs[b]&&(c.userConfigs[b].uid=a)}),this.transcodingConfig=c,this.connection)try{var r,p,n;let a=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:z(r=Ub(Uc(p=this.streamingTasks).call(p))).call(r,a=>
a.taskId).join("#")});k.debug(m(n="[".concat(this.spec.clientId,"] update live transcoding config success, code: ")).call(n,a.code,", config:"),A(this.transcodingConfig))}catch(K){var q;if(!K.data||!K.data.retry)throw K;K.data.changeAddress&&this.connection.tryNextAddress();t(q=this.streamingTasks).call(q,a=>{k.warning("[".concat(this.spec.clientId,"] live streaming receive error"),K.toString(),"try to republish",a.url);this.startLiveStreamingTask(a.url,a.mode,K).then(()=>{var b;k.debug(m(b="[".concat(this.spec.clientId,
"] live streaming republish ")).call(b,a.url," success"))}).catch(b=>{k.error("[".concat(this.spec.clientId,"] live streaming republish failed"),a.url,b.toString());this.onLiveStreamError&&this.onLiveStreamError(a.url,b)})})}}setInjectStreamConfig(a,b){this.injectConfig=Ya({},this.injectConfig,a);this.injectLoopTimes=b}async startLiveStreamingTask(a,b,c){var e,f,h,l;if(U(e=Ub(Uc(f=this.streamingTasks).call(f))).call(e,a=>a.mode===ua.INJECT)&&b===ua.INJECT)return(new q(n.LIVE_STREAMING_TASK_CONFLICT,
"inject stream over limit")).throw();if(!this.transcodingConfig&&b===ua.TRANSCODE)throw new q(n.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");e={command:"PublishStream",ts:x(),url:a,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};k.debug(m(h=m(l="[".concat(this.spec.clientId,"] start live streaming ")).call(l,a,", mode: ")).call(h,b));h=await this.taskMutex.lock();if(!this.connection&&c)return void h();if(this.streamingTasks.get(a)&&
!c)return h(),(new q(n.LIVE_STREAMING_TASK_CONFLICT)).throw();try{this.connection||(this.connection=await this.connect(b))}catch(p){throw h(),p;}switch(b){case ua.TRANSCODE:e.transcodingConfig=xc({},this.transcodingConfig);break;case ua.INJECT:e={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:x(),url:a,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(e.vid=this.uapResponse.vid);this.isStartingStreamingTask=!0;l=this.lastTaskId++;
try{var r;let f=new y((b,e)=>{jb(this.retryTimeout).then(()=>{if(c)return e(c);const b=this.statusError.get(a);return b?(this.statusError.delete(a),e(b)):void 0})}),n=await y.race([this.connection.request("request",{clientRequest:e},!0,{url:a,command:"PublishStream",workerType:b===ua.TRANSCODE?1:2,requestByUser:!c,tid:l.toString()}),f]);this.isStartingStreamingTask=!1;k.debug(m(r="[".concat(this.spec.clientId,"] live streaming started, code: ")).call(r,n.code));this.streamingTasks.set(a,{clientRequest:e,
mode:b,url:a,taskId:l});h()}catch(p){if(h(),this.isStartingStreamingTask=!1,!p.data||!p.data.retry||c)throw p;return p.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(a,b,p)):await this.startLiveStreamingTask(a,b,p)}}stopLiveStreamingTask(a){return new y((b,c)=>{let e=this.streamingTasks.get(a);if(!e||!this.connection)return(new q(n.UNEXPECTED_ERROR,"can not find streaming task to stop")).throw();let f=e.mode;e.abortTask=()=>{k.debug("[".concat(this.spec.clientId,
"] stop live streaming success(worker exception)"));this.streamingTasks.delete(a);b()};this.connection.request("request",{clientRequest:{command:f===ua.INJECT?"UninjectStream":"UnpublishStream",url:e.url}},!1,{url:a,command:"UnPublishStream",workerType:f===ua.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(c=>{var e;k.debug(m(e="[".concat(this.spec.clientId,"] stop live streaming success, code: ")).call(e,c.code));this.streamingTasks.delete(a);0===this.streamingTasks.size&&
f!==ua.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0);b();f===ua.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(5,this.spec.uid,a)}).catch(c)})}async controlInjectStream(a,b,c,e){let f=this.streamingTasks.get(a);if(!f||!this.connection||f.mode!==ua.INJECT)throw new q(n.INVALID_OPERATION,"can not find inject stream task to control");return(await this.connection.request("request",{clientRequest:{command:"ControlStream",url:a,control:b,audioVolume:c,position:e}})).serverResponse}resetAllTask(){var a;
let b=Ub(Uc(a=this.streamingTasks).call(a));this.terminate();for(let a of b)this.startLiveStreamingTask(a.url,a.mode).catch(b=>{this.onLiveStreamError&&this.onLiveStreamError(a.url,b)})}terminate(){this.cancelToken&&this.cancelToken.cancel();this.streamingTasks=new ba;this.isStartingStreamingTask=!1;this.statusError=new ba;this.cancelToken=$b.CancelToken.source();this.uapResponse=void 0;this.connection&&this.connection.close();this.connection=void 0}async connect(a){if(this.connection)throw new q(n.UNEXPECTED_ERROR,
"live streaming connection has already connected");let b=await Ia(this,Ad.REQUEST_WORKER_MANAGER_LIST,a);return this.uapResponse=b,this.connection=new xs(b.workerToken,this.spec,this.wsRetryConfig,a),this.connection.on(Nb.WARNING,(a,b)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(b,a)),this.connection.on(Nb.PUBLISH_STREAM_STATUS,a=>this.handlePublishStreamServer(a)),this.connection.on(Nb.INJECT_STREAM_STATUS,a=>this.handleInjectStreamServerStatus(a)),this.connection.on(Nb.REQUEST_NEW_ADDRESS,
(b,e)=>{if(!this.connection)return e(new q(n.UNEXPECTED_ERROR,"can not get new live streaming address list"));Ia(this,Ad.REQUEST_WORKER_MANAGER_LIST,a).then(a=>{this.uapResponse=a;b(a.addressList)}).catch(e)}),await this.connection.init(b.addressList),this.connection}handlePublishStreamServer(a){var b=a.serverStatus&&a.serverStatus.url||"empty_url";let c=this.streamingTasks.get(b),e=a.reason;switch(a.code){case oa.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case oa.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:a=
new q(n.LIVE_STREAMING_CDN_ERROR,"",{code:a.code});if(c)return k.error(a.toString()),this.onLiveStreamError&&this.onLiveStreamError(b,a);if(!this.isStartingStreamingTask)break;this.statusError.set(b,a);case oa.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:return a=new q(n.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,e),this.onLiveStreamWarning&&this.onLiveStreamWarning(b,a);case oa.LIVE_STREAM_RESPONSE_WORKER_LOST:case oa.LIVE_STREAM_RESPONSE_WORKER_QUIT:var f;if(this.connection){this.connection.tryNextAddress();
b=Ub(Uc(f=this.streamingTasks).call(f));for(let c of b)c.abortTask?c.abortTask():(k.warning("[".concat(this.spec.clientId,"] publish stream status code"),a.code,"try to republish",c.url),this.startLiveStreamingTask(c.url,c.mode,new q(n.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:a.code})).then(()=>{k.debug("[".concat(this.spec.clientId,"] republish live stream success"),c.url)}).catch(a=>{k.error(a.toString());this.onLiveStreamError&&this.onLiveStreamError(c.url,a)}))}}}handleInjectStreamServerStatus(a){let b=
Number(a.uid),c=a.serverStatus&&a.serverStatus.url;switch(a.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(0,b,c));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(1,b,c),void this.streamingTasks.delete(c);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(2,b,c),void this.streamingTasks.delete(c);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(10,b,c),void this.streamingTasks.delete(c);case 499:return this.onInjectStatusChange&&
this.onInjectStatusChange(3,b,c),void this.streamingTasks.delete(c);default:return void k.debug("inject stream server status",a)}}hasUrl(a){return this.streamingTasks.has(a)}}class Yj{constructor(){this.destChannelMediaInfos=new ba}setSrcChannelInfo(a){$i(a);this.srcChannelMediaInfo=a}addDestChannelInfo(a){$i(a);this.destChannelMediaInfos.set(a.channelName,a)}removeDestChannelInfo(a){Yf(a);this.destChannelMediaInfos.delete(a)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}
class zs extends Wa{constructor(a,b,c){super();this.requestId=1;this.onOpen=()=>{this.emit("open");this.startHeartBeatCheck()};this.onClose=a=>{this.emit("close");this.dispose()};this.onMessage=a=>{a=JSON.parse(a.data);if(!a||"serverResponse"!==a.command||!a.requestId)return a&&"serverStatus"===a.command&&a.serverStatus&&a.serverStatus.command?(this.emit("status",a.serverStatus),void this.emit(a.serverStatus.command,a.serverStatus)):void 0;this.emit("req_".concat(a.requestId),a)};this.joinInfo=a;
this.clientId=b;this.ws=new Dh("cross-channel-".concat(this.clientId),c);this.ws.on(ea.RECONNECTING,()=>{this.ws.reconnectMode="retry";this.emit("reconnecting")});this.ws.on(ea.CONNECTED,this.onOpen);this.ws.on(ea.ON_MESSAGE,this.onMessage);this.ws.on(ea.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(a){let b=this.requestId++;return a.requestId=b,a.seq=b,this.ws.sendMessage(a),b}waitStatus(a){return new y((b,c)=>{let e=window.setTimeout(()=>{c(new q(n.TIMEOUT,"wait status timeout, status: ".concat(a)))},
5E3);this.once(a,f=>{window.clearTimeout(e);f.state&&0!==f.state?c(new q(n.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(a))):b(void 0)});this.once("dispose",()=>{window.clearTimeout(e);c(new q(n.WS_ABORT))})})}async request(a){if("closed"===this.ws.state)throw new q(n.WS_DISCONNECT);let b=()=>new y((a,b)=>{this.ws.once(ea.CLOSED,()=>b(new q(n.WS_ABORT)));this.ws.once(ea.CONNECTED,a)});"connected"!==this.ws.state&&await b();let c=this.sendMessage(a);a=await new y((a,b)=>{const e=
()=>{b(new q(n.WS_ABORT))};this.ws.once(ea.RECONNECTING,e);this.ws.once(ea.CLOSED,e);this.once("req_".concat(c),a);jb(3E3).then(()=>{this.removeAllListeners("req_".concat(c));this.ws.off(ea.RECONNECTING,e);this.ws.off(ea.CLOSED,e);b(new q(n.TIMEOUT,"cross channel ws request timeout"))})});if(!a||200!==a.code)throw new q(n.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(A(a)));return a}async connect(a){this.ws.removeAllListeners(ea.REQUEST_NEW_URLS);this.ws.on(ea.REQUEST_NEW_URLS,b=>{b(a)});
await this.ws.init(a)}dispose(){this.clearHeartBeatCheck();this.emit("dispose");this.removeAllListeners();this.ws.close()}sendPing(a){let b=this.requestId++;return a.requestId=b,this.ws.sendMessage(a),b}startHeartBeatCheck(){this.heartBeatTimer=window.setInterval(()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})},3E3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer);
this.heartBeatTimer=void 0}}class As extends Wa{constructor(a,b,c,e){super();this.cancelToken=$b.CancelToken.source();this.requestId=0;this._state="RELAY_STATE_IDLE";this.errorCode="RELAY_OK";this.onStatus=a=>{var b;k.debug(m(b="[".concat(this.clientId,"] ChannelMediaStatus: ")).call(b,A(a)));a&&a.command&&("onAudioPacketReceived"===a.command&&this.emit("event","PACKET_RECEIVED_AUDIO_FROM_SRC"),"onVideoPacketReceived"===a.command&&this.emit("event","PACKET_RECEIVED_VIDEO_FROM_SRC"),"onSrcTokenPrivilegeDidExpire"===
a.command&&(this.errorCode="SRC_TOKEN_EXPIRED",this.state="RELAY_STATE_FAILURE"),"onDestTokenPrivilegeDidExpire"===a.command&&(this.errorCode="DEST_TOKEN_EXPIRED",this.state="RELAY_STATE_FAILURE"))};this.onReconnect=async()=>{k.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting"));this.emit("event","NETWORK_DISCONNECTED");this.state="RELAY_STATE_IDLE";this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(a=>{"RELAY_STATE_IDLE"!==this.state&&
(k.error("auto restart channel media relay failed",a.toString()),this.errorCode="SERVER_CONNECTION_LOST",this.state="RELAY_STATE_FAILURE")})};this.joinInfo=a;this.clientId=b;this.signal=new zs(this.joinInfo,this.clientId,c);this.httpRetryConfig=e}set state(a){a!==this._state&&("RELAY_STATE_FAILURE"!==a&&(this.errorCode="RELAY_OK"),this.emit("state",a,this.errorCode),this._state=a)}get state(){return this._state}async startChannelMediaRelay(a){if("RELAY_STATE_IDLE"!==this.state)throw new q(n.INVALID_OPERATION);
this.state="RELAY_STATE_CONNECTING";await this.connect();k.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(a)}catch(b){if(b.data&&b.data.serverResponse&&"SetSourceChannel"===b.data.serverResponse.command)throw new q(n.CROSS_CHANNEL_FAILED_JOIN_SRC);if(b.data&&b.data.serverResponse&&"SetDestChannelStatus"===b.serverResponse.command)throw new q(n.CROSS_CHANNEL_FAILED_JOIN_DEST);if(b.data&&b.data.serverResponse&&"StartPacketTransfer"===
b.serverResponse.command)throw new q(n.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw b;}this.prevChannelMediaConfig=a}async updateChannelMediaRelay(a){if("RELAY_STATE_RUNNING"!==this.state)throw new q(n.INVALID_OPERATION);await this.sendUpdateMessage(a);this.prevChannelMediaConfig=a}async stopChannelMediaRelay(){await this.sendStopRelayMessage();k.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success"));this.state="RELAY_STATE_IDLE";this.dispose()}dispose(){k.debug("[".concat(this.clientId,
"] disposeChannelMediaRelay"));this.cancelToken.cancel();this.cancelToken=$b.CancelToken.source();this.state="RELAY_STATE_IDLE";this.emit("dispose");this.signal.dispose();this.prevChannelMediaConfig=void 0}async connect(){let a=await xo(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=a.workerToken;await this.signal.connect(a.addressList);this.emit("event","NETWORK_CONNECTED");this.signal.on("status",this.onStatus);this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(a){var b=
this.genMessage(Va.StopPacketTransfer);await this.signal.request(b);await this.signal.waitStatus("Normal Quit");k.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));b=this.genMessage(Va.SetSdkProfile,a);await this.signal.request(b);k.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));b=this.genMessage(Va.SetSourceChannel,a);await this.signal.request(b);await this.signal.waitStatus("SetSourceChannelStatus");this.emit("event","PACKET_JOINED_SRC_CHANNEL");
k.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));b=this.genMessage(Va.SetSourceUserId,a);await this.signal.request(b);k.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));b=this.genMessage(Va.SetDestChannel,a);await this.signal.request(b);await this.signal.waitStatus("SetDestChannelStatus");this.emit("event","PACKET_JOINED_DEST_CHANNEL");k.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));a=
this.genMessage(Va.StartPacketTransfer,a);await this.signal.request(a);this.emit("event","PACKET_SENT_TO_DEST_CHANNEL");this.state="RELAY_STATE_RUNNING";k.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success"))}async sendUpdateMessage(a){a=this.genMessage(Va.UpdateDestChannel,a);await this.signal.request(a);this.emit("event","PACKET_UPDATE_DEST_CHANNEL");k.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){let a=
this.genMessage(Va.StopPacketTransfer);await this.signal.request(a);k.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(a,b){let c=[],e=[],f=[];this.requestId+=1;let h={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:ob,sid:this.joinInfo.sid,ts:x(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.7.3"===h.sdkVersion&&(h.sdkVersion="0.0.1");let k=null,m=null;switch(a){case Va.SetSdkProfile:return h.clientRequest=
{command:"SetSdkProfile",type:"multi_channel"},h;case Va.SetSourceChannel:if(m=b&&b.getSrcChannelMediaInfo(),!m)throw new q(n.UNEXPECTED_ERROR,"can not find source config");return h.clientRequest={command:"SetSourceChannel",uid:"0",channelName:m.channelName,token:m.token||this.joinInfo.appId},h;case Va.SetSourceUserId:if(m=b&&b.getSrcChannelMediaInfo(),!m)throw new q(n.UNEXPECTED_ERROR,"can not find source config");return h.clientRequest={command:"SetSourceUserId",uid:m.uid+""},h;case Va.SetDestChannel:if(k=
b&&b.getDestChannelMediaInfo(),!k)throw new q(n.UNEXPECTED_ERROR,"can not find dest config");return t(k).call(k,a=>{c.push(a.channelName);e.push(a.uid+"");f.push(a.token||this.joinInfo.appId)}),h.clientRequest={command:"SetDestChannel",channelName:c,uid:e,token:f},h;case Va.StartPacketTransfer:return h.clientRequest={command:"StartPacketTransfer"},h;case Va.Reconnect:return h.clientRequest={command:"Reconnect"},h;case Va.StopPacketTransfer:return h.clientRequest={command:"StopPacketTransfer"},h;case Va.UpdateDestChannel:if(k=
b&&b.getDestChannelMediaInfo(),!k)throw new q(n.UNEXPECTED_ERROR,"can not find dest config");return t(k).call(k,a=>{c.push(a.channelName);e.push(a.uid+"");f.push(a.token||this.joinInfo.appId)}),h.clientRequest={command:"UpdateDestChannel",channelName:c,uid:e,token:f},h}return h}}class Bs{constructor(a,b){this._trust_stream_added_state_=this._trust_video_mute_state_=this._trust_audio_mute_state_=this._trust_video_enabled_state_=this._trust_audio_enabled_state_=this._trust_in_room_=!0;this._video_muted_=
this._audio_muted_=!1;this._video_enabled_=this._audio_enabled_=!0;this._video_added_=this._audio_added_=!1;this.uid=a;this._uintid=b}get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio)return this._audioTrack}get videoTrack(){if(this.hasVideo)return this._videoTrack}}let Cs=async a=>{var b=ig("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB");
b=await window.crypto.subtle.importKey("spki",b,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]);a=(c=a,(new TextEncoder).encode(c));var c;c=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},b,a);return Re(new Uint8Array(c))},Lf;class Ds{constructor(a,b){var c;this.name=a;this.time=performance.now();this.sequence=J(c=Wq[b]).call(c,a)}setElapse(a){this.elapse=a}}let Es=new ba;class Fs{constructor(a,b){this.records=[];this._id=a;this._group=b;this._localTimeStamp=x();this._performanceTimeStamp=performance.now()}checkPoint(a){var b;
let c=new Ds(a,this._group);-1===c.sequence&&k.warning("[".concat(this._id,"] check point record failed, cannot get the sequence"));this.records.push(c);(a=U(b=this.records).call(b,a=>a.sequence===c.sequence-1))&&c.setElapse(c.time-a.time)}getRecord(a){var b;return U(b=this.records).call(b,b=>b&&b.name===a)}resetRecords(){this.records.length=0}}var ye=function(a,b,c,e){var f,h=arguments.length,k=3>h?b:null===e?e=ca(b,c):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)k=Reflect.decorate(a,
b,c,e);else for(var m=a.length-1;0<=m;m--)(f=a[m])&&(k=(3>h?f(k):3<h?f(b,c,k):f(b,c))||k);return 3<h&&k&&Q(b,c,k),k},mb=function(a,b){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(a,b)};class Gd extends Wa{constructor(a){var b,c,e,f;let h;if(super(),this._users=[],this._sessionId=null,this._bindEnabledTracks=[],this._leaveMutex=new sc("client-leave"),this._publishMutex=new sc("client-publish"),this._subscribeMutex=new ba,this._remoteStream=new ba,this._encryptionMode=
"none",this._encryptionSecret=null,this._encryptionSalt=null,this._turnServer={servers:[],mode:"auto"},this._cloudProxyServerMode="disabled",this._isDualStreamEnabled=!1,this._streamFallbackTypeCacheMap=new ba,this._remoteStreamTypeCacheMap=new ba,this._axiosCancelSource=$b.CancelToken.source(),this._networkQualitySensitivity="normal",this._useLocalAccessPoint=!1,this._handleLocalTrackEnable=(a,b,c)=>{this.publish(a,!1).then(b).catch(c)},this._handleLocalTrackDisable=(a,b,c)=>{this.unpublish(a,!1).then(b).catch(c)},
this._handleUserOnline=a=>{var b;this.isStringUID&&"string"!=typeof a.uid&&k.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));let c=U(b=this._users).call(b,b=>b.uid===a.uid);c?c._trust_in_room_=!0:(b=new Bs(a.uid,a.uint_id||a.uid),this._users.push(b),k.debug("[".concat(this._clientId,"] user online"),a.uid),this.emit(R.USER_JOINED,b))},this._handleUserOffline=a=>{var b;let c=U(b=this._users).call(b,b=>b.uid===a.uid);c&&(this._handleRemoveStream(a),Gc(this._users,c),this._remoteStreamTypeCacheMap.delete(c.uid),
this._streamFallbackTypeCacheMap.delete(c.uid),k.debug("[".concat(this._clientId,"] user offline"),a.uid,"reason:",a.reason),this.emit(R.USER_LEAVED,c,a.reason))},this._handleAddAudioOrVideoStream=(a,b,c)=>{var e,f,h;let l=U(e=this._users).call(e,a=>a.uid===b);if(!l)return void k.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));k.debug(m(f=m(h="[".concat(this._clientId,"] stream added with uid ")).call(h,b,", type ")).call(f,a));e="audio"===a?l.hasAudio:l.hasVideo;var p,
n;(l._uintid||(l._uintid=c||b),l._trust_stream_added_state_=!0,"audio"===a?l._audio_added_=!0:l._video_added_=!0,("audio"===a?l.hasAudio:l.hasVideo)&&!e)&&(k.info(m(p=m(n="[".concat(this._clientId,"] remote user ")).call(n,l.uid," published ")).call(p,a)),this.emit(R.USER_PUBLISHED,l,a));"video"===a?u.onGatewayStream(this._sessionId,Ta.ON_ADD_VIDEO_STREAM,sa.ON_ADD_VIDEO_STREAM,{peer:c||b}):u.onGatewayStream(this._sessionId,Ta.ON_ADD_AUDIO_STREAM,sa.ON_ADD_AUDIO_STREAM,{peer:c||b});(a=this._remoteStream.get(b))&&
a.readyToReconnect&&"connecting"===a.connectionState&&a.reconnectPC().catch(a=>{k.error("[".concat(this._clientId,"] resubscribe error"),a.toString())})},this._handleRemoveStream=a=>{var b,c;let e=U(b=this._users).call(b,b=>b.uid===a.uid);if(!e)return void k.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));k.debug(m(c="[".concat(this._clientId,"] stream removed with uid ")).call(c,a.uid));b=()=>{};e.hasAudio&&e.hasVideo?b=()=>{var a,b;k.info(m(a="[".concat(this._clientId,
"] remote user ")).call(a,e.uid," unpublished audio track"));this.emit(R.USER_UNPUBLISHED,e,"audio");k.info(m(b="[".concat(this._clientId,"] remote user ")).call(b,e.uid," unpublished video track"));this.emit(R.USER_UNPUBLISHED,e,"video")}:e.hasVideo?b=()=>{var a;k.info(m(a="[".concat(this._clientId,"] remote user ")).call(a,e.uid," unpublished video track"));this.emit(R.USER_UNPUBLISHED,e,"video")}:e.hasAudio&&(b=()=>{var a;k.info(m(a="[".concat(this._clientId,"] remote user ")).call(a,e.uid," unpublished audio track"));
this.emit(R.USER_UNPUBLISHED,e,"audio")});e._trust_stream_added_state_=!0;e._audio_added_=!1;e._video_added_=!1;(c=this._remoteStream.get(e.uid))&&(c.closeP2PConnection(),this._remoteStream.delete(e.uid));u.onGatewayStream(this._sessionId,Ta.ON_REMOVE_STREAM,sa.ON_REMOVE_STREAM,{peer:a.uint_id||a.uid});b()},this._handleSetStreamLocalEnable=(a,b,c)=>{var e,f,h,l,p,n;let r=U(e=this._users).call(e,a=>a.uid===b);if(!r)return void k.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));
k.debug(m(f=m(h=m(l="[".concat(this._clientId,"] local ")).call(l,a," ")).call(h,c?"enabled":"disabled"," with uid ")).call(f,b));e="audio"===a?r.hasAudio:r.hasVideo;if("audio"===a){r._trust_audio_enabled_state_=!0;var q=r._audio_enabled_;if(r._audio_enabled_=c,r._audio_enabled_===q)return;var t,w;c=r._audio_enabled_?"enable-local-audio":"disable-local-audio";k.debug(m(t=m(w="[".concat(this._clientId,"] user-info-updated, uid: ")).call(w,b,", msg: ")).call(t,c));this.emit(R.USER_INFO_UPDATED,b,c)}else{r._trust_video_enabled_state_=
!0;t=r._video_enabled_;if(r._video_enabled_=c,r._video_enabled_===t)return;var u;c=r._video_enabled_?"enable-local-video":"disable-local-video";k.debug(m(q=m(u="[".concat(this._clientId,"] user-info-update, uid: ")).call(u,b,", msg: ")).call(q,c));this.emit(R.USER_INFO_UPDATED,b,c)}c="audio"===a?r.hasAudio:r.hasVideo;if(e!==c){var v,x;if(!e&&c)return k.info(m(v=m(x="[".concat(this._clientId,"] remote user ")).call(x,b," published ")).call(v,a)),void this.emit(R.USER_PUBLISHED,r,a);if(v=this._remoteStream.get(b))x=
jd({},v.subscribeOptions),x.audio=!!r.hasAudio&&x.audio,x.video=!!r.hasVideo&&x.video,x.audio||x.video?v.setSubscribeOptions(x):(v.closeP2PConnection().catch(a=>{k.warning("close sub pc error",a)}),this._remoteStream.delete(r.uid));k.info(m(p=m(n="[".concat(this._clientId,"] remote user ")).call(n,r.uid," unpublished ")).call(p,a));this.emit(R.USER_UNPUBLISHED,r,a)}},this._handleMuteStream=(a,b,c)=>{var e,f,h;k.debug("[".concat(this._clientId,"] receive mute message"),a,b,c);let l=U(e=this._users).call(e,
b=>b.uid===a);var p;if(!l)return void k.warning(m(p="[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ")).call(p,a));e="audio"===b?l.hasAudio:l.hasVideo;if("audio"===b){l._trust_audio_mute_state_=!0;var n=l._audio_muted_;if(l._audio_muted_=c,l._audio_muted_===n)return;var r,q;c=l._audio_muted_?"mute-audio":"unmute-audio";k.debug(m(r=m(q="[".concat(this._clientId,"] user-info-update, uid: ")).call(q,a,", msg: ")).call(r,c));this.emit(R.USER_INFO_UPDATED,a,c)}else{l._trust_video_mute_state_=
!0;r=l._video_muted_;if(l._video_muted_=c,l._video_muted_===r)return;var t;c=l._video_muted_?"mute-video":"unmute-video";k.debug(m(n=m(t="[".concat(this._clientId,"] user-info-update, uid: ")).call(t,a,", msg: ")).call(n,c));this.emit(R.USER_INFO_UPDATED,a,c)}c="audio"===b?l.hasAudio:l.hasVideo;if(e!==c){var w,u;if(!e&&c)return k.info(m(w=m(u="[".concat(this._clientId,"] remote user ")).call(u,a," published ")).call(w,b)),void this.emit(R.USER_PUBLISHED,l,b);if(w=this._remoteStream.get(a))u=jd({},
w.subscribeOptions),u.audio=!!l.hasAudio&&u.audio,u.video=!!l.hasVideo&&u.video,"video"===b&&w.pc._statsFilter.setVideoIsReady(!1),u.audio||u.video?w.setSubscribeOptions(u):(w.closeP2PConnection().catch(a=>{k.warning("close sub pc error",a)}),this._remoteStream.delete(l.uid));k.info(m(f=m(h="[".concat(this._clientId,"] remote user ")).call(h,a," unpublished ")).call(f,b));this.emit(R.USER_UNPUBLISHED,l,b)}},this._handleP2PLost=a=>{k.debug("[".concat(this._clientId,"] receive p2p lost"),a);let b=null;
if(this._highStream&&this._highStream.pc.ID===a.p2pid)b=this._highStream;else if(this._lowStream&&this._lowStream.pc.ID===a.p2pid)b=this._lowStream;else{var c;t(c=this._remoteStream).call(c,c=>{c.pc.ID===a.p2pid&&(b=c)})}b?b.emit(E.GATEWAY_P2P_LOST,a.p2pid):k.warning("P2PLost stream not found",a)},this._handleTokenWillExpire=()=>{k.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire"));this.emit(R.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)},this._handleBeforeUnload=a=>{void 0!==a.returnValue&&
""!==a.returnValue||(this.leave(),k.info("[".concat(this._clientId,"] auto leave onbeforeunload")))},this._handleUpdateNetworkQuality=()=>{var a;if("normal"!==this._networkQualitySensitivity){if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.emit(R.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});var b={downlinkNetworkQuality:0,uplinkNetworkQuality:0};this._highStream&&!this._highStream.detecting&&(b.uplinkNetworkQuality=this._highStream.getNetworkQuality());
var c=0;t(a=this._remoteStream).call(a,a=>c+=a.getNetworkQuality());0<this._remoteStream.size&&(b.downlinkNetworkQuality=Math.round(c/this._remoteStream.size));this.emit(R.NETWORK_QUALITY,b)}},this._codec=a.codec,this._mode=a.mode,a.proxyServer&&(this._proxyServer=a.proxyServer,u.setProxyServer(this._proxyServer),k.setProxyServer(this._proxyServer)),a.turnServer&&(this._turnServer=jd({},this._turnServer,{mode:"manual"},a.turnServer)),this._clientId=va(5,"client-"),k.info(m(b=m(c=m(e=m(f="[".concat(this._clientId,
"] Initializing AgoraRTC client v")).call(f,ob," build: ")).call(e,"v4.7.3-0-g0eb931c7(11/16/2021, 7:46:22 PM)",", mode: ")).call(c,this._mode,", codec: ")).call(b,this._codec)),this._performanceRecorder=function(a,b){b=new Fs(a,b);return Es.set(a,b),b}(this._clientId,"join"),a.clientRoleOptions)try{Zi(a.clientRoleOptions),h=Ya({},a.clientRoleOptions)}catch(r){var l;k.warning(m(l="[".concat(this._clientId,"] ")).call(l,r.toString()))}this._statsCollector=new oe(this._clientId);this._statsCollector.onStatsException=
(a,b,c)=>{var e,f,h;k.debug(m(e=m(f=m(h="[".concat(this._clientId,"] receive exception msg, code: ")).call(h,a,", msg: ")).call(f,b,", uid: ")).call(e,c));this.emit(R.EXCEPTION,{code:a,msg:b,uid:c})};this._statsCollector.onUploadPublishDuration=(a,b,c,e)=>{var f;let h=U(f=this._users).call(f,b=>b.uid===a);h&&u.peerPublishStatus(this._sessionId,{subscribeElapse:e,audioPublishDuration:b,videoPublishDuration:c,peer:h._uintid})};this._gateway=new Er({clientId:this._clientId,mode:this._mode,codec:this._codec,
websocketRetryConfig:a.websocketRetryConfig||Ga,httpRetryConfig:a.httpRetryConfig||Ga,forceWaitGatewayResponse:void 0===a.forceWaitGatewayResponse||a.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:a.role,clientRoleOptions:h});this._config=a;this._configDistribute=new ds;this._handleGatewayEvents()}get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._highStream?this._highStream.getAllTracks():[]}get uid(){return this._uid}get channelName(){return this._channelName}get isStringUID(){return!!this._joinInfo&&
!!this._joinInfo.stringUid}async join(a,b,c,e,f){var h;this._performanceRecorder.checkPoint("startJoin");var l="HTTPS"===(Lf||Lf||(Lf=(window.location.protocol.split(":")[0]||"").toUpperCase(),Lf));let r=void 0!==window.isSecureContext?window.isSecureContext:"Browser Not Support",p=()=>{k.warning("The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser")};
void 0!==window.isSecureContext?window.isSecureContext||p():l||p();l=u.reportApiInvoke(this._sessionId,{name:D.JOIN,options:[a,b,c,e],states:{isHttps:l,isSecureContext:r},tag:C.TRACER});try{if(!c&&null!==c)throw new q(n.INVALID_PARAMS,"Invalid token: ".concat(c,". If you don not use token, set it to null"));c&&Sa(c,"token",1,2047);Sa(a,"appid",1,2047);Yf(b);e&&Zf(e);f&&Sa(f,"optionalInfo",1,2047)}catch(B){throw l.onError(B),B;}if(k.info(m(h="[".concat(this._clientId,"] start join channel ")).call(h,
b)),this._leaveMutex.isLocked)k.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),k.debug("[".concat(this._clientId,"] join: continue"));if("DISCONNECTED"!==this.connectionState)throw a=new q(n.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state")),l.onError(a),a;this._sessionId||(this._sessionId=va(32,"").toUpperCase());this._gateway.state="CONNECTING";f={clientId:this._clientId,appId:a,sid:this._sessionId,
cname:b,uid:"string"!=typeof e?e:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:c||a,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:f,useLocalAccessPoint:this._useLocalAccessPoint};"string"==typeof e&&(f.stringUid=e,this._uintUid?(f.uid=this._uintUid,this._uintUid=void 0):f.uid=0);"none"!==this._encryptionMode&&this._encryptionSecret&&(f.aesmode=this._encryptionMode,f.aespassword=await Cs(this._encryptionSecret),this._encryptionSalt&&(f.aessalt=this._encryptionSalt));
this._startSession(this._sessionId,{channel:b,appId:a});wb(()=>{"CONNECTING"===this.connectionState&&u.joinChannelTimeout(this._sessionId,5)},5E3);try{var t;let e;if("443only"===f.cloudProxyServer)f.proxyServer=v.PROXY_SERVER_TYPE2;else if("proxy3"===f.cloudProxyServer||"proxy4"===f.cloudProxyServer||"proxy5"===f.cloudProxyServer){let a=v.PROXY_SERVER_TYPE3;Qb(a)?f.proxyServer=a[0]:f.proxyServer=a}if(u.setProxyServer(f.proxyServer),k.setProxyServer(f.proxyServer),this._performanceRecorder.checkPoint("startRequestAp"),
f.stringUid&&!f.uid&&"normal"===f.cloudProxyServer){var x;await Gj(f,this._axiosCancelSource.token,this._config.httpRetryConfig||Ga,!1);let a=await ng(f.stringUid,f,this._axiosCancelSource.token,this._config.httpRetryConfig||Ga);k.debug(m(x="getUserAccount Success ".concat(f.stringUid," => ")).call(x,a));f.uid=a;e=await Ud(f,this._axiosCancelSource.token,this._config.httpRetryConfig||Ga)}else{if(f.stringUid&&!f.uid){var K;let a=await ng(f.stringUid,f,this._axiosCancelSource.token,this._config.httpRetryConfig||
Ga);k.debug(m(K="getUserAccount Success ".concat(f.stringUid," => ")).call(K,a));f.uid=a}e=await Gj(f,this._axiosCancelSource.token,this._config.httpRetryConfig||Ga,!0)}this._performanceRecorder.checkPoint("startJoinGateway");this._configDistribute.startGetConfigDistribute(f,this._axiosCancelSource.token);this._configDistribute.on(ke.UPDATE_BITRATE_LIMIT,a=>{this._highStream&&this._highStream.handleUpdateBitrateLimit(a.uplink);a.low_stream_uplink&&this._lowStream&&this._lowStream.handleUpdateBitrateLimit({max_bitrate:a.low_stream_uplink.bitrate,
min_bitrate:a.low_stream_uplink.bitrate||0})});this._key=c||a;this._joinInfo=jd({},f,{cid:e.gatewayInfo.cid,uid:f.uid?f.uid:e.gatewayInfo.uid,vid:e.gatewayInfo.vid,apResponse:e.gatewayInfo.res,uni_lbs_ip:e.gatewayInfo.uni_lbs_ip,gatewayAddrs:e.gatewayInfo.gatewayAddrs});let h=await this._gateway.join(this._joinInfo,this._key);return l.onSuccess(h),this._appId=a,this._channelName=f.cname,this._uid=h,this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=
window.setInterval(this._handleUpdateNetworkQuality,2E3),window.addEventListener("beforeunload",this._handleBeforeUnload),k.info(m(t="[".concat(this._clientId,"] Joining channel success: ")).call(t,b)),wb(()=>{k.startUpload()},5E3),this._performanceRecorder.checkPoint("finishJoin"),y=this,Z(pc).call(pc,y)||pc.push(y),h}catch(B){throw a=Qb(B)?B[0]:B,k.error("[".concat(this._clientId,"] Joining channel failed, rollback"),a),a.code!==n.OPERATION_ABORTED&&(this._gateway.state="DISCONNECTED",this._reset()),
l.onError(a),a;}var y}async leave(){let a=u.reportApiInvoke(this._sessionId,{name:D.LEAVE,options:[],tag:C.TRACER});k.info("[".concat(this._clientId,"] Leaving channel"));window.removeEventListener("beforeunload",this._handleBeforeUnload);this._reset();var b=J(pc).call(pc,this);-1!==b&&Ra(pc).call(pc,b,1);b=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return k.info("[".concat(this._clientId,"] Leaving channel repeated, success")),b(),a.onSuccess();await this._gateway.leave("CONNECTED"!==
this.connectionState);k.info("[".concat(this._clientId,"] Leaving channel success"));b();a.onSuccess()}async publish(a,b=!0){var c,e;Qb(a)||(a=[a]);let f=u.reportApiInvoke(this._sessionId,{name:D.PUBLISH,options:z(a).call(a,a=>a?Object(a).toString():"null"),tag:C.TRACER});if(0===a.length)return a=new q(n.INVALID_PARAMS,"track list is empty"),f.onError(a),a.throw();if("audience"===this._gateway.role)return a=new q(n.INVALID_OPERATION,"audience can not publish stream"),f.onError(a),a.throw();for(let c of a){if(!(c instanceof
yf))return a=new q(n.INVALID_PARAMS,"pamameter is not local track"),f.onError(a),a.throw();if(!c._enabled&&b)return a=new q(n.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(c.getTrackId())),f.onError(a),a.throw()}if(k.info(m(c="[".concat(this._clientId,"] Publishing tracks, id ")).call(c,z(a).call(a,a=>"".concat(a.getTrackId()," ")))),await this._configDistribute.awaitConfigDistributeComplete(),b&&t(a).call(a,a=>{var b;let c=this._configDistribute.getBitrateLimit();var e;(a instanceof
ta&&c&&a.setBitrateLimit(c.uplink),-1===J(b=this._bindEnabledTracks).call(b,a))&&(a.addListener(G.NEED_ADD_TRACK,this._handleLocalTrackEnable),a.addListener(G.NEED_REMOVE_TRACK,this._handleLocalTrackDisable),this._bindEnabledTracks.push(a),db()&&a.muted&&k.debug(m(e="[".concat(this._clientId,"] on firefox publish a muted track ")).call(e,a.getTrackId(),", skip the pub operation and wait unmute")))}),db()&&0===(a=I(a).call(a,a=>!a.muted)).length)return void f.onSuccess(z(a).call(a,a=>a.trackMediaType+
":"+a.getTrackLabel()).toString());c=await this._publishMutex.lock();try{let b=await this._publishHighStream(a),e=(b.audioTrack,b.videoTrack);this._isDualStreamEnabled&&e&&!this._lowStream&&await this._publishLowStream(e);c();f.onSuccess(z(a).call(a,a=>a.trackMediaType+":"+a.getTrackLabel()).toString())}catch(h){throw c(),b&&t(a).call(a,a=>{var b,c;let e=J(b=this._bindEnabledTracks).call(b,a);-1!==e&&(a.off(G.NEED_ADD_TRACK,this._handleLocalTrackEnable),a.off(G.NEED_REMOVE_TRACK,this._handleLocalTrackDisable),
Ra(c=this._bindEnabledTracks).call(c,e,1))}),f.onError(h),k.error("[".concat(this._clientId,"] publish error"),h.toString()),h;}k.info(m(e="[".concat(this._clientId,"] Publish success, id ")).call(e,z(a).call(a,a=>"".concat(a.getTrackId()," "))))}async unpublish(a,b=!0){var c;let e=await this._publishMutex.lock(),f,h,l;try{var q,p;if(!this._highStream||(f=this._highStream.getAllTracks(),a?Qb(a)||(a=[a]):a=this._highStream.getAllTracks(),h=function(a,b){if(a.length!==b.length)return!1;for(let c=0;c<
a.length;c+=1){let e=a[c];if(I(a).call(a,a=>a===e).length!==I(b).call(b,a=>a===e).length)return!1}return!0}(f,a),l=u.reportApiInvoke(this._sessionId,{name:D.UNPUBLISH,options:z(a).call(a,a=>a.getTrackId()),tag:C.TRACER}),k.info(m(q=m(p="[".concat(this._clientId,"] Unpublish tracks, tracks ")).call(p,z(a).call(a,a=>"".concat(a.getTrackId()," ")),", isClosePC: ")).call(q,h)),!this._highStream))return k.warning("[".concat(this._clientId,"] Could not find tracks to unpublish")),void(e&&e())}catch(w){throw e&&
e(),w;}try{this._lowStream&&0<I(a).call(a,a=>"video"===a.trackMediaType).length&&(await this._lowStream.closeP2PConnection(),this._lowStream=void 0),h?await this._highStream.closeP2PConnection():await this._highStream.removeTracks(a,b),e&&e()}catch(w){if(w.code!==n.OPERATION_ABORTED)throw l.onError(w),k.error("[".concat(this._clientId,"] unpublish error"),w.toString()),e&&e(),w;k.debug("[".concat(this._clientId,"] ignore unpub operation abort"));e&&e()}this._highStream&&"disconnected"===this._highStream.connectionState&&
(this._highStream=void 0,this._lowStream=void 0);b&&t(a).call(a,a=>{var b,c;let e=J(b=this._bindEnabledTracks).call(b,a);-1!==e&&(a.off(G.NEED_ADD_TRACK,this._handleLocalTrackEnable),a.off(G.NEED_REMOVE_TRACK,this._handleLocalTrackDisable),Ra(c=this._bindEnabledTracks).call(c,e,1))});k.info(m(c="[".concat(this._clientId,"] Unpublish success,tracks ")).call(c,z(a).call(a,a=>"".concat(a.getTrackId()))));l.onSuccess()}async subscribe(a,b){var c,e,f,h;fb(b,"mediaType",["audio","video"]);let l=u.reportApiInvoke(this._sessionId,
{name:D.SUBSCRIBE,options:[a.uid,b],tag:C.TRACER});if(!this._joinInfo)throw b=new q(n.INVALID_OPERATION,"Can't subscribe stream, not joined"),l.onError(b),b;if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw b=new q(n.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state")),l.onError(b),b;if(!U(c=this._users).call(c,b=>b===a)){var r;b=new q(n.INVALID_REMOTE_USER,"user is not in the channel");throw k.error(m(r="[".concat(this._clientId,"] can not subscribe ")).call(r,
a.uid,", this user is not in the channel")),l.onError(b),b;}if(!a.hasAudio&&!a.hasVideo){var p;b=new q(n.INVALID_REMOTE_USER,"user is not published");throw k.error(m(p="[".concat(this._clientId,"] can not subscribe ")).call(p,a.uid,", user is not published")),l.onError(b),b;}r={audio:"audio"===b,video:"video"===b};if(!a.hasAudio&&r.audio||!a.hasVideo&&r.video){var t,v;var x=new q(n.REMOTE_USER_IS_NOT_PUBLISHED);throw k.error(m(t=m(v="[".concat(this._clientId,"] can not subscribe ")).call(v,a.uid,
" with mediaType ")).call(t,b,", remote track is not published")),l.onError(x),x;}(t=this._subscribeMutex.get(a.uid))||(t=new sc("sub-".concat(a.uid)),this._subscribeMutex.set(a.uid,t));k.info(m(e=m(f="[".concat(this._clientId,"] subscribe user ")).call(f,a.uid,", mediaType: ")).call(e,b));e=await t.lock();f=this._remoteStream.get(a.uid);try{if(f)r.audio=r.audio||f.subscribeOptions.audio,r.video=r.video||f.subscribeOptions.video,await this._gateway.subscribeChange(f,r);else{f=new ws(a,this._statsCollector,
this._joinInfo,r);this._remoteStream.set(a.uid,f);try{await this._gateway.subscribe(f)}catch(B){throw this._remoteStream.delete(a.uid),B;}f.on(E.CONNECTION_STATE_CHANGE,(b,c)=>{"connecting"===b?this.emit(R.MEDIA_RECONNECT_START,a.uid):"connected"===b&&this.emit(R.MEDIA_RECONNECT_END,a.uid)})}e()}catch(B){var y;throw l.onError(B),e(),k.error(m(y="[".concat(this._clientId,"] subscribe user ")).call(y,a.uid," error"),B),B;}k.info(m(x=m(h="[".concat(this._clientId,"] subscribe success user ")).call(h,
a.uid,", mediaType: ")).call(x,b));this._defaultStreamFallbackType&&this.setStreamFallbackOption(a.uid,this._defaultStreamFallbackType).catch(a=>{k.warning("[".concat(this._clientId,"] auto set fallback failed"),a)});b="audio"===b?a.audioTrack:a.videoTrack;return b?(l.onSuccess(b.getTrackId()),b):(b=new q(n.UNEXPECTED_ERROR,"can not find remote track in user object"),l.onError(b),b.throw())}async unsubscribe(a,b){var c,e,f,h,l;b&&fb(b,"mediaType",["audio","video"]);let r=u.reportApiInvoke(this._sessionId,
{name:D.UNSUBSCRIBE,options:[a.uid,b],tag:C.TRACER});if(!U(c=this._users).call(c,b=>b===a)){var p;b=new q(n.INVALID_REMOTE_USER,"user is not in the channel");throw k.error(m(p="[".concat(this._clientId,"] can not subscribe ")).call(p,a.uid,", user is not in the channel")),r.onError(b),b;}k.info(m(e=m(f="[".concat(this._clientId,"] unsubscribe uid: ")).call(f,a.uid,", mediaType: ")).call(e,b));(p=this._subscribeMutex.get(a.uid))||(p=new sc("sub-".concat(a.uid)),this._subscribeMutex.set(a.uid,p));p=
await p.lock();c=this._remoteStream.get(a.uid);var t;if(!c)return k.warning(m(t="[".concat(this._clientId,"]: you have not subscribe the remote user ")).call(t,a.uid)),r.onSuccess(),void p();t=jd({},c.subscribeOptions);"audio"===b?t.audio=!1:"video"===b?(t.video=!1,c.pc._statsFilter.setVideoIsReady(!1)):(t.audio=!1,t.video=!1);try{t.audio||t.video?await this._gateway.subscribeChange(c,t):(await c.closeP2PConnection(),this._remoteStream.delete(a.uid)),p()}catch(K){var v;if(K.code!==n.OPERATION_ABORTED)throw r.onError(K),
p(),k.error(m(v="[".concat(this._clientId,"] unsubscribe user ")).call(v,a.uid," error"),K.toString()),K;p();k.debug("[".concat(this._clientId,"] ignore unsub operation abort"))}k.info(m(h=m(l="[".concat(this._clientId,"] unsubscribe success uid: ")).call(l,a.uid,", mediaType: ")).call(h,b));r.onSuccess()}setLowStreamParameter(a){if(!a)throw new q(n.INVALID_PARAMS);null==a.width||ha(a.width,"streamParameter.width");null==a.height||ha(a.height,"streamParameter.height");null==a.framerate||ha(a.framerate,
"streamParameter.framerate");null==a.bitrate||ha(a.bitrate,"streamParameter.bitrate");!0;let b=u.reportApiInvoke(this._sessionId,{name:D.SET_LOW_STREAM_PARAMETER,options:[a],tag:C.TRACER});(!a.width&&a.height||a.width&&!a.height)&&k.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set"));k.info("[".concat(this._clientId,"] set low stream parameter to"),A(a));let c=this._configDistribute.getLowStreamConfigDistribute();c&&c.bitrate&&a.bitrate&&c.bitrate<
a.bitrate&&(a.bitrate=c.bitrate);this._lowStreamParameter=a;b.onSuccess()}async enableDualStream(){let a=u.reportApiInvoke(this._sessionId,{name:D.ENABLE_DUAL_STREAM,options:[],tag:C.TRACER});if(!la.supportDualStream){u.streamSwitch(this._sessionId,{lts:x(),isdual:!0,succ:!1});var b=new q(n.NOT_SUPPORTED,"Your browser is not support dual stream");throw a.onError(b),b;}if(this._isDualStreamEnabled)throw b=new q(n.INVALID_OPERATION,"Dual stream is already enabled"),a.onError(b),b;if(this._highStream&&
"connected"===this._highStream.connectionState&&this._highStream.videoTrack)try{await this._publishLowStream(this._highStream.videoTrack)}catch(c){throw u.streamSwitch(this._sessionId,{lts:x(),isdual:!0,succ:!1}),a.onError(c),c;}this._isDualStreamEnabled=!0;u.streamSwitch(this._sessionId,{lts:x(),isdual:!0,succ:!0});k.info("[".concat(this._clientId,"] enable dual stream"));a.onSuccess()}async disableDualStream(){let a=u.reportApiInvoke(this._sessionId,{name:D.DISABLE_DUAL_STREAM,options:[],tag:C.TRACER});
if(this._lowStream)try{await this._lowStream.closeP2PConnection()}catch(b){throw u.streamSwitch(this._sessionId,{lts:x(),isdual:!1,succ:!1}),a.onError(b),b;}this._lowStream=void 0;this._isDualStreamEnabled=!1;this._highStream&&(this._highStream.lowStreamConnection=void 0);u.streamSwitch(this._sessionId,{lts:x(),isdual:!1,succ:!0});k.info("[".concat(this._clientId,"] disable dual stream"));a.onSuccess()}async setClientRole(a,b){fb(a,"role",["audience","host"]);!0;b&&Zi(b);let c=u.reportApiInvoke(this._sessionId,
{name:D.SET_CLIENT_ROLE,options:[a,b],tag:C.TRACER});if("rtc"===this._mode)return k.warning("[".concat(this._clientId,"]rtc mode can not use setClientRole")),a=new q(n.INVALID_OPERATION,"rtc mode can not use setClientRole"),c.onError(a),a.throw();if(b&&b.level&&"host"===a)return a=new q(n.INVALID_OPERATION,"host mode can not set audience latency level"),c.onError(a),a.throw();try{var e,f;if("audience"===a&&this._highStream){let a=new q(n.INVALID_OPERATION,"can not set client role to audience when publishing stream");
return c.onError(a),a.throw()}await this._gateway.setClientRole(a,b);k.info(m(e=m(f="[".concat(this._clientId,"] set client role to ")).call(f,a,", level: ")).call(e,b&&b.level));c.onSuccess()}catch(h){throw c.onError(h),h;}}setProxyServer(a){if(Sa(a,"proxyServer"),"DISCONNECTED"!==this.connectionState)throw new q(n.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new q(n.INVALID_OPERATION,"You have already set the proxy");
this._proxyServer=a;u.setProxyServer(this._proxyServer);k.setProxyServer(this._proxyServer)}setTurnServer(a){if(Qb(a)||(a=[a]),"DISCONNECTED"!==this.connectionState)throw new q(n.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new q(n.INVALID_OPERATION,"You have already set the proxy");var b;if(Xi(a))return this._turnServer={servers:a,mode:"original-manual"},void k.info(m(b="[".concat(this._clientId,"] Set original turnserver success: ")).call(b,
z(a).call(a,a=>a.urls).join(","),"."));t(a).call(a,a=>Yi(a));this._turnServer={servers:a,mode:"manual"};k.info("[".concat(this._clientId,"] Set turnserver success."))}startProxyServer(a){let b=u.reportApiInvoke(this._sessionId,{name:D.START_PROXY_SERVER,options:[],tag:C.TRACER});if("DISCONNECTED"!==this.connectionState)throw a=new q(n.INVALID_OPERATION,"Start proxy server before join channel"),b.onError(a),a;if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw a=
new q(n.INVALID_OPERATION,"You have already set the proxy"),b.onError(a),a;let c=[1,2,3,4,5];switch(void 0===a&&(a=1),a){case 1:this._cloudProxyServerMode="normal";break;case 2:this._cloudProxyServerMode="443only";break;case 3:this._cloudProxyServerMode="proxy3";break;case 4:this._cloudProxyServerMode="proxy4";break;case 5:this._cloudProxyServerMode="proxy5";break;default:throw a=new q(n.INVALID_PARAMS,"proxy server mode must be ".concat(c.join("|"))),b.onError(a),a;}k.info("[".concat(this._clientId,
"] set cloud proxy server mode to"),this._cloudProxyServerMode);b.onSuccess()}stopProxyServer(){let a=u.reportApiInvoke(this._sessionId,{name:D.STOP_PROXY_SERVER,options:[],tag:C.TRACER});if("DISCONNECTED"!==this.connectionState)throw new q(n.INVALID_OPERATION,"Stop proxy server after leave channel");u.setProxyServer();k.setProxyServer();this._cloudProxyServerMode="disabled";k.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode);this._proxyServer=void 0;this._turnServer=
{mode:"auto",servers:[]};a.onSuccess()}setLocalAccessPoints(a,b){if(Xf(a,"serverList"),Sa(b,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new q(n.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");let c=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;a=z(a).call(a,a=>{var e;return c.test(a)?m(e="".concat(a.replace(/\./g,"-"),".")).call(e,b):
a});this._useLocalAccessPoint=!0;eb("WEBCS_DOMAIN",a);eb("WEBCS_DOMAIN_BACKUP_LIST",a);eb("GATEWAY_DOMAINS",[b]);eb("EVENT_REPORT_DOMAIN",a[0]);eb("EVENT_REPORT_BACKUP_DOMAIN",a[1]||a[0]);eb("LOG_UPLOAD_SERVER","".concat(a[0],":6444"));k.info("set local access point success")}async setRemoteVideoStreamType(a,b){var c,e;fb(b,"streamType",[0,1]);let f=u.reportApiInvoke(this._sessionId,{name:D.SET_REMOTE_VIDEO_STREAM_TYPE,options:[a,b],tag:C.TRACER});try{await this._gateway.setRemoteVideoStreamType(a,
b),wb(()=>{var b;let c=U(b=this._users).call(b,b=>b.uid===a);c&&c.videoTrack&&c.videoTrack.updateMediaStreamTrackResolution()},2E3)}catch(h){throw f.onError(h),k.error("[".concat(this._clientId,"] set remote video stream type error"),h.toString()),h;}k.info(m(c=m(e="[".concat(this._clientId,"] set remote ")).call(e,a," video stream type to ")).call(c,b));this._remoteStreamTypeCacheMap.set(a,b);f.onSuccess()}async setStreamFallbackOption(a,b){var c,e;fb(b,"fallbackType",[0,1,2]);let f=u.reportApiInvoke(this._sessionId,
{name:D.SET_STREAM_FALLBACK_OPTION,options:["too long to show",b],tag:C.TRACER});try{await this._gateway.setStreamFallbackOption(a,b)}catch(h){throw f.onError(h),k.error("[".concat(this._clientId,"] set stream fallback option"),h.toString()),h;}k.info(m(c=m(e="[".concat(this._clientId,"] set remote ")).call(e,a," stream fallback type to ")).call(c,b));this._streamFallbackTypeCacheMap.set(a,b);f.onSuccess()}setEncryptionConfig(a,b,c){fb(a,"encryptionMode","aes-128-xts aes-256-xts aes-128-ecb sm4-128-ecb aes-128-gcm aes-256-gcm aes-128-gcm2 aes-256-gcm2 none".split(" "));
!0;Sa(b,"secret");let e=["aes-128-gcm2","aes-256-gcm2"];if(Z(e).call(e,a)){if(!(c&&c instanceof Uint8Array&&32===c.length))throw new q(n.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes");}else if(c)throw new q(n.INVALID_PARAMS,"current encrypt mode does not need salt");/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'"|{}\[\]])(?=.{8,})/.test(b)||k.warning("The secret is not strong:\n      The secret must contain at least 1 lowercase alphabetical character,\n      The secret must contain at least 1 uppercase alphabetical character,\n      The secret must contain at least 1 numeric character,\n      The secret must contain at least one special character,\n      The secret must be eight characters or longer.\n      ");
this._encryptionMode=a;this._encryptionSecret=b;c&&(this._encryptionSalt=Re(c))}async renewToken(a){Sa(a,"token",1,2047);let b=u.reportApiInvoke(this._sessionId,{name:D.RENEW_TOKEN,options:[a],tag:C.TRACER});if(!this._key)return a=new q(n.INVALID_OPERATION,"renewToken should not be called before user join"),b.onError(a),a.throw();this._key=a;try{await this._gateway.renewToken(a)}catch(c){throw b.onError(c),k.error("[".concat(this._clientId,"] renewToken failed"),c.toString()),c;}k.debug("[".concat(this._clientId,
"] renewToken success"));b.onSuccess()}enableAudioVolumeIndicator(){let a=u.reportApiInvoke(this._sessionId,{name:D.ENABLE_AUDIO_VOLUME_INDICATOR,options:[],tag:C.TRACER});if(this._audioVolumeIndicationInterval)return k.warning("you have already enabled audio volume indicator!"),a.onSuccess();this._audioVolumeIndicationInterval=window.setInterval(()=>{var a,c,e;let f=he(a=z(c=Ub(Uc(e=this._remoteStream).call(e))).call(c,a=>({level:a.user.audioTrack?100*a.user.audioTrack._source.getAccurateVolumeLevel():
0,uid:a.getUserId()}))).call(a,(a,b)=>a.level-b.level);this._highStream&&this._highStream.audioTrack&&(f.push({level:100*this._highStream.audioTrack._source.getAccurateVolumeLevel(),uid:this._highStream._userId}),f=he(f).call(f,(a,b)=>a.level-b.level));this.emit(R.VOLUME_INDICATOR,f)},v.AUDIO_VOLUME_INDICATION_INTERVAL||2E3);a.onSuccess()}getRTCStats(){let a=this._statsCollector.getRTCStats(),b=this._gateway.getInChannelInfo();return a.Duration=Math.round(b.duration/1E3),a}startLiveStreaming(a,b){let c=
u.reportApiInvoke(this._sessionId,{name:D.START_LIVE_STREAMING,options:[a,b],tag:C.TRACER});if(!b){if("h264"!==this._codec)return a=new q(n.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264"),c.onError(a),y.reject(a);if(!this._highStream)return a=new q(n.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming"),c.onError(a),y.reject(a)}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(a)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(a))return a=
new q(n.LIVE_STREAMING_TASK_CONFLICT),c.onError(a),y.reject(a);b=b?ua.TRANSCODE:ua.RAW;return this._createLiveStreamingClient(b).startLiveStreamingTask(a,b).then(()=>c.onSuccess()).catch(a=>{throw c.onError(a),a;})}setLiveTranscoding(a){let b=u.reportApiInvoke(this._sessionId,{name:D.SET_LIVE_TRANSCODING,options:[a],tag:C.TRACER});return this._createLiveStreamingClient(ua.TRANSCODE).setTranscodingConfig(a).then(()=>b.onSuccess()).catch(a=>{throw b.onError(a),a;})}stopLiveStreaming(a){var b;let c=
u.reportApiInvoke(this._sessionId,{name:D.STOP_LIVE_STREAMING,options:[a],tag:C.TRACER}),e=I(b=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient]).call(b,b=>b&&b.hasUrl(a));return e.length?y.all(z(e).call(e,b=>b&&b.stopLiveStreamingTask(a))).then(()=>c.onSuccess()).catch(a=>{throw c.onError(a),a;}):(b=new q(n.INVALID_PARAMS,"can not find live streaming url to stop"),c.onError(b),y.reject(b))}async addInjectStreamUrl(a,b){let c=u.reportApiInvoke(this._sessionId,{name:D.ADD_INJECT_STREAM_URL,
options:[a,b],tag:C.TRACER});try{if(!this._joinInfo)throw new q(n.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");let c=this._createLiveStreamingClient(ua.INJECT);c.setInjectStreamConfig(b,0);await c.startLiveStreamingTask(a,ua.INJECT)}catch(e){throw c.onError(e),e;}c.onSuccess()}async removeInjectStreamUrl(){let a=u.reportApiInvoke(this._sessionId,{name:D.REMOVE_INJECT_STREAM_URL,options:[],tag:C.TRACER});try{var b,c;let a=this._createLiveStreamingClient(ua.INJECT),f=U(b=Ub(Uc(c=a.streamingTasks).call(c))).call(b,
a=>a.mode===ua.INJECT);if(!this._joinInfo||!f)throw new q(n.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await a.stopLiveStreamingTask(f.url)}catch(e){throw a.onError(e),e;}a.onSuccess()}async startChannelMediaRelay(a){let b=u.reportApiInvoke(this._sessionId,{name:D.START_CHANNEL_MEDIA_RELAY,options:[a],tag:C.TRACER});try{Xj(a),await this._createChannelMediaRelayClient().startChannelMediaRelay(a)}catch(c){return b.onError(c),c.throw()}b.onSuccess()}async updateChannelMediaRelay(a){let b=
u.reportApiInvoke(this._sessionId,{name:D.UPDATE_CHANNEL_MEDIA_RELAY,options:[a],tag:C.TRACER});try{Xj(a),await this._createChannelMediaRelayClient().updateChannelMediaRelay(a)}catch(c){return b.onError(c),c.throw()}b.onSuccess()}async stopChannelMediaRelay(){let a=u.reportApiInvoke(this._sessionId,{name:D.STOP_CHANNEL_MEDIA_RELAY,options:[],tag:C.TRACER});try{await this._createChannelMediaRelayClient().stopChannelMediaRelay()}catch(b){return a.onError(b),b.throw()}a.onSuccess()}sendStreamMessage(a,
b=!0){if(!this._joinInfo)throw new q(n.INVALID_OPERATION,"can not send data stream, not joined");"string"==typeof a&&(a=(new TextEncoder).encode(a));if(1024<(new Blob([a])).size)throw new q(n.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(ia.DATA_STREAM,{payload:Re(a)},!b)}sendMetadata(a){if(!this._joinInfo)throw new q(n.INVALID_OPERATION,"can not send metadata, not joined");if(1024<(new Blob([a])).size)throw new q(n.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(ia.SEND_METADATA,
{session_id:this._joinInfo.sid,metadata:Re(a)})}async sendCustomReportMessage(a){Qb(a)||(a=[a]);t(a).call(a,eo);let b=u.reportApiInvoke(this._sessionId,{name:D.SEND_CUSTOM_REPORT_MESSAGE,options:[A(a)],tag:C.TRACER});if(!this._joinInfo)return a=new q(n.INVALID_OPERATION,"can not send custom report, not joined"),b.onError(a),a.throw();await u.sendCustomReportMessage(this._joinInfo.sid,a);b.onSuccess()}getLocalAudioStats(){if(!this._highStream)return vf;let a=this._statsCollector.getLocalAudioTrackStats(this._highStream.connectionId);
return $c()&&this._highStream&&this._highStream.audioTrack&&(this._highStream.audioTrack instanceof ab?!this._highStream.audioTrack.isActive:!this._highStream.audioTrack.enabled)&&(a.sendVolumeLevel=0),a}getRemoteAudioStats(){var a;let b={};return t(a=this._remoteStream).call(a,(a,e)=>{b[e]=this._statsCollector.getRemoteAudioTrackStats(a.connectionId)}),b}getLocalVideoStats(){return this._highStream?this._statsCollector.getLocalVideoTrackStats(this._highStream.connectionId):wf}getRemoteVideoStats(){var a;
let b={};return t(a=this._remoteStream).call(a,(a,e)=>{b[e]=this._statsCollector.getRemoteVideoTrackStats(a.connectionId)}),b}getRemoteNetworkQuality(){var a;let b={};return t(a=this._remoteStream).call(a,(a,e)=>{b[e]=this._statsCollector.getRemoteNetworkQualityStats(a.connectionId)}),b}async pickSVCLayer(a,b){fb(b.spatialLayer,"spatialLayer",[0,1,2,3]);fb(b.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(a,b)}catch(c){throw k.error("[".concat(this._clientId,"] pick SVC layer failed"),
c.toString()),c;}}_reset(){var a,b,c;k.debug("[".concat(this._clientId,"] reset client"));this._axiosCancelSource.cancel();this._axiosCancelSource=$b.CancelToken.source();this._streamFallbackTypeCacheMap=new ba;this._remoteStreamTypeCacheMap=new ba;this._configDistribute.stopGetConfigDistribute();this._defaultStreamFallbackType=this._proxyServer=this._joinInfo=void 0;this._sessionId=null;this._statsCollector.reset();this._channelName=this._uid=this._appId=this._key=void 0;this._encryptionMode="none";
this._encryptionSalt=this._encryptionSecret=null;t(a=this._users).call(a,a=>{a.audioTrack&&(a.audioTrack.stop(),a.audioTrack._isDestroyed=!0);a.videoTrack&&(a.videoTrack.stop(),a.videoTrack._isDestroyed=!0)});this._users=[];this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0);this._highStream&&(this._highStream.closeP2PConnection(!0),this._highStream=void 0);t(b=this._bindEnabledTracks).call(b,a=>{a.off(G.NEED_ADD_TRACK,
this._handleLocalTrackEnable);a.off(G.NEED_REMOVE_TRACK,this._handleLocalTrackDisable)});this._bindEnabledTracks=[];this._lowStream&&(this._lowStream.closeP2PConnection(!0),this._lowStream=void 0);t(c=this._remoteStream).call(c,a=>{a.closeP2PConnection(!0)});this._remoteStream=new ba;this._publishMutex=new sc("client-publish");this._subscribeMutex=new ba;this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0);this._injectStreamingClient&&
(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=void 0);this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0);this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0);this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),
this._channelMediaRelayClient=void 0)}_startSession(a,b){var c,e,f;let h=a||va(32,"").toUpperCase();a?k.debug(m(c="[".concat(this._clientId,"] new Session ")).call(c,h)):k.debug(m(e=m(f="[".concat(this._clientId,"] renewSession ")).call(f,this._sessionId," => ")).call(e,h));this._sessionId=h;b?u.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:b.channel,appid:b.appId,mode:this._mode}):this._joinInfo?u.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._joinInfo.cname,appid:this._joinInfo.appId,
mode:this._mode}):this._gateway.joinInfo&&u.sessionInit(this._sessionId,{lts:(new Date).getTime(),cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId,mode:this._mode});this._joinInfo&&(this._joinInfo.sid=h);this._gateway.joinInfo&&(this._gateway.joinInfo.sid=h)}async _publishHighStream(a){if(!this._joinInfo)throw new q(n.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new q(n.INVALID_OPERATION,
"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&v.FORCE_TURN&&!v.TURN_ENABLE_TCP&&!v.TURN_ENABLE_UDP)throw new q(n.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");if(k.debug("[".concat(this._clientId,"] publish high stream")),this._highStream)return await this._highStream.addTracks(a),this._highStream;this._highStream=new On(this._statsCollector,this._joinInfo,this._codec);this._highStream.on(E.P2P_LOST,()=>{this._highStream&&this.emit(R.P2P_LOST,
this._highStream.getUserId())});await this._highStream.addTracks(a);try{await this._gateway.publish(this._highStream,"high")}catch(b){throw this._highStream=void 0,b;}return this._highStream.on(E.CONNECTION_STATE_CHANGE,(a,c)=>{this._highStream&&("connected"===a?this.emit(R.MEDIA_RECONNECT_END,this._highStream.getUserId()):"connecting"===a&&this.emit(R.MEDIA_RECONNECT_START,this._highStream.getUserId()))}),this._highStream}async _publishLowStream(a){if(!this._joinInfo)throw new q(n.INVALID_OPERATION,
"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new q(n.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if(!this._highStream||"connected"!==this._highStream.connectionState)throw new q(n.UNEXPECTED_ERROR,"Could not find high stream");if(this._lowStream)return(new q(n.UNEXPECTED_ERROR,"[".concat(this._clientId,"] Can't publish low stream when stream already publish"))).throw();k.debug("[".concat(this._clientId,
"] publish low stream"));this._lowStream=new On(this._statsCollector,this._joinInfo,this._codec,!0);let b=this._configDistribute.getLowStreamConfigDistribute();b&&b.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&b.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=b.bitrate));this._lowStream.lowStreamParameter=this._lowStreamParameter;await this._lowStream.addTracks([a]);
try{await this._gateway.publish(this._lowStream,"low")}catch(c){throw this._lowStream=void 0,c;}this._highStream.lowStreamConnection=this._lowStream}_createLiveStreamingClient(a){if(!this._joinInfo||!this._appId)return(new q(n.INVALID_OPERATION,"can not create live streaming client, please join channel first")).throw();let b=()=>new ys(this._joinInfo,this._config.websocketRetryConfig||Ga,this._config.httpRetryConfig||Ga),c=a=>{a.onLiveStreamError=(a,b)=>{u.reportApiInvoke(this._sessionId,{name:D.ON_LIVE_STREAM_ERROR,
options:[a,b],tag:C.TRACER}).onSuccess();this.emit(R.LIVE_STREAMING_ERROR,a,b)};a.onLiveStreamWarning=(a,b)=>{u.reportApiInvoke(this._sessionId,{name:D.ON_LIVE_STREAM_WARNING,options:[a,b],tag:C.TRACER}).onSuccess();this.emit(R.LIVE_STREAMING_WARNING,a,b)};a.on(Ad.REQUEST_WORKER_MANAGER_LIST,(a,b,c)=>{if(!this._joinInfo)return c(new q(n.INVALID_OPERATION,"can not find join info to get worker manager"));Hj(a,this._joinInfo,this._axiosCancelSource.token,Ga).then(b).catch(c)})};switch(a){case ua.RAW:return this._liveRawStreamingClient||
(this._liveRawStreamingClient=b(),c(this._liveRawStreamingClient)),this._liveRawStreamingClient;case ua.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=b(),c(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case ua.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=b(),this._injectStreamingClient.on(Ad.REQUEST_WORKER_MANAGER_LIST,(a,b,c)=>{if(!this._joinInfo)return c(new q(n.INVALID_OPERATION,"can not find join info to get worker manager"));
Hj(a,this._joinInfo,this._axiosCancelSource.token,Ga).then(b).catch(c)}),this._injectStreamingClient.onInjectStatusChange=(a,b,c)=>{this.emit(R.INJECT_STREAM_STATUS,a,b,c)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){return this._joinInfo?(this._channelMediaRelayClient||(this._channelMediaRelayClient=new As(this._joinInfo,this._clientId,this._config.websocketRetryConfig||Ga,this._config.httpRetryConfig||Ga),this._channelMediaRelayClient.on("state",a=>{"RELAY_STATE_FAILURE"===a&&
this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose();this.emit(R.CHANNEL_MEDIA_RELAY_STATE,a)}),this._channelMediaRelayClient.on("event",a=>{this.emit(R.CHANNEL_MEDIA_RELAY_EVENT,a)})),this._channelMediaRelayClient):(new q(n.INVALID_OPERATION,"can not create channel media relay client, please join channel first")).throw()}_handleGatewayEvents(){this._gateway.on(Ja.DISCONNECT_P2P,()=>{var a;k.debug("[".concat(this._clientId,"] start full reconnect"));this._highStream&&"disconnected"!==
this._highStream.connectionState&&(k.debug("[".concat(this._clientId,"] ready to reconnect high stream")),this._highStream.readyToReconnectPC());this._lowStream&&"disconnected"!==this._lowStream.connectionState&&(k.debug("[".concat(this._clientId,"] ready to reconnect low stream")),this._lowStream.readyToReconnectPC());t(a=this._remoteStream).call(a,(a,c)=>{var b;k.debug(m(b="[".concat(this._clientId,"] ready to reconnect remote stream ")).call(b,c));a.readyToReconnectPC()})});this._gateway.on(Ja.CONNECTION_STATE_CHANGE,
(a,b,c)=>{var e,f;let h=()=>{this.emit(R.CONNECTION_STATE_CHANGE,a,b,c)};if(k.info(m(e=m(f="[".concat(this._clientId,"] connection state change: ")).call(f,b," -> ")).call(e,a)),"DISCONNECTED"===a)return this._reset(),void h();var l,n;if("RECONNECTING"===a)this._highStream&&"connecting"===this._highStream.connectionState&&(k.debug("[".concat(this._clientId,"] ready to reconnect high stream")),this._highStream.readyToReconnectPC()),this._lowStream&&"connecting"===this._lowStream.connectionState&&(k.debug("[".concat(this._clientId,
"] ready to reconnect low stream")),this._lowStream.readyToReconnectPC()),t(l=this._remoteStream).call(l,(a,b)=>{var c;"connecting"===a.connectionState&&(k.debug(m(c="[".concat(this._clientId,"] ready to reconnect remote stream ")).call(c,b)),a.readyToReconnectPC())}),t(n=this._users).call(n,a=>{a._trust_in_room_=!1;a._trust_audio_enabled_state_=!1;a._trust_video_enabled_state_=!1;a._trust_audio_mute_state_=!1;a._trust_video_mute_state_=!1;a._trust_stream_added_state_=!1}),this._userOfflineTimeout&&
window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._streamRemovedTimeout=this._userOfflineTimeout=void 0;else if("CONNECTED"===a){var p,q;t(p=this._streamFallbackTypeCacheMap).call(p,(a,b)=>{this._gateway.setStreamFallbackOption(b,a).catch(a=>k.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),a))});t(q=this._remoteStreamTypeCacheMap).call(q,(a,b)=>{this._gateway.setRemoteVideoStreamType(b,a).catch(a=>
k.warning("[".concat(this._clientId,"] auto set remote stream type failed"),a))});this._highStream&&"connecting"===this._highStream.connectionState?this._highStream.reconnectPC().then(()=>{this._lowStream&&"connecting"===this._lowStream.connectionState&&this._lowStream.reconnectPC().catch(a=>{k.error("[".concat(this._clientId,"] republish low stream error"),a.toString());this.emit(R.ERROR,{reason:a})})}).catch(a=>{k.error("[".concat(this._clientId,"] republish high stream error"),a.toString());this.emit(R.ERROR,
{reason:a})}):this._lowStream&&"connecting"===this._lowStream.connectionState&&this._lowStream.reconnectPC().catch(a=>{k.error("[".concat(this._clientId,"] republish low stream error"),a.toString());this.emit(R.ERROR,{reason:a})});this._userOfflineTimeout=window.setTimeout(()=>{var a;if("CONNECTED"===this.connectionState){this._userOfflineTimeout=void 0;var b=I(a=this._users).call(a,a=>!a._trust_in_room_);t(b).call(b,a=>{var b;k.debug(m(b="[".concat(this._clientId,"] user offline timeout, emit user offline ")).call(b,
a.uid));this._handleUserOffline({uid:a.uid})})}},3E3);this._streamRemovedTimeout=window.setTimeout(()=>{var a;"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,t(a=this._users).call(a,a=>{var b,c,e,f,h;a._trust_audio_mute_state_||(k.debug(m(b="[".concat(this._clientId,"] auto dispatch audio unmute event ")).call(b,a.uid)),this._handleMuteStream(a.uid,"audio",!1));a._trust_video_mute_state_||(k.debug(m(c="[".concat(this._clientId,"] auto dispatch video unmute event ")).call(c,
a.uid)),this._handleMuteStream(a.uid,"video",!1));a._trust_audio_enabled_state_||(k.debug(m(e="[".concat(this._clientId,"] auto dispatch enable local audio ")).call(e,a.uid)),this._handleSetStreamLocalEnable("audio",a.uid,!0));!a._trust_video_enabled_state_&&a._video_enabled_&&(k.debug(m(f="[".concat(this._clientId,"] auto dispatch enable local video ")).call(f,a.uid)),this._handleSetStreamLocalEnable("video",a.uid,!0));a._trust_stream_added_state_||(k.debug(m(h="[".concat(this._clientId,"] auto dispatch stream remove ")).call(h,
a.uid)),this._handleRemoveStream({uid:a.uid,uint_id:a._uintid}))}))},1E3)}h()});this._gateway.on(Ja.REQUEST_NEW_GATEWAY_LIST,(a,b)=>{if(!this._joinInfo)return b(new q(n.UNEXPECTED_ERROR,"can not recover, no join info"));Ud(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Ga).then(b=>{var c;this._joinInfo&&(this._joinInfo.apResponse=b.gatewayInfo.res);a(z(c=b.gatewayInfo.gatewayAddrs).call(c,a=>{if(this._joinInfo&&this._joinInfo.proxyServer){var b,c;a=a.split(":");return m(b=
m(c="wss://".concat(this._joinInfo.proxyServer,"/ws/?h=")).call(c,a[0],"&p=")).call(b,a[1])}return"wss://".concat(a)}))}).catch(b)});this._gateway.on(Ja.NETWORK_QUALITY,a=>{"normal"===this._networkQualitySensitivity&&this.emit(R.NETWORK_QUALITY,a)});this._gateway.on(Ja.STREAM_TYPE_CHANGE,(a,b)=>{this.emit(R.STREAM_TYPE_CHANGED,a,b);u.reportApiInvoke(this._sessionId,{name:D.STREAM_TYPE_CHANGE,options:[a,b],tag:C.TRACER}).onSuccess(A({uid:a,streamType:b}))});this._gateway.on(Ja.IS_P2P_DISCONNECTED,
a=>{var b,c,e;let f=[];return this._highStream&&f.push(this._highStream),t(b=this._remoteStream).call(b,a=>f.push(a)),0===f.length||0===I(f).call(f,a=>"connected"===a.connectionState).length?a(!0):(k.debug(m(c="[".concat(this._clientId,"] ")).call(c,z(e=I(f).call(f,a=>"connected"===a.connectionState)).call(e,a=>a.connectionId)," is connected")),void a(!1))});this._gateway.on(Ja.NEED_RENEW_SESSION,()=>{this._startSession()});this._gateway.signal.on(fa.ON_USER_ONLINE,this._handleUserOnline);this._gateway.signal.on(fa.ON_USER_OFFLINE,
this._handleUserOffline);this._gateway.signal.on(fa.ON_ADD_AUDIO_STREAM,a=>this._handleAddAudioOrVideoStream("audio",a.uid,a.uint_id));this._gateway.signal.on(fa.ON_ADD_VIDEO_STREAM,a=>this._handleAddAudioOrVideoStream("video",a.uid,a.uint_id));this._gateway.signal.on(fa.ON_REMOVE_STREAM,this._handleRemoveStream);this._gateway.signal.on(fa.ON_P2P_LOST,this._handleP2PLost);this._gateway.signal.on(fa.MUTE_AUDIO,a=>this._handleMuteStream(a.uid,"audio",!0));this._gateway.signal.on(fa.UNMUTE_AUDIO,a=>
this._handleMuteStream(a.uid,"audio",!1));this._gateway.signal.on(fa.MUTE_VIDEO,a=>this._handleMuteStream(a.uid,"video",!0));this._gateway.signal.on(fa.UNMUTE_VIDEO,a=>this._handleMuteStream(a.uid,"video",!1));this._gateway.signal.on(fa.RECEIVE_METADATA,a=>{let b=ig(a.metadata);this.emit(R.RECEIVE_METADATA,a.uid,b)});this._gateway.signal.on(fa.ON_DATA_STREAM,a=>{a.seq&&delete a.seq;a.payload=ig(a.payload);this.emit(R.STREAM_MESSAGE,a.uid,a.payload);this.onStreamMessage&&this.onStreamMessage(a)});
this._gateway.signal.on(fa.ON_CRYPT_ERROR,()=>{Qd(()=>{k.warning("[".concat(this._clientId,"] on crypt error"));this.emit(R.CRYPT_ERROR)},this._sessionId)});this._gateway.signal.on(fa.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire);this._gateway.signal.on(fa.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{k.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again"));this._reset();this._gateway.leave(!0);this.emit(R.ON_TOKEN_PRIVILEGE_DID_EXPIRE)});
this._gateway.signal.on(fa.ON_STREAM_FALLBACK_UPDATE,a=>{var b,c;k.debug(m(b=m(c="[".concat(this._clientId,"] stream fallback peerId: ")).call(c,a.stream_id,", attr: ")).call(b,a.stream_type));this.emit(R.STREAM_FALLBACK,a.stream_id,1===a.stream_type?"fallback":"recover")});this._gateway.signal.on(fa.ON_PUBLISH_STREAM,a=>{var b;this.uid===this._uid&&(this._highStream&&this._highStream._waitingSuccessResponse&&"connected"===this._highStream.connectionState?(this._highStream.reportPublishEvent(!0,null,
A({proxy:a.proxy})),k.info(m(b="[".concat(this._clientId,"] on publish stream, ")).call(b,A(a))),void 0!==a.proxy&&this.emit(R.IS_USING_CLOUD_PROXY,!!a.proxy)):this._lowStream?this._lowStream.reportPublishEvent(!0,null,A({proxy:a.proxy})):k.warning("get on_publish_stream message but cannot handle"))});this._gateway.signal.on(fa.ENABLE_LOCAL_VIDEO,a=>{this._handleSetStreamLocalEnable("video",a.uid,!0)});this._gateway.signal.on(fa.DISABLE_LOCAL_VIDEO,a=>{this._handleSetStreamLocalEnable("video",a.uid,
!1)});this._gateway.signal.on(T.REQUEST_TIMEOUT,(a,b)=>{if(this._joinInfo)switch(a){case ia.PUBLISH:var c;if(!b)break;a="high"===b.stream_type?this._highStream:this._lowStream;if(!a)break;"offer"===b.state&&u.publish(this._joinInfo.sid,{lts:a.startTime,succ:!1,ec:n.TIMEOUT,audio:b.audio,video:b.video,p2pid:b.p2p_id,publishRequestid:a.ID,screenshare:!(!a.videoTrack||-1===J(c=a.videoTrack._hints).call(c,Yb.SCREEN_TRACK)),audioName:a.audioTrack&&(a.audioTrack instanceof ab?a.audioTrack.getSubTrackLabels().join(","):
a.audioTrack.getTrackLabel()),videoName:a.videoTrack&&a.videoTrack.getTrackLabel()});break;case ia.SUBSCRIBE:(c=this._remoteStream.get(b.stream_id))&&b&&u.subscribe(this._joinInfo.sid,{lts:c.startTime,succ:!1,ec:n.TIMEOUT,audio:!!b.audio,video:!!b.video,peerid:b.stream_id,subscribeRequestid:c.ID,p2pid:c.pc.ID})}})}}ye([Md({report:u}),mb("design:type",Function),mb("design:paramtypes",[String]),mb("design:returntype",void 0)],Gd.prototype,"setProxyServer",null);ye([Md(),mb("design:type",Function),mb("design:paramtypes",
[Object]),mb("design:returntype",void 0)],Gd.prototype,"setTurnServer",null);ye([Md({report:u}),mb("design:type",Function),mb("design:paramtypes",[Array,String]),mb("design:returntype",void 0)],Gd.prototype,"setLocalAccessPoints",null);ye([Md({report:u}),mb("design:type",Function),mb("design:paramtypes",[String,String,Uint8Array]),mb("design:returntype",void 0)],Gd.prototype,"setEncryptionConfig",null);ye([bg({report:u}),mb("design:type",Function),mb("design:paramtypes",[Object,Object]),mb("design:returntype",
y)],Gd.prototype,"pickSVCLayer",null);class Gs extends ym{constructor(a,b={}){super();this.currentLoopCount=this.pausePlayTime=this.startPlayOffset=this.startPlayTime=0;this._currentState="stopped";this.audioBuffer=a;this.options=b;this.startPlayOffset=this.options.startPlayTime||0}set currentState(a){a!==this._currentState&&(this._currentState=a,this.emit(Mb.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer.duration}get currentTime(){return"stopped"===
this.currentState?0:"paused"===this.currentState?this.pausePlayTime:(this.context.currentTime-this.startPlayTime+this.startPlayOffset)%this.audioBuffer.duration}updateOptions(a){"stopped"===this.currentState?(this.options=a,this.startPlayOffset=this.options.startPlayTime||0):k.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer();this.sourceNode=this.createSourceNode();this.startSourceNode();this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&
"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(a){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=a,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=
a))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(a){}this.reset()}}startSourceNode(){var a;this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=xa(a=
this.handleSourceNodeEnded).call(a,this))}createSourceNode(){let a=this.context.createBufferSource();return a.buffer=this.audioBuffer,a.loop=!!this.options.loop,a.connect(this.outputNode),a}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0;this.currentState="stopped";this.sourceNode&&
(this.sourceNode.disconnect(),this.sourceNode=void 0);this.currentLoopCount=0}}let ak=new ba;var Hs=ma.setInterval;let Is=V().name;class ze{constructor(a,b){this.id=0;ze.count+=1;this.id=ze.count;this.element=a;this.context=b}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection];this.peerPair[1].ontrack=a=>{let b=document.createElement("audio");b.srcObject=new MediaStream([a.track]);b.play();this.audioPlayerElement=b}}async switchSdp(){if(this.peerPair){var a=async(a,b)=>{b="offer"===
b?await a.createOffer():await a.createAnswer();return await a.setLocalDescription(b),"complete"===a.iceGatheringState?a.localDescription:new y(b=>{a.onicegatheringstatechange=()=>{"complete"===a.iceGatheringState&&b(a.localDescription)}})},b=async(a,b)=>await a.setRemoteDescription(b);try{let c=await a(this.peerPair[0],"offer");await b(this.peerPair[1],c);let e=await a(this.peerPair[1],"answer");await b(this.peerPair[0],e)}catch(c){throw(new q(n.LOCAL_AEC_ERROR,c.toString())).print();}}}async getTracksFromMediaElement(a){if(this.audioTrack)return this.audioTrack;
let b;try{a instanceof HTMLVideoElement&&(a.captureStream?a.captureStream():a.mozCaptureStream()),b=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(a).connect(b)}catch(c){throw(new q(n.LOCAL_AEC_ERROR,c.toString())).print();}if(!b)throw(new q(n.LOCAL_AEC_ERROR,"no dest node when local aec")).print();a=b.stream.getAudioTracks()[0];return this.audioTrack=a,a}getElement(){return this.element}async startEchoCancellation(){this.context.resume();this.peerPair&&this.close();
this.initPeers();let a=await this.getTracksFromMediaElement(this.element);this.peerPair&&this.peerPair[0].addTrack(a);await this.switchSdp()}close(){var a;k.debug("close echo cancellation unit, id is",this.id);this.audioPlayerElement&&this.audioPlayerElement.pause();this.peerPair&&t(a=this.peerPair).call(a,a=>{a.close()});this.audioPlayerElement=this.peerPair=void 0}}ze.count=0;var Zh=function(a,b){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(a,b)};let Js=
window.AudioContext||window.webkitAudioContext;class Qn{constructor(){this.units=[]}processExternalMediaAEC(a){var b;if(!this._doesEnvironmentNeedAEC())return k.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Js);let c=U(b=this.units).call(b,b=>b&&b.getElement()===a);return c||(c=new ze(a,this.context),this.units.push(c)),c.startEchoCancellation(),k.debug("start processing local audio echo cancellation, id is",c.id),c.id}_doesEnvironmentNeedAEC(){return V().name!==
S.SAFARI}}(function(a,b,c,e){var f,h=arguments.length,k=3>h?b:null===e?e=ca(b,c):e;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)k=Reflect.decorate(a,b,c,e);else for(var m=a.length-1;0<=m;m--)(f=a[m])&&(k=(3>h?f(k):3<h?f(b,c,k):f(b,c))||k);return 3<h&&k&&Q(b,c,k),k})([Md({report:u}),Zh("design:type",Function),Zh("design:paramtypes",[HTMLAudioElement]),Zh("design:returntype",Number)],Qn.prototype,"processExternalMediaAEC",null);let Ks=new Qn;var Rn,Sn,Tn,Un;eb("PROCESS_ID",m(Rn=
m(Sn=m(Tn=m(Un="process-".concat(va(8,""),"-")).call(Un,va(4,""),"-")).call(Tn,va(4,""),"-")).call(Sn,va(4,""),"-")).call(Rn,va(12,"")));(function(){let a=V();var b=navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia?!0:!1;la.getDisplayMedia=b;la.getStreamFromExtension=a.name===S.CHROME&&34<Number(a.version);la.supportUnifiedPlan=function(){if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;let a=new RTCPeerConnection,b=!1;try{a.addTransceiver("audio"),
b=!0}catch(f){}return a.close(),b}();la.supportMinBitrate=a.name===S.CHROME||a.name===S.EDGE;la.supportSetRtpSenderParameters=function(){let a=V();return window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters?!!Tf()||!(!$c()&&!Ee())||a.name===S.FIREFOX&&64<=Number(a.version):!1}();a.name===S.SAFARI&&(14<=Number(a.version)?la.supportDualStream=!0:la.supportDualStream=!1);la.webAudioMediaStreamDest=function(){let a=V();return a.name===S.SAFARI&&
12>Number(a.version)?!1:!0}();la.supportReplaceTrack=window.RTCRtpSender?"function"==typeof RTCRtpSender.prototype.replaceTrack?!0:!1:!1;la.supportWebGL="undefined"!=typeof WebGLRenderingContext;la.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack;Tf()||(la.webAudioWithAEC=!0);la.supportShareAudio=function(){let a=V();return(a.os===Na.WIN_10||a.os===Na.WIN_81||a.os===Na.WIN_7||a.os===Na.LINUX||a.os===Na.MAC_OS)&&a.name===S.CHROME&&74<=Number(a.version)?!0:!1}();la.supportDualStreamEncoding=
function(){let a=V();return"Safari"===a.name&&14<=Number(a.version)}();k.info("browser compatibility",A(la),A(a))})();let nb={__CLIENT_LIST__:pc,__TRACK_LIST__:Bc,VERSION:ob,BUILD:"v4.7.3-0-g0eb931c7(11/16/2021, 7:46:22 PM)",setParameter:eb,getParameter:function(a){return v[a]},getSupportedCodec:async function(a){let b=null;a?(b=new En({}),b.addStream(a)):b=new Fn({});a=Oj(await b.createOfferSDP());return b.close(),a},checkSystemRequirements:function(){const a=u.reportApiInvoke(null,{name:D.CHECK_SYSTEM_REQUIREMENTS,
options:[],tag:C.TRACER});var b=!1;try{var c=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,e=window.WebSocket;b=!!(window.RTCPeerConnection&&c&&e)}catch(f){return k.error("check system requirement failed: ",f),!1}c=!1;e=V();e.name===S.CHROME&&58<=Number(e.version)&&("WebKit"!==cb.engine.name||Zn())&&(c=!0);e.name===S.FIREFOX&&56<=Number(e.version)&&(c=!0);e.name===S.OPERA&&45<=Number(e.version)&&(c=!0);e.name===S.SAFARI&&11<=Number(e.version)&&(c=!0);V().name!==S.WECHAT&&V().name!==
S.QQ||(c=!0);k.debug("checkSystemRequirements, api:",b,"browser",c);b=b&&c;return a.onSuccess(b),b},getDevices:function(a){return lb.enumerateDevices(!0,!0,a)},getMicrophones:function(a){return lb.getRecordingDevices(a)},getCameras:function(a){return lb.getCamerasDevices(a)},getElectronScreenSources:fj,getPlaybackDevices:function(a){return lb.getSpeakers(a)},createClient:function(a={codec:"vp8",mode:"rtc"}){const b=u.reportApiInvoke(null,{name:D.CREATE_CLIENT,options:[a],tag:C.TRACER});try{fb(a.codec,
"config.codec",["vp8","vp9","av1","h264"]),fb(a.mode,"config.mode",["rtc","live"]),void 0!==a.proxyServer&&Sa(a.proxyServer,"config.proxyServer",1,1E4),void 0!==a.turnServer&&Yi(a.turnServer),void 0!==a.httpRetryConfig&&Wi(a.httpRetryConfig),void 0!==a.websocketRetryConfig&&Wi(a.websocketRetryConfig),!0}catch(c){throw b.onError(c),c;}return b.onSuccess(),new Gd(jd({forceWaitGatewayResponse:!0},a,{role:"rtc"===a.mode?"host":a.role}))},createCameraVideoTrack:async function(a={encoderConfig:"480p_1"}){const b=
u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_CAM_VIDEO_TRACK,options:[xg({},a)]}),c=sg(a);var e=va(8,"track-cam-");let f=null;k.info("start create camera video track with config",A(a),"trackId",e);try{f=(await Fb({video:c},e)).getVideoTracks()[0]||null}catch(h){throw b.onError(h),h;}if(!f)return e=new q(n.UNEXPECTED_ERROR,"can not find track in media stream"),b.onError(e),e.throw();a.optimizationMode&&yg(e,f,a,a.encoderConfig&&bd(a.encoderConfig));a=new ve(f,a,c,a.scalabiltyMode?Fe(a.scalabiltyMode):
{numSpatialLayers:1,numTemporalLayers:1},a.optimizationMode,e);return b.onSuccess(a.getTrackId()),k.info("create camera video success, trackId:",e),a},createCustomVideoTrack:function(a){const b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_CUSTOM_VIDEO_TRACK,options:[a]}),c=new ta(a.mediaStreamTrack,{bitrateMax:a.bitrateMax,bitrateMin:a.bitrateMin},a.scalabiltyMode?Fe(a.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},a.optimizationMode);return b.onSuccess(c.getTrackId()),k.info("create custom video track success with config",
a,"trackId",c.getTrackId()),c},createScreenVideoTrack:async function(a={},b="disable"){const c=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_SCREEN_VIDEO_TRACK,options:[xg({},a),b]});a.encoderConfig?"string"==typeof a.encoderConfig||a.encoderConfig.width&&a.encoderConfig.height||(a.encoderConfig.width={max:1920},a.encoderConfig.height={max:1080}):a.encoderConfig="1080p_2";var e={};a.screenSourceType&&(e.mediaSource=a.screenSourceType);a.extensionId&&Kd()&&(e.extensionId=a.extensionId);a.electronScreenSourceId&&
(e.sourceId=a.electronScreenSourceId);var f=a.encoderConfig?Uf(a.encoderConfig):null;f=(e.mandatory={chromeMediaSource:"desktop",maxWidth:f?f.width:void 0,maxHeight:f?f.height:void 0},f&&f.frameRate&&("number"==typeof f.frameRate?(e.mandatory.maxFrameRate=f.frameRate,e.mandatory.minFrameRate=f.frameRate):(e.mandatory.maxFrameRate=f.frameRate.max||f.frameRate.ideal||f.frameRate.exact||void 0,e.mandatory.minFrameRate=f.frameRate.min||f.frameRate.ideal||f.frameRate.exact||void 0),e.frameRate=f.frameRate),
f&&f.width&&(e.width=f.width),f&&f.height&&(e.height=f.height),e);const h=va(8,"track-scr");let l=null;e=null;const m=la;if(!m.supportShareAudio&&"enable"===b)return a=new q(n.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio"),c.onError(a),a.throw();k.info("start create screen video track with config",a,"withAudio",b,"trackId",h);try{const a=await Fb({screen:f,screenAudio:"auto"===b?m.supportShareAudio:"enable"===b},h);l=a.getVideoTracks()[0]||null;e=a.getAudioTracks()[0]||
null}catch(p){throw c.onError(p),p;}if(!l)return a=new q(n.UNEXPECTED_ERROR,"can not find track in media stream"),c.onError(a),a.throw();if(!e&&"enable"===b)return l&&l.stop(),a=new q(n.SHARE_AUDIO_NOT_ALLOWED),c.onError(a),a.throw();a.optimizationMode||(a.optimizationMode="detail");a.optimizationMode&&(yg(h,l,a,a.encoderConfig&&Uf(a.encoderConfig)),a.encoderConfig&&"string"!=typeof a.encoderConfig&&(a.encoderConfig.bitrateMin=a.encoderConfig.bitrateMax));a=new ta(l,a.encoderConfig?Uf(a.encoderConfig):
{},a.scalabiltyMode?Fe(a.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},a.optimizationMode,h);if(a._hints.push(Yb.SCREEN_TRACK),!e)return c.onSuccess(a.getTrackId()),k.info("create screen video track success","video:",a.getTrackId()),a;b=new La(e);return c.onSuccess([a.getTrackId(),b.getTrackId()]),k.info("create screen video track success","video:",a.getTrackId(),"audio:",b.getTrackId()),[a,b]},createMicrophoneAndCameraTracks:async function(a={},b={encoderConfig:"480p_1"}){var c,e,f;const h=
u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_MIC_AND_CAM_TRACKS,options:[a,b]}),l=sg(b),r=Mj(a),p=va(8,"track-mic-"),t=va(8,"track-cam-");let v=null,x=null;k.info(m(c=m(e=m(f="start create camera video track(".concat(t,") and microphone audio track(")).call(f,p,") with config, audio: ")).call(e,A(a),", video: ")).call(c,A(b)));try{var y;const a=await Fb({audio:r,video:l},m(y="".concat(p,"-")).call(y,t));v=a.getAudioTracks()[0];x=a.getVideoTracks()[0]}catch(ra){throw h.onError(ra),ra;}if(!v||
!x){var z=new q(n.UNEXPECTED_ERROR,"can not find tracks in media stream");return h.onError(z),z.throw()}b.optimizationMode&&yg(t,x,b,b.encoderConfig&&bd(b.encoderConfig));a=new ne(v,a,r,p);b=new ve(x,b,l,b.scalabiltyMode?Fe(b.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},b.optimizationMode,t);return h.onSuccess([a.getTrackId(),b.getTrackId()]),k.info(m(z="create camera video track(".concat(t,") and microphone audio track(")).call(z,p,") success")),[a,b]},createMicrophoneAudioTrack:async function(a=
{}){const b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_MIC_AUDIO_TRACK,options:[a]}),c=Mj(a);var e=va(8,"track-mic-");let f=null;k.info("start create microphone audio track with config",A(a),"trackId",e);try{f=(await Fb({audio:c},e)).getAudioTracks()[0]||null}catch(h){throw b.onError(h),h;}if(!f)return e=new q(n.UNEXPECTED_ERROR,"can not find track in media stream"),b.onError(e),e.throw();a=new ne(f,a,c,e);return b.onSuccess(a.getTrackId()),k.info("create microphone audio track success, trackId:",
e),a},createCustomAudioTrack:function(a){const b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_CUSTOM_AUDIO_TRACK,options:[a]}),c=new La(a.mediaStreamTrack,a.encoderConfig?Ge(a.encoderConfig):{});return k.info("create custom audio track success with config",a,"trackId",c.getTrackId()),b.onSuccess(c.getTrackId()),c},createBufferSourceAudioTrack:async function(a){const b=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CREATE_BUFFER_AUDIO_TRACK,options:[a]}),c=va(8,"track-buf-");k.info("start create buffer source audio track with config",
A(a),"trackId",c);const e=a.source;if(!(a.source instanceof AudioBuffer))try{a.source=await Bo(a.source,a.cacheOnlineFile)}catch(h){return b.onError(h),h.throw()}const f=new Gs(a.source);a=new Cd(e,f,a.encoderConfig?Ge(a.encoderConfig):{},c);return k.info("create buffer source audio track success, trackId:",c),b.onSuccess(a.getTrackId()),a},setLogLevel:function(a){k.setLogLevel(a)},enableLogUpload:function(){k.enableLogUpload()},disableLogUpload:function(){k.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new Yj},
checkAudioTrackIsActive:async function(a,b=5E3){const c=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[b]});if(!(a instanceof La||a instanceof xe)){var e=new q(n.INVALID_TRACK,"the parameter is not a audio track");return c.onError(e),e.throw()}b&&1E3>b&&(b=1E3);const f=a instanceof La?a.getTrackLabel():"remote_track";let h=e=a.getVolumeLevel(),l=e;const r=x();return new y(e=>{const n=Hs(()=>{var p=a.getVolumeLevel();h=p>h?p:h;l=p<l?p:l;p=1E-4<h-l;var q=x()-r;if(p||
q>b){var t;clearInterval(n);q={duration:q,deviceLabel:f,maxVolumeLevel:h,result:p};k.info(m(t="[track-".concat(a.getTrackId(),"] check audio track active completed. ")).call(t,A(q)));c.onSuccess(q);e(p)}},200)})},checkVideoTrackIsActive:async function(a,b=5E3){var c;const e=u.reportApiInvoke(null,{tag:C.TRACER,name:D.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[b]});if(!(a instanceof ta||a instanceof we))return a=new q(n.INVALID_TRACK,"the parameter is not a video track"),e.onError(a),a.throw();b&&1E3>b&&
(b=1E3);var f=a instanceof ta?a.getTrackLabel():"remote_track",h=a.getMediaStreamTrack(!0);const l=document.createElement("video");l.style.width="1px";l.style.height="1px";l.setAttribute("muted","");l.muted=!0;l.setAttribute("playsinline","");l.controls=!1;($c()||Ee())&&(l.style.opacity="0.01",l.style.position="fixed",l.style.left="0",l.style.top="0",document.body.appendChild(l));l.srcObject=new MediaStream([h]);l.play();const r=document.createElement("canvas");r.width=160;r.height=120;let p=h=0;
try{const a=x();h=await function(a,b,c,e){let f,h=0,l=null;return new y((m,p)=>{wb(()=>{f&&(f(),m(h))},b);f=dg(()=>{a:{h>e&&f&&(f(),m(h));var b=c.getContext("2d");if(b){b.drawImage(a,0,0,160,120);b=b.getImageData(0,0,c.width,c.height);var r=Math.floor(b.data.length/3);if(l)for(let a=0;a<r;a+=3)if(b.data[a]!==l[a]){h+=1;l=b.data;break a}l=b.data}else b=new q(n.UNEXPECTED_ERROR,"can not get canvas 2d context."),k.error(b.toString()),p(b)}},30)})}(l,b,r,4);p=x()-a}catch(w){throw e.onError(w),w;}Is===
S.SAFARI&&(l.pause(),l.remove());l.srcObject=null;b=4<h;f={duration:p,changedPicNum:h,deviceLabel:f,result:b};return k.info(m(c="[track-".concat(a.getTrackId(),"] check video track active completed. ")).call(c,A(f))),e.onSuccess(f),b},setArea:function(a){const b=u.reportApiInvoke(null,{name:D.SET_AREA,options:a,tag:C.TRACER});try{var c;let b=[];if("string"==typeof a&&(b=[a]),Qb(a)&&(t(a).call(a,a=>{if(!Z(hm).call(hm,a))throw new q(n.INVALID_PARAMS,"invalid area code");}),b=a),"[object Object]"===
Object.prototype.toString.call(a)){const {areaCode:c,excludedArea:e}=a;if(!c)throw new q(n.INVALID_PARAMS,"area code is needed");a=c;"string"==typeof c&&(a=[c]);b=e?cs(a,e):a}eb("AREAS",b);const f=(a=>{const b={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return z(a).call(a,a=>{const c=nh[a];(a=W(c))&&z(a).call(a,a=>{var e;"CODE"!==a&&(b[a]=m(e=
b[a]).call(e,c[a]))})}),b})(b);z(c=W(f)).call(c,a=>{"LOG_UPLOAD_SERVER"===a||"EVENT_REPORT_DOMAIN"===a||"EVENT_REPORT_BACKUP_DOMAIN"===a||"PROXY_SERVER_TYPE3"===a?eb(a,f[a][0]):eb(a,f[a])});k.debug("set area success:",b.join(","))}catch(e){throw b.onError(e),e;}b.onSuccess()},loadModule:async function(a,b){var c;if(k.debug(m(c="loadModule: ".concat(a.name,", loadOption: ")).call(c,A(b))),!a.moduleInit)throw k.debug("Invalid Plugin"),new q(n.INVALID_PLUGIN,"invalid plugin");try{await a.moduleInit({logger:k,
report:u},b)}catch(e){throw new q(n.UNEXPECTED_ERROR,"unexpected error in loadModule",e);}},processExternalMediaAEC:function(a){Ks.processExternalMediaAEC(a)}};return lb.on(qc.CAMERA_DEVICE_CHANGED,a=>{k.info("camera device changed",A(a));nb.onCameraChanged&&nb.onCameraChanged(a)}),lb.on(qc.RECORDING_DEVICE_CHANGED,a=>{k.info("microphone device changed",A(a));nb.onMicrophoneChanged&&nb.onMicrophoneChanged(a)}),lb.on(qc.PLAYOUT_DEVICE_CHANGED,a=>{k.debug("playout device changed",A(a));nb.onPlaybackDeviceChanged&&
nb.onPlaybackDeviceChanged(a)}),Bb.onAutoplayFailed=()=>{k.info("detect audio element autoplay failed");nb.onAudioAutoplayFailed&&nb.onAudioAutoplayFailed()},da.on("autoplay-failed",()=>{k.info("detect webaudio autoplay failed");nb.onAudioAutoplayFailed&&nb.onAudioAutoplayFailed()}),kj.on("autoplay-failed",()=>{k.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web");nb.onAutoplayFailed?nb.onAutoplayFailed():nb.onAudioAutoplayFailed?k.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\nPlease refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):
k.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\nIt will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\nPlease refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .")}),window&&(window.__ARTC__=nb),nb})
//# sourceMappingURL=AgoraRTC_N-production.js.map
