@rongcloud/plugin-rtc 5.2.1 → 5.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +70 -6
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -12,4 +12,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
|
12
12
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
13
13
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
14
14
|
PERFORMANCE OF THIS SOFTWARE.
|
|
15
|
-
***************************************************************************** */function t(e,t,r,i){return new(r||(r=Promise))((function(n,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}const r=new e.Logger("RCRTC");var i,n;exports.RCRTCCode=void 0,(i=exports.RCRTCCode||(exports.RCRTCCode={}))[i.SUCCESS=1e4]="SUCCESS",i[i.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",i[i.PARAMS_ERROR=50001]="PARAMS_ERROR",i[i.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",i[i.NOT_IN_ROOM=50003]="NOT_IN_ROOM",i[i.SERVICE_INVALID=50004]="SERVICE_INVALID",i[i.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",i[i.SIGNAL_ERROR=53001]="SIGNAL_ERROR",i[i.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",i[i.REQUEST_FAILED=53004]="REQUEST_FAILED",i[i.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",i[i.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",i[i.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",i[i.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",i[i.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",i[i.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",i[i.PERMISSION_DENIED=53012]="PERMISSION_DENIED",i[i.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",i[i.INVALID_TAGS=53014]="INVALID_TAGS",i[i.INVALID_USER_ID=53015]="INVALID_USER_ID",i[i.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",i[i.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",i[i.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",i[i.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",i[i.TRACK_NOT_READY=53020]="TRACK_NOT_READY",i[i.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",i[i.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",i[i.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",i[i.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",i[i.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",i[i.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",i[i.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",i[i.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",i[i.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(n||(n={}));class o{constructor(){this.queue=[],this.locked=!1}checkToStart(){return t(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e){const t=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),t}}const s=new o,a=e=>s.push(e);let c=!0,d=!0;function u(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function l(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const o=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),n.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(r))return o.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function p(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(c=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function h(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(d=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function m(){if("object"==typeof window){if(c)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function _(e,t){d&&console.warn(e+" is deprecated, please use "+t+" instead.")}function C(e){return"[object Object]"===Object.prototype.toString.call(e)}function R(e){return C(e)?Object.keys(e).reduce((function(t,r){const i=C(e[r]),n=i?R(e[r]):e[r],o=i&&!Object.keys(n).length;return void 0===n||o?t:Object.assign(t,{[r]:n})}),{}):e}function f(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?f(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{f(e,e.get(t),r)}))})))}function v(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&f(e,r,n)}))})),n}const T=m;function g(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let s=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!s&&r.length&&t.includes("back")&&(s=r[r.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),T("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return T("chrome: "+JSON.stringify(e)),n(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(o(e))))))}}}function S(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function y(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else l(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function E(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.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 I(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},o=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(o(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(o(n(t)))},r])})).then(r,i)}}function k(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>v(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),l(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>v(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function b(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function x(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return b(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[r.id];if(o)o.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=o(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=s(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function O(e,t){l(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var L=Object.freeze({__proto__:null,shimMediaStream:S,shimOnTrack:y,shimGetSendersWithDtmf:E,shimGetStats:I,shimSenderReceiverGetStats:k,shimAddTrackRemoveTrackWithNative:b,shimAddTrackRemoveTrack:x,shimPeerConnection:P,fixNegotiationNeeded:O,shimGetUserMedia:g,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,o=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var D,A,N=(D=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var o=i[n],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){var a=t.parseRtpMap(s),c=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var n=0;return r.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],n=t.parseRtpParameters(e),o=-1!==n.fecMechanisms.indexOf("RED"),s=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),o&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;var o=t.matchPrefix(e,"a=rtcp-mux");return r.mux=o.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(r=n[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);var o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var s=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(s[0],10),protocol:s[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var n=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,n){var o=t.writeRtpDescription(e.kind,r);if(o+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),o+="a=mid:"+e.mid+"\r\n",e.direction?o+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var s="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";o+="a="+s,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+s,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+s,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),o},t.getDirection=function(e,r){for(var i=t.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},D(A={exports:{}},A.exports),A.exports);function M(e,t,r,i,n){var o=N.writeRtpDescription(e.kind,t);if(o+=N.writeIceParameters(e.iceGatherer.getLocalParameters()),o+=N.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":n||"active"),o+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?o+="a=sendrecv\r\n":e.rtpSender?o+="a=sendonly\r\n":e.rtpReceiver?o+="a=recvonly\r\n":o+="a=inactive\r\n",e.rtpSender){var s=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=s;var a="msid:"+(i?i.id:"-")+" "+s+"\r\n";o+="a="+a,o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,o+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return o+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+N.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(o+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+N.localCName+"\r\n"),o}function w(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var o=i(e.parameters.apt,r),s=i(t.parameters.apt,n);return o&&s&&o.name.toLowerCase()===s.name.toLowerCase()};return e.codecs.forEach((function(i){for(var o=0;o<t.codecs.length;o++){var s=t.codecs[o];if(i.name.toLowerCase()===s.name.toLowerCase()&&i.clockRate===s.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&s.parameters.apt&&!n(i,s,e.codecs,t.codecs))continue;(s=JSON.parse(JSON.stringify(s))).numChannels=Math.min(i.numChannels,s.numChannels),r.codecs.push(s),s.rtcpFeedback=s.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function U(e,t,r){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"]}}[t][e].indexOf(r)}function $(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function j(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var V=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,n){var o=new Event("track");o.track=r,o.receiver=i,o.transceiver={receiver:i},o.streams=n,e.setTimeout((function(){t._dispatchEvent("track",o)}))}var n=function(r){var i=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=n[e].bind(n)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw j("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var o=r.iceCandidatePoolSize;o>0;o--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=N.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},n.prototype.addTrack=function(t,r){if(this._isClosed)throw j("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw j("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},n.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw j("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw j("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,r){var i=this,n=this.transceivers[r].iceGatherer;if(!n.onlocalcandidate){var o=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),n.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var o=new Event("icecandidate");o.candidate={sdpMid:t,sdpMLineIndex:r};var s=e.candidate,a=!s||0===Object.keys(s).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),s.component=1,s.ufrag=n.getLocalParameters().usernameFragment;var c=N.writeCandidate(s);o.candidate=Object.assign(o.candidate,N.parseCandidate(c)),o.candidate.candidate=c,o.candidate.toJSON=function(){return{candidate:o.candidate.candidate,sdpMid:o.candidate.sdpMid,sdpMLineIndex:o.candidate.sdpMLineIndex,usernameFragment:o.candidate.usernameFragment}}}var d=N.getMediaSections(i._localDescription.sdp);d[o.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+o.candidate.candidate+"\r\n",i._localDescription.sdp=N.getDescription(i._localDescription.sdp)+d.join("");var u=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",o),u&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){o.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,r,i){var n=w(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:N.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),i&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(j("TypeError",'Unsupported type "'+e.type+'"'));if(!U("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(j("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=N.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=N.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=N.splitSections(i._remoteDescription.sdp),r=t.shift();var n=N.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var o=i.transceivers[t],s=o.iceGatherer,a=o.iceTransport,c=o.dtlsTransport,d=o.localCapabilities,u=o.remoteCapabilities;if(!(N.isRejected(e)&&0===N.matchPrefix(e,"a=bundle-only").length)&&!o.rejected){var l=N.getIceParameters(e,r),p=N.getDtlsParameters(e,r);n&&(p.role="server"),i.usingBundle&&0!==t||(i._gather(o.mid,t),"new"===a.state&&a.start(s,l,n?"controlling":"controlled"),"new"===c.state&&c.start(p));var h=w(d,u);i._transceive(o,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var o=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(j("TypeError",'Unsupported type "'+n.type+'"'));if(!U("setRemoteDescription",n.type,o.signalingState)||o._isClosed)return Promise.reject(j("InvalidStateError","Can not set remote "+n.type+" in state "+o.signalingState));var s={};o.remoteStreams.forEach((function(e){s[e.id]=e}));var a=[],c=N.splitSections(n.sdp),d=c.shift(),u=N.matchPrefix(d,"a=ice-lite").length>0,l=N.matchPrefix(d,"a=group:BUNDLE ").length>0;o.usingBundle=l;var p=N.matchPrefix(d,"a=ice-options:")[0];return o.canTrickleIceCandidates=!!p&&p.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var p=N.splitLines(i),h=N.getKind(i),m=N.isRejected(i)&&0===N.matchPrefix(i,"a=bundle-only").length,_=p[0].substr(2).split(" ")[2],C=N.getDirection(i,d),R=N.parseMsid(i),f=N.getMid(i)||N.generateIdentifier();if(m||"application"===h&&("DTLS/SCTP"===_||"UDP/DTLS/SCTP"===_))o.transceivers[c]={mid:f,kind:h,protocol:_,rejected:!0};else{var v,T,g,S,y,E,I,k,b;!m&&o.transceivers[c]&&o.transceivers[c].rejected&&(o.transceivers[c]=o._createTransceiver(h,!0));var x,P,O=N.parseRtpParameters(i);m||(x=N.getIceParameters(i,d),(P=N.getDtlsParameters(i,d)).role="client"),I=N.parseRtpEncodingParameters(i);var L=N.parseRtcpParameters(i),D=N.matchPrefix(i,"a=end-of-candidates",d).length>0,A=N.matchPrefix(i,"a=candidate:").map((function(e){return N.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!m&&l&&c>0&&o.transceivers[c]&&(o._disposeIceAndDtlsTransports(c),o.transceivers[c].iceGatherer=o.transceivers[0].iceGatherer,o.transceivers[c].iceTransport=o.transceivers[0].iceTransport,o.transceivers[c].dtlsTransport=o.transceivers[0].dtlsTransport,o.transceivers[c].rtpSender&&o.transceivers[c].rtpSender.setTransport(o.transceivers[0].dtlsTransport),o.transceivers[c].rtpReceiver&&o.transceivers[c].rtpReceiver.setTransport(o.transceivers[0].dtlsTransport)),"offer"!==n.type||m){if("answer"===n.type&&!m){T=(v=o.transceivers[c]).iceGatherer,g=v.iceTransport,S=v.dtlsTransport,y=v.rtpReceiver,E=v.sendEncodingParameters,k=v.localCapabilities,o.transceivers[c].recvEncodingParameters=I,o.transceivers[c].remoteCapabilities=O,o.transceivers[c].rtcpParameters=L,A.length&&"new"===g.state&&(!u&&!D||l&&0!==c?A.forEach((function(e){$(v.iceTransport,e)})):g.setRemoteCandidates(A)),l&&0!==c||("new"===g.state&&g.start(T,x,"controlling"),"new"===S.state&&S.start(P)),!w(v.localCapabilities,v.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&v.sendEncodingParameters[0].rtx&&delete v.sendEncodingParameters[0].rtx,o._transceive(v,"sendrecv"===C||"recvonly"===C,"sendrecv"===C||"sendonly"===C),!y||"sendrecv"!==C&&"sendonly"!==C?delete v.rtpReceiver:(b=y.track,R?(s[R.stream]||(s[R.stream]=new e.MediaStream),r(b,s[R.stream]),a.push([b,y,s[R.stream]])):(s.default||(s.default=new e.MediaStream),r(b,s.default),a.push([b,y,s.default])))}}else{(v=o.transceivers[c]||o._createTransceiver(h)).mid=f,v.iceGatherer||(v.iceGatherer=o._createIceGatherer(c,l)),A.length&&"new"===v.iceTransport.state&&(!D||l&&0!==c?A.forEach((function(e){$(v.iceTransport,e)})):v.iceTransport.setRemoteCandidates(A)),k=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),E=v.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,U=!1;if("sendrecv"===C||"sendonly"===C){if(U=!v.rtpReceiver,y=v.rtpReceiver||new e.RTCRtpReceiver(v.dtlsTransport,h),U)b=y.track,R&&"-"===R.stream||(R?(s[R.stream]||(s[R.stream]=new e.MediaStream,Object.defineProperty(s[R.stream],"id",{get:function(){return R.stream}})),Object.defineProperty(b,"id",{get:function(){return R.track}}),M=s[R.stream]):(s.default||(s.default=new e.MediaStream),M=s.default)),M&&(r(b,M),v.associatedRemoteMediaStreams.push(M)),a.push([b,y,M])}else v.rtpReceiver&&v.rtpReceiver.track&&(v.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===v.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),v.associatedRemoteMediaStreams=[]);v.localCapabilities=k,v.remoteCapabilities=O,v.rtpReceiver=y,v.rtcpParameters=L,v.sendEncodingParameters=E,v.recvEncodingParameters=I,o._transceive(o.transceivers[c],!1,U)}}})),void 0===o._dtlsRole&&(o._dtlsRole="offer"===n.type?"active":"passive"),o._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?o._updateSignalingState("have-remote-offer"):o._updateSignalingState("stable"),Object.keys(s).forEach((function(t){var r=s[t];if(r.getTracks().length){if(-1===o.remoteStreams.indexOf(r)){o.remoteStreams.push(r);var n=new Event("addstream");n.stream=r,e.setTimeout((function(){o._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];r.id===e[2].id&&i(o,t,n,[r])}))}})),a.forEach((function(e){e[2]||i(o,e[0],e[1],[])})),e.setTimeout((function(){o&&o.transceivers&&o.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},n.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(j("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,n=r.transceivers.filter((function(e){return"video"===e.kind})).length,o=arguments[0];if(o){if(o.mandatory||o.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==o.offerToReceiveAudio&&(i=!0===o.offerToReceiveAudio?1:!1===o.offerToReceiveAudio?0:o.offerToReceiveAudio),void 0!==o.offerToReceiveVideo&&(n=!0===o.offerToReceiveVideo?1:!1===o.offerToReceiveVideo?0:o.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));i>0||n>0;)i>0&&(r._createTransceiver("audio"),i--),n>0&&(r._createTransceiver("video"),n--);var s=N.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var o=i.track,s=i.kind,a=i.mid||N.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(n,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(s);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];o&&t>=15019&&"video"===s&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,s)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(s+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),s+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){s+=M(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),s+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,s+="a="+N.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(s+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:s});return Promise.resolve(a)},n.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(j("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(j("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=N.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var n=N.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,o){if(!(o+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var s;if(e.stream)"audio"===e.kind?s=e.stream.getAudioTracks()[0]:"video"===e.kind&&(s=e.stream.getVideoTracks()[0]),s&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=w(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=M(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var o=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(o)},n.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,n){if(!r._remoteDescription)return n(j("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var o=e.sdpMLineIndex;if(e.sdpMid)for(var s=0;s<r.transceivers.length;s++)if(r.transceivers[s].mid===e.sdpMid){o=s;break}var a=r.transceivers[o];if(!a)return n(j("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?N.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===o||o>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!$(a.iceTransport,c))return n(j("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=N.getMediaSections(r._remoteDescription.sdp))[o]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=N.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=N.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=N.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);i()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw j("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var o=["createOffer","createAnswer"];return o.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(o=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n};function B(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function F(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function H(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=V(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&_("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),m("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function G(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var J=Object.freeze({__proto__:null,shimPeerConnection:H,shimReplaceTrack:G,shimGetUserMedia:B,shimGetDisplayMedia:F});function W(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){_("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Y(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function K(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,o]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,o)}}function q(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function z(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),l(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Q(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){_("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function X(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Z(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function ee(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function te(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function re(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var ie=Object.freeze({__proto__:null,shimOnTrack:Y,shimPeerConnection:K,shimSenderGetStats:q,shimReceiverGetStats:z,shimRemoveStream:Q,shimRTCDataChannel:X,shimAddTransceiver:Z,shimGetParameters:ee,shimCreateOffer:te,shimCreateAnswer:re,shimGetUserMedia:W,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function ne(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function oe(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function se(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function ae(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(ce(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function ce(e){return e&&void 0!==e.video?Object.assign({},e,{video:R(e.video)}):e}function de(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(_("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ue(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function le(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function pe(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var he=Object.freeze({__proto__:null,shimLocalStreamsAPI:ne,shimRemoteStreamsAPI:oe,shimCallbacksAPI:se,shimGetUserMedia:ae,shimConstraints:ce,shimRTCIceServerUrls:de,shimTrackEventTransceiver:ue,shimCreateOfferLegacy:le,shimAudioContext:pe});function me(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=N.parseCandidate(e.candidate),n=Object.assign(r,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,l(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function _e(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=N.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=N.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},o=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=N.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=n(e),r=o(arguments[0],e);let s;s=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function Ce(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},l(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Re(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function fe(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function ve(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var Te=Object.freeze({__proto__:null,shimRTCIceCandidate:me,shimMaxMessageSize:_e,shimSendThrowTypeError:Ce,shimConnectionState:Re,removeExtmapAllowMixed:fe,shimAddIceCandidateNullOrEmpty:ve});const ge=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=m,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=u(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=u(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=u(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=u(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Te,extractVersion:u,disableLog:p,disableWarnings:h};switch(i.browser){case"chrome":if(!L||!P||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=L,ve(e,i),g(e,i),S(e),P(e,i),y(e),x(e,i),E(e),I(e),k(e),O(e,i),me(e),Re(e),_e(e,i),Ce(e),fe(e,i);break;case"firefox":if(!ie||!K||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=ie,ve(e,i),W(e,i),K(e,i),Y(e),Q(e),q(e),z(e),X(e),Z(e),ee(e),te(e),re(e),me(e),Re(e),_e(e,i),Ce(e);break;case"edge":if(!J||!H||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=J,B(e),F(e),H(e,i),G(e),_e(e,i),Ce(e);break;case"safari":if(!he||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=he,ve(e,i),de(e),le(e),se(e),ne(e),oe(e),ue(e),ae(e),pe(e),me(e),_e(e,i),Ce(e),fe(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var Se,ye;exports.RCFrameRate=void 0,(Se=exports.RCFrameRate||(exports.RCFrameRate={})).FPS_10="FPS_10",Se.FPS_15="FPS_15",Se.FPS_24="FPS_24",Se.FPS_30="FPS_30",exports.RCResolution=void 0,(ye=exports.RCResolution||(exports.RCResolution={})).W176_H132="W176_H132",ye.W176_H144="W176_H144",ye.W256_H144="W256_H144",ye.W320_H180="W320_H180",ye.W240_H240="W240_H240",ye.W320_H240="W320_H240",ye.W480_H360="W480_H360",ye.W640_H360="W640_H360",ye.W480_H480="W480_H480",ye.W640_H480="W640_H480",ye.W720_H480="W720_H480",ye.W1280_H720="W1280_H720",ye.W1920_H1080="W1920_H1080";const Ee={[exports.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[exports.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[exports.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[exports.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[exports.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[exports.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[exports.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[exports.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[exports.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[exports.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[exports.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[exports.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[exports.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Ie=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in Ee){const t=Ee[e],o=Math.abs(t.width*t.height-r);o<i&&(n=t,i=o)}return n},ke={10:1,15:1,24:1.5,30:1.5},be=e=>{let t=Number.MAX_VALUE,r=1;for(const i in ke){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=ke[i])}return r},xe={getCameras:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class Pe extends e.EventEmitter{constructor(e,t,r,i,n){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=n,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){r.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){r.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(i,n){return t(this,void 0,void 0,(function*(){if(!this._msTrack)return r.warn(`the track is not ready to play -> id: ${this._id}`),{code:exports.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&r.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==n?void 0:n.volume){if(!e.isNumber(null==n?void 0:n.volume))return r.error(`${null==n?void 0:n.volume} is not a number, the valid range of options.volume is 0-100`),{code:exports.RCRTCCode.PARAMS_ERROR};(null==n?void 0:n.volume)<0&&(n.volume=0,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==n?void 0:n.volume)>100&&(n.volume=100,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==n?void 0:n.audioDeviceId){if(!(yield xe.getSpeakers()).map((e=>e.deviceId)).includes(n.audioDeviceId))return r.error(`the options.audioDeviceId is invalid --\x3e ${n.audioDeviceId}`),{code:exports.RCRTCCode.PARAMS_ERROR}}const t=this.isVideoTrack();if(t&&(!i||!(i instanceof HTMLVideoElement)))return r.error(`the video track need an <video> to play -> id: ${this._id}`),{code:exports.RCRTCCode.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=t?i:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t;r.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;r.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;r.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;r.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;r.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;r.info(`HTMLMediaElement oncanplay -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onvolumechange=e=>{var t;const i=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));r.info(`HTMLMediaElement onvolumechange -> volume: ${i}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,t&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),t||!(null==n?void 0:n.volume)&&0!==(null==n?void 0:n.volume)||(this._element.volume=(null==n?void 0:n.volume)/100);try{(null==n?void 0:n.audioDeviceId)&&!t?yield this._element.setSinkId(n.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(r.error(`setSinkId failed -> ${e.message}`),{code:exports.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(r.error(e),{code:exports.RCRTCCode.TRACK_PLAY_ERROR})}return{code:exports.RCRTCCode.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class Oe extends Pe{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(Oe.EVENT_LOCAL_TRACK_END,this),this.removeAll(Oe.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(Oe.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;r.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(Oe.__INNER_EVENT_DESTROY__,this)}setBitrate(t=0,i=0,n=0){!e.isNumber(t)||!e.isNumber(i)||!e.isNumber(n)||t<=0||i<=0||t<i?r.error("setBitrate params error ->"):this._bitrateInfo={max:t,min:i,start:n}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?Je(this._msTrack):{min:0,max:0};return{min:(null===(e=this._bitrateInfo)||void 0===e?void 0:e.min)||r,max:(null===(t=this._bitrateInfo)||void 0===t?void 0:t.max)||i}}}Oe.EVENT_LOCAL_TRACK_END="local-track-end",Oe.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Oe.__INNER_EVENT_DESTROY__="inner-destroy";class Le extends Oe{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,i){r.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class De extends Oe{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}}class Ae extends Oe{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,Ae.__innerSetMapping(this.getTrackId(),n)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const n=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));n&&n.length>0?this._mapping.set(t,n):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Ae.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Ae._mapping=new Map;class Ne extends Ae{constructor(e,t,r,i){super(e,t,"video",r,i)}}class Me extends Ae{constructor(e,t,r,i){super(e,t,"audio",r,i)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:exports.RCRTCCode.SUCCESS})}}class we extends Le{}class Ue extends De{}class $e extends De{}const je=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ve=e=>JSON.stringify(e),Be=e=>/^[a-zA-Z\d-=]+$/g.test(e),Fe="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),He=t=>{if(void 0===t)return 0;if(e.isNumber(t))return t;const r=t;return r.exact||r.ideal||r.max||0},Ge=e=>{const t=e.getConstraints();return{width:He(t.width),height:He(t.height),frameRate:He(t.frameRate)}},Je=e=>{const{width:t,height:r,frameRate:i}=Ge(e),n=Ie(t,r),o=be(i);return{min:n.minBitrate*o,max:n.maxBitrate*o}},We=e=>[e.msid,e.mediaType].join("_"),Ye=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Ke=(e,t)=>[e,t].join("_"),qe=e=>e.map((e=>Object.assign({},e))),ze=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],o=[];return t.forEach((t=>{const n=We(t);let s=e.findIndex((e=>We(e)===n));if(r&&(s=e.findIndex((e=>e.uri===t.uri))),-1===s)return void i.push(t);const a=e[s];a.uri!==t.uri?i.push(t):a.state!==t.state&&o.push(t),e.splice(s,1)})),n.push(...e),{publishedList:i,unpublishedList:n,modifiedList:o}},Qe=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const n=[];do{const e=i%r;i=(i-e)/r,n.unshift(t[e])}while(i);return n.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},Xe=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},Ze=e=>!!exports.RCResolution[e],et=e=>!!exports.RCFrameRate[e],tt=e=>parseInt(e.replace("FPS_","")),rt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=ge.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function it(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function nt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const ot=e=>"[object Null]"===Object.prototype.toString.call(e),st=e=>1===e.type,at=e=>{const t={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const n=[],o=e.users[i];if(o.uris)try{n.push(...JSON.parse(o.uris))}catch(e){r.warn(`invalid user data -> userId: ${i}, userData: ${o}`)}t[i]=n})),t};var ct,dt;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick"}(ct||(ct={})),exports.RCRTCPingResult=void 0,(dt=exports.RCRTCPingResult||(exports.RCRTCPingResult={})).SUCCESS="Success",dt.FAIL="Fail";class ut{constructor(e,t,r,i=1e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._latestTimestamp=Date.now(),this._timer=null}start(){return t(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var i,n,o;return t(this,void 0,void 0,(function*(){const t=yield new Promise((t=>{this._context.rtcPing(this._roomId,this._roomMode).then(t).catch((i=>{r.error(`rtcping receive unknown error -> ${i}`),t(e.ErrorCode.UNKNOWN)})),setTimeout(t,1e4,e.ErrorCode.TIMEOUT)})),s=Date.now();if(t===e.ErrorCode.SUCCESS)return this._latestTimestamp=s,void(null===(i=this.onPingResult)||void 0===i||i.call(this,exports.RCRTCPingResult.SUCCESS));null===(n=this.onPingResult)||void 0===n||n.call(this,exports.RCRTCPingResult.FAIL),r.warn(`rtcping failed -> code: ${t}`),(40003===t||s-this._latestTimestamp>6e4)&&(this.stop(),null===(o=this.onFailed)||void 0===o||o.call(this,40003===t))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var lt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(lt||(lt={}));const pt=(e,t)=>Math.round(8*t/e),ht=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},mt=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.floor(e*r)},_t=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return ht(e/t,3);const n=t-i;if(0===n)return 0;const o=e-r;return o<0||n<0?0:ht(o/n,3)},Ct=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!ot(t)||!ot(r)||0!==i};var Rt;exports.RCMediaType=void 0,(Rt=exports.RCMediaType||(exports.RCMediaType={}))[Rt.AUDIO_ONLY=0]="AUDIO_ONLY",Rt[Rt.VIDEO_ONLY=1]="VIDEO_ONLY",Rt[Rt.AUDIO_VIDEO=2]="AUDIO_VIDEO";class ft{constructor(e,t){this._rtcPeerConn=e,this._sdpSemantics=t,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,n;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:o,timestamp:s}=this._latestBytesSent[e];i=t-o,n=r-s,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,n=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return pt(n,i)}updateBytesRecv(e,t,r){let i,n;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:o,timestamp:s}=this._latestBytesRecv[e];i=t-o,n=r-s,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,n=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return pt(n,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:n,packetsSent:o}=this._latestPacketsSent[e];i=_t(t,r,n,o),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?o:r}else i=_t(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:n,packetsRecv:o}=this._latestPacketsRecv[e];i=_t(t,r+t,n,o+n)}else i=_t(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===exports.RCMediaType.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const n=i.value,o=e.get(n);/^RTCCodec_/.test(n)||(r[n]=o),i=t.next()}return r}formatRCRTCStateReport(e){return{senders:[],receivers:[]}}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,n=e.kind||e.mediaType,o=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,s=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==o?void 0:o.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],u=null==d?void 0:d.match(a);let l=u?u[1]:"";if(l)return`${l}_${"video"===n?1:0}`;const p=null==s?void 0:s.split("\r\nm="),h=null==p?void 0:p.filter((e=>e.includes(`a=ssrc:${i}`)))[0],m=null==h?void 0:h.match(a);return l=m?m[1]:"",`${l}_${"video"===n?1:0}`}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class vt extends ft{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(s))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:l,packetsSent:p,bytesSent:h,trackId:m,encoderImplementation:_,pliCount:C,nackCount:R,firCount:f}=s;if(!m)return;let{framesPerSecond:v,frameWidth:T,frameHeight:g}=s;"video"!==c||T||g||v||(T=e[m].frameWidth,g=e[m].frameHeight,v=u?e[u].framesPerSecond:null);const S=e[l];let y=null,E=null,I=0;S&&(y=S.jitter,E=S.roundTripTime,I=S.packetsLost),n+=I;const k=this.getResourceIdByParseSdp(s),b=u?e[u].audioLevel:e[m].audioLevel;let x=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),S?x=this.updateSenderPacketsLost(k,I,p):this._latestPacketsSent[k].crtPacketsSent=p;let P=this.updateBytesSent(k,h,r);P<0&&(P=0),o+=P,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:x,remoteResource:!1,audioLevel:b||0===b?mt(b):null,frameWidth:T,frameHeight:g,frameRate:v,bitrate:P,jitter:y?Math.round(1e3*y):y,rtt:E,encoderImplementation:_,pliCount:C,nackCount:R,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:n,roundTripTime:o,packetsLost:s}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!Ct(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*n),a.rtt=o;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,s,r)}}));let s=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,framesPerSecond:p,kind:h,codecImplementationName:m,nackCount:_,pliCount:C}=o;if(!a)return;let{frameWidth:R,frameHeight:f,audioLevel:v}=o;"video"===h?R||f||(R=e[a].frameWidth,f=e[a].frameHeight):v||(v=e[a].audioLevel),n+=c;const T=this.getResourceIdByParseSdp(o),g=this.updateReceiverPacketsLost(T,c,d);let S=this.updateBytesRecv(T,l,r);S<0&&(S=0),s+=S,t.receivers.push({trackId:T,kind:h,packetsLostRate:g,remoteResource:!0,audioLevel:v||0===v?mt(v):null,frameWidth:R,frameHeight:f,frameRate:p,bitrate:S,jitter:u?Math.round(1e3*u):0,codecImplementationName:m,nackCount:_,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,p=e[u],{ip:h,port:m,networkType:_}=p,C=e[l],{ip:R,port:f,protocol:v}=C;t.iceCandidatePair={IP:h,port:m,networkType:_,remoteIP:R,remotePort:f,protocol:v,bitrateRecv:s,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const n=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{mediaSourceId:o,trackId:s}=n,a=this.getResourceIdByParseSdp(n),c=o&&e[o]?e[o].audioLevel:(null===(i=e[s])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?mt(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n}=i,{audioLevel:o}=i||e[n],s=this.getResourceIdByParseSdp(i);t.push({trackId:s,audioLevel:o||0===o?mt(o):null})})),t}}class Tt extends ft{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,n=0,o=0;for(const s in e){const a=e[s],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:o,kind:s,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:l,nackCount:p,pliCount:h,remoteId:m}=a,{jitter:_,roundTripTime:C,packetsLost:R}=m?e[m]:{jitter:null,roundTripTime:null,packetsLost:0},f=this.getResourceIdByParseSdp(a);i+=R;let v=null;!this._latestPacketsSent[f]&&(this._latestPacketsSent[f]={}),m?v=this.updateSenderPacketsLost(f,R,d):this._latestPacketsSent[f].crtPacketsSent=d;let T=0;"video"===s?u&&(T=Math.floor(u/1e3)):T=this.updateBytesSent(f,c,t),T<0&&(T=0),n+=T,r.senders.push({trackId:f,kind:s,packetsLostRate:v,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:T,jitter:_?Math.round(1e3*_):null,rtt:C,encoderImplementation:null,pliCount:h,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),n=r.senders.filter((e=>e.trackId===i))[0];n&&Ct(n)&&(n.jitter=Math.round(1e3*a.jitter),n.rtt=a.rtt,n.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:n,bytesReceived:s,packetsReceived:c,jitter:d,framerateMean:u,kind:l,bitrateMean:p,nackCount:h,pliCount:m}=a,_=this.getResourceIdByParseSdp(a);i+=n;const C=this.updateReceiverPacketsLost(_,n,c);let R=0;"video"===l?p&&(R=Math.floor(p/1e3)):R=this.updateBytesRecv(_,s,t),R<0&&(R=0),o+=R,r.receivers.push({trackId:_,kind:l,packetsLostRate:C,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:R,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:s,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:l,protocol:p}=d;r.iceCandidatePair={IP:s,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:p,bitrateRecv:o,bitrateSend:n,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=n),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=o),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],n=i.type;if("outbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class gt extends ft{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,o=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const s=this.getResourceIdByParseSdp(n),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:l,trackId:p,encoderImplementation:h,pliCount:m,nackCount:_,firCount:C}=n;if(!p)return;const{audioLevel:R,frameHeight:f,frameWidth:v}=e[p];let T=this.updateBytesSent(s,l,r);T<0&&(T=0),o+=T,t.senders.push({trackId:s,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:R||0===R?mt(R):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:T,jitter:null,rtt:null,encoderImplementation:h,pliCount:m,nackCount:_,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let s=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(o))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,mediaType:p,nackCount:h,pliCount:m}=o,_=this.getResourceIdByParseSdp(o);if(!a)return;const{frameHeight:C,frameWidth:R,audioLevel:f}=e[a];n+=c;const v=this.updateReceiverPacketsLost(_,c,d);let T=this.updateBytesRecv(_,l,r);T<0&&(T=0),s+=T,t.receivers.push({trackId:_,kind:p,packetsLostRate:v,remoteResource:!0,audioLevel:f||0===f?mt(f):null,frameWidth:R,frameHeight:C,frameRate:null,bitrate:T,jitter:u,codecImplementationName:null,nackCount:h,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,p=e[u],{address:h,port:m}=p,_=e[l],{address:C,port:R,protocol:f}=_;t.iceCandidatePair={IP:h||null,port:m,networkType:null,remoteIP:C,remotePort:R,protocol:f,bitrateRecv:s,bitrateSend:o,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:n,mediaType:o}=i;if("video"===o)return;const s=this.getResourceIdByParseSdp(i),a=e[n];t.push({trackId:s,audioLevel:a||0===a?mt(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n,mediaType:o}=i;if(!n||"video"===o)return;const{audioLevel:s}=e[n],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:s||0===s?mt(s):null})})),t}}class St{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:r,supportsUnifiedPlan:i}=rt;i?/chrome/i.test(t)?this._sdpSemantics=r>92?"unified-plan":r<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=r<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return St._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:n,height:o}=Ge(r);e.push({trackId:r.id,simulcast:i?lt.TINY:lt.NORMAL,resolution:`${n}x${o}`})}return e}setRemoteAnswer(e){return t(this,void 0,void 0,(function*(){e=e.replace(/\s+\r\n/g,"\r\n");try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return r.error(e),exports.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return exports.RCRTCCode.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(rt.browser)?new vt(e,t):/Firefox/i.test(rt.browser)?new Tt(e,t):/Safari/i.test(rt.browser)?new gt(e,t):null}}class yt extends St{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const n=e.getTrackId(),o=this.senders[n];o?o.replaceTrack(r):this.senders[n]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return t(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){let t=0,r=0;this._localTracks.forEach((e=>{const{min:i,max:n}=e.getBitrate();r+=i,t+=n})),t=this._maxBitrate&&this._maxBitrate>0?Math.min(t,this._maxBitrate):t,r=this._minBitrate&&this._minBitrate>0?Math.max(r,this._minBitrate):r;const i=this._startBitrate||Math.round(.7*t),n=`b=AS:${t}`;e=e.replace(/[\r\n]+m=video[^\r\n]+/,(e=>`${e}\r\n${n}`));const o=[`;x-google-min-bitrate=${r}`,`;x-google-max-bitrate=${t}`,`;x-google-start-bitrate=${i}`].join("");return e=e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+o)),super.setRemoteAnswer(e)}}class Et extends St{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,i){r.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const n=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);n.getTracks().forEach((e=>{e.kind===i.kind&&n.removeTrack(e)})),n.addTrack(i);const o=this._sendTransceiver[t];o?(o.sender.replaceTrack(i),o.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[n]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const n=this._outboundStreams[r];(e.isAudioTrack()?n.getAudioTracks():n.getVideoTracks()).forEach((e=>n.removeTrack(e)));const o=this._sendTransceiver[`${t}_tiny`];if(!o||"inactive"===o.direction)return;o.direction="inactive";const s=o.sender,a=s.track;this._peer.removeTrack(s),s.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Ye(e);this._recvTransceiver[e]=t;const i=r===exports.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,n=i.findIndex((e=>e===t));n>=0&&i.splice(n,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],n=r.findIndex((e=>e===i));n>=0&&(t.splice(e,1),r.splice(n,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);this._recvTransceiver[t].direction="inactive"}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return t(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=(e=>e.split(/\r\n(?=m=)/).map((e=>(e=>/a=(recvonly|inactive)/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/g,""):e)(e))).join("\r\n"))(r),r=r.replace(/a=ice-options:trickle/g,"a=ice-options:trickle\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=e.split(/\r\n(?=m=)/).map((e=>{var t;const r=e.match(/a=mid:[^\s]+/);if(!r)return e;const i=r[0].replace("a=mid:","");let n="";for(const e in this._sendTransceiver){if(this._sendTransceiver[e].mid===i){n=e;break}}if(!n)return e;const o=null===(t=this._localTracks[n])||void 0===t?void 0:t.getBitrate();if(!o)return e;const{max:s,min:a}=o,c=s&&s>0?o.start||.7*s:0,d=[];if(s&&s>0&&d.push(`;x-google-max-bitrate=${s}`),a&&a>0&&d.push(`;x-google-min-bitrate=${a}`),c>0&&d.push(`;x-google-start-bitrate=${c}`),0===d.length)return e;const u=d.join("");return e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+u))})).join("\r\n");const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(r.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class It extends e.EventEmitter{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=St.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new yt(i):new Et(i),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,r)}getLocalTracks(){return Object.values(this.pubLocalTracks)}_onConnectionStateChange(){r.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;r.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(r.warn("iceconenction state is `failed`, exchange SDP to try again."),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState)}catch(e){r.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){const t=[e.streams[0].id,"audio"===e.receiver.track.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(It.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,r,i){return t(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,r,i)}))}createOffer(e){return t(this,void 0,void 0,(function*(){return yield this._sdpStrategy.createOffer(e)}))}setRemoteAnswer(e){return t(this,void 0,void 0,(function*(){return this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(Oe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Oe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Oe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Oe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}removeLocalTrackById(e){const t=this.getLocalTrack(e);t&&this.removeLocalTrack(t)}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)}))}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(Oe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Oe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const r=`${t}_tiny`,i=this.getLocalTrack(r);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[r],i.destroy())}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e)}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(Oe.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(Oe.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:n}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)ot(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:n.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t}))}}_getStatsData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);return null===(r=this.reportParser)||void 0===r?void 0:r.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);if(!i)return[];return null===(r=this.reportParser)||void 0===r?void 0:r.getAudioLevelList(i)}))}_reportHandle(){var e,r,i;return t(this,void 0,void 0,(function*(){const t=yield this._getStatsData();if(!t)return;(t.senders.length||t.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(t));const n=this._createRCRTCStateReport(t);null===(i=null===(r=this._reportListener)||void 0===r?void 0:r.onStateReport)||void 0===i||i.call(r,n)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this.reportParser=null}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}var kt,bt,xt,Pt,Ot;It.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(kt||(kt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(bt||(bt={}));class Lt{constructor(e,t,r,i,n=bt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(t){this._context.getConnectionStatus()===e.ConnectionStatus.CONNECTED&&this._context.setRTCState(this._roomId,t)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Qe(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){const{iceCandidatePair:t,senders:r,receivers:i}=e,n=(null==t?void 0:t.bitrateSend)||-1,o=(null==t?void 0:t.bitrateRecv)||-1,s=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),u=(null==t?void 0:t.availableOutgoingBitrate)||-1,l=(null==t?void 0:t.totalPacketsLost)||-1,p=this._context.getCurrentId();let h=`R3\t${n}\t-1\t-1\t-1\t${s}\t${a}\t${c}\t${d}\t${u}\t${l}\t${p}\r`,m=`R4\t${o}\t-1\t-1\t-1\t${s}\t${a}\t${c}\t${d}\t${u}\t${l}\t${p}\r`;const _=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:o,packetsLostRate:s,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:p,pliCount:h,rtt:m,googFirsSent:_,encoderImplementation:C}=e,R=this._getPolarisTrackId(r),f=this._getRealResourceId(r);return{trackId:R,googCodecName:C||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:s||0===s?s:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:p||0===p?p:-1,pliCount:h||0===h?h:-1,rtt:m||-1,googFirsSent:_,samplingRate:n,googRenderDelayMs:u,encoderImplementation:C||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(f))||void 0===t?void 0:t.isLocalMuted())?kt.DISABLE:kt.ENABLE}})),C=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:o,packetsLostRate:s,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:p,pliCount:h,rtt:m,googFirsReceived:_,codecImplementationName:C}=e,R=this._getPolarisTrackId(r),f=this._getRealResourceId(r);return{trackId:R,googCodecName:C||String(-1),audioLevel:i||0===i?i:-1,bitrate:o||0===o?o:-1,packetsLostRate:s||0===s?s:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:p||0===p?p:-1,pliCount:h||0===h?h:-1,rtt:m||-1,googFirsReceived:_,samplingRate:n,googRenderDelayMs:u,codecImplementationName:C||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(f))||void 0===t?void 0:t.isLocalMuted())?kt.DISABLE:kt.ENABLE}}));h+=_.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&this._send(h+`\r${this._userRole}`),m+=C.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&this._send(m+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.2.1\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${rt.browser}\t${rt.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}class Dt extends Pe{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e}isSubscribed(){return this._isSubscribed}}class At extends Dt{constructor(e,t,r){super(e,t,"audio",r)}}class Nt extends Dt{constructor(e,t,r){super(e,t,"video",r)}}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(xt||(xt={})),function(e){e.BEGIN="begin",e.END="end"}(Pt||(Pt={}));class Mt{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return t(this,void 0,void 0,(function*(){if("new"===this._pc.getRTCPeerConn().iceConnectionState||!this._audioLevelChangeHandler)return;const e=(yield this._pc.getAudioLevelReportData()).map((e=>{const{userId:t}=sr.parseTrackId(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?r.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}exports.RCRTCLiveRole=void 0,(Ot=exports.RCRTCLiveRole||(exports.RCRTCLiveRole={}))[Ot.ANCHOR=1]="ANCHOR",Ot[Ot.AUDIENCE=2]="AUDIENCE";const wt=e=>e instanceof Pe?e.getTrackId():e.track.getTrackId();class Ut{constructor(e,t,i,n,s,c,d,u,l){this._context=e,this._runtime=t,this._roomId=i,this._roomMode=s,this._service=c,this._initOptions=d,this._ntfClearRoomItem=u,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new o,this._appListener=null,this._token=n.token,this._sessionId=n.sessionId,this._roomResources=l?{}:at(n),this._initRemoteTracks();const p=this._context.getCurrentId(),h=this._roomResources[p]=this._roomResources[p]||[];r.debug(`room data -> ${JSON.stringify(this._roomResources)}`),h.length>0&&a((()=>this._unpublishPrev(h))),l&&this._afterChangedRole(n),this._pinger=new ut(i,this._roomMode,e,this._initOptions.pingGap),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),this._polarisReport=new Lt(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new It(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(It.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(Oe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(Oe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}_initRemoteTracks(){const e=this._context.getCurrentId();for(const t in this._roomResources){const r=this._roomResources[t];t!==e&&0!==r.length&&r.forEach((e=>{const t=We(e),{tag:r,userId:i,mediaType:n}=Ye(t),o=n===exports.RCMediaType.AUDIO_ONLY?new At(r,i):new Nt(r,i);o.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=o}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(t,i,n){r.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),e.assert("max",t,(t=>e.isNumber(t)&&t>Math.max(i||1,200)),!0),e.assert("min",i,(r=>e.isNumber(r)&&r>=1&&(!e.isNumber(t)||r<t)),!0),e.assert("start",n,(r=>e.isNumber(r)&&r>i&&r<=t)),this._pc.setBitrate(t,i,n)}_onTrackReady(e){const t=e.streams[0].id,i=e.receiver.track,n=[t,"audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),o=this._remoteTracks[n];o?(o.__innerSetMediaStreamTrack(i),this._callAppListener("onTrackReady",o)):r.warn(`cannot found remote track ${i.id}`)}_callAppListener(e,...t){var i;const n=null===(i=this._appListener)||void 0===i?void 0:i[e];if(n)try{n(...t)}catch(e){r.error(e)}}_onUserUnpublish(e){return t(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._onTrackUnpublish(e)}))}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}_unpublishPrev(i){return t(this,void 0,void 0,(function*(){const t=i.slice();i.length=0,r.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const n=yield this._context.setRTCTotalRes(this._roomId,je(ct.UNPUBLISH,t),Ve([]),ct.TOTAL_CONTENT_RESOURCE,Ve([]));n!==e.ErrorCode.SUCCESS?r.error(`unpublish prev uris failed -> code: ${n}`):r.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(t){const{targetId:i,conversationType:n}=t;if(n!==e.ConversationType.RTC_ROOM)return!1;if(i!==this._roomId)return!0;r.info(`recv inner msg -> message: ${JSON.stringify(t)} | roomid: ${this._roomId}`);const o=t.content;switch(t.messageType){case ct.KICK:this._kickoff(!0,o);break;case ct.STATE:this.msgTaskQueue.push((()=>this._stateHandle(o)));break;case ct.MODIFY:case ct.PUBLISH:case ct.UNPUBLISH:case ct.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(o,t.messageType,t.senderUserId)));break;case ct.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",t.messageType,t.content);break;case ct.USER_NOTIFY:r.warn(`TODO: ${ct.USER_NOTIFY}`);break;default:this._callAppListener("onMessageReceive",t.messageType,t.content,t.senderUserId,t.messageUId)}return!0}_kickoff(e,t){let i;r.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(i=e.type)})),this._callAppListener("onKickOff",e,i)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,i,n){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void r.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:t,ignore:o}=e;if(o)return;const s=[],c=[],d=[];let u;const l=this._roomResources[n]||(this._roomResources[n]=[]);switch(i){case ct.MODIFY:d.push(...t);break;case ct.PUBLISH:s.push(...t);break;case ct.UNPUBLISH:c.push(...t);break;case ct.TOTAL_CONTENT_RESOURCE:u=ze(l,t),s.push(...u.publishedList),c.push(...u.unpublishedList),d.push(...u.modifiedList)}if(s.length>0){const e=l.map(We),t=[],i=[];if(s.forEach((r=>{const n=We(r),o=e.indexOf(n),{userId:s,tag:a,mediaType:c}=Ye(n);o>-1?l[o]=r:l.push(r);let d=this._remoteTracks[n];d?d.isSubscribed()&&t.push(d):(d=c===exports.RCMediaType.AUDIO_ONLY?new At(a,s):new Nt(a,s),this._remoteTracks[n]=d,i.push(d)),d.__innerSetRemoteMuted(0===r.state)})),t.length){const e=t.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:i}=yield a((()=>this.__subscribe(t,!0)));i!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${i}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(i)}if(c.length>0){const e=c.map(We);for(let t=l.length-1;t>=0;t-=1){const r=l[t];e.includes(We(r))&&l.splice(t,1)}const t=c.map((e=>{const t=We(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(d.length>0){const e=l.map(We);for(let t=0;t<d.length;t+=1){const r=d[t],i=We(r),n=e.indexOf(i);l[n].state=r.state;const o=this._remoteTracks[i];o.__innerSetRemoteMuted(0===r.state),o.isAudioTrack()?this._onAudioMuteChange(o):this._onVideoMuteChange(o)}}}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var i;return t(this,void 0,void 0,(function*(){const{users:t}=e;if(0===t.length)return;const n=[],o=[],s=[],a=[];t.forEach((e=>{0==+e.state?(r.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?s.push(e.userId):n.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(r.debug(`user left -> ${e.userId}`),e.switchRoleType?a.push(e.userId):o.push(e.userId))}));const c=[...n,...s],d=[...o,...a];if(d.length){const e=[],t=[];d.forEach((r=>{e.push(...this.getRemoteTracksByUserId(r)),t.push(r)})),e.length&&(yield this.unsubscribe(e),e.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),t.length&&t.forEach((e=>delete this._roomResources[e]))}if(null===(i=this._appListener)||void 0===i?void 0:i.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.ANCHOR))),a.length&&a.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.AUDIENCE))),n.length&&this._callAppListener("onUserJoin",n),void(o.length&&this._callAppListener("onUserLeave",o));c.length&&this._callAppListener("onUserJoin",c),d.length&&this._callAppListener("onUserLeave",d)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._pc}getRemoteUserIds(){const e=this._context.getCurrentId();return Object.keys(this._roomResources).filter((t=>t!==e))}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getSessionId(){return this._sessionId}sendMessage(i,n){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.sendMessage(e.ConversationType.RTC_ROOM,this._roomId,{messageType:i,content:n,isStatusMessage:!0});return t!==e.ErrorCode.SUCCESS?(r.error(`send message failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}setRoomAttribute(i,n,o,s=!1){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,i,n,s,e.RTCApiType.ROOM,o);return t!==e.ErrorCode.SUCCESS?(r.error(`SetRoomAttributeValue Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}deleteRoomAttributes(i,n,o=!1){return t(this,void 0,void 0,(function*(){const t=yield this._context.removeRTCData(this._roomId,i,o,e.RTCApiType.ROOM,n);return t!==e.ErrorCode.SUCCESS?(r.error(`DeleteRoomAttribute Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}getRoomAttributes(i=[],n=!1){return t(this,void 0,void 0,(function*(){const{code:t,data:o}=yield this._context.getRTCData(this._roomId,i,n,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`GetRoomAttributes Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS,data:o}}))}_setUserAttributeValue(t,r,i){return this._context.setRTCData(this._roomId,t,r,!1,e.RTCApiType.PERSON,i)}_deleteUserAttributes(t,r){return this._context.removeRTCData(this._roomId,t,!1,e.RTCApiType.PERSON,r)}_getUserAttributes(t){return this._context.getRTCData(this._roomId,t,!1,e.RTCApiType.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var r;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._pc.removeAllLocalTrack(),this._pinger.stop(),yield this._service.exit(this._getRTCReqestHeaders()),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof De&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(i){return t(this,void 0,void 0,(function*(){const t=i.getTrackId(),n=this._context.getCurrentId(),o=[{resourceId:t,enabled:!i.isLocalMuted()}],s=this._roomResources[n]||[],c=[];for(let e=0;e<s.length;e+=1){const t=s[e],r=We(t),i=o.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=o[i];t.state=e?1:0,c.push(t);break}}const d=yield a((()=>this._context.setRTCTotalRes(this._roomId,je(ct.MODIFY,c),Ve(s),ct.TOTAL_CONTENT_RESOURCE)));d!==e.ErrorCode.SUCCESS&&r.error("notice `track.enabled` change failed -> code: "+d)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof Oe?e:e.track;r.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__publish(e)))}))}__publish(i){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Oe||e.track instanceof Oe))),!0))return r.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof Oe?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(i)>10)return r.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED};r.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`),i.forEach((e=>{const{track:t,pubTiny:i}=e instanceof Oe?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&i){let e;try{e=t.__innerGetMediaStreamTrack().clone();const r=i.frameRate||exports.RCFrameRate.FPS_15,n=i.resolution||exports.RCResolution.W176_H144,{width:o,height:s}=Xe(n),a=tt(r);e.applyConstraints({width:o,height:s,frameRate:a})}catch(i){return null==e||e.stop(),void r.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${i.message}`)}this._pc.addLocalTrack(new De(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const n=yield this._createExchangeParams(this._subscribedList,!1),o=yield this._exchangeHandle(n);if(o.code!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${this._roomId}, code: ${o.code}`),this._removePubFailedTracks(i),{code:o.code};const{publishList:s,sdp:a,resultCode:c,message:d,urls:u,mcuPublishList:l}=o.data;if(c!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${this._roomId}, code: ${c}, msg: ${d}`),this._removePubFailedTracks(i),{code:c};const p=yield this._pc.setRemoteAnswer(a.sdp);if(p!==exports.RCRTCCode.SUCCESS)return{code:p};const h=this._roomResources[t],m=s.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(We(e))},e))),{publishedList:_}=ze(h,m),C=(null==l?void 0:l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],R=yield this._context.setRTCTotalRes(this._roomId,je(ct.PUBLISH,_),Ve(m),ct.TOTAL_CONTENT_RESOURCE,Ve(C));if(R!==e.ErrorCode.SUCCESS)return r.error(`send publish streams notification failed: ${R}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._roomResources[t]=m;const f=_.map((e=>We(e)));return this._polarisReport&&this._polarisReport.sendR2(xt.PUBLISH,Pt.BEGIN,f),i.forEach((e=>{const{track:t}=e instanceof Oe?{track:e}:e;t.__innerSetPublished(!0)})),r.debug(`publish success: ${f.join(",")}`),this._roomMode===e.RTCMode.LIVE?{code:exports.RCRTCCode.SUCCESS,liveUrl:null==u?void 0:u.liveUrl}:{code:exports.RCRTCCode.SUCCESS}}))}_reTryExchange(){return t(this,void 0,void 0,(function*(){a((()=>t(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=yield this._exchangeHandle(e);if(t.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${t.code}`),{code:t.code};const{sdp:i,resultCode:n}=t.data;if(n!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const o=yield this._pc.setRemoteAnswer(i.sdp);return o!==exports.RCRTCCode.SUCCESS?{code:o}:void 0}))))}))}_exchangeHandle(e){return this._service.exchange(this._getRTCReqestHeaders(),e)}_getRTCReqestHeaders(){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._token,RoomType:this._roomMode,UserId:this._context.getCurrentId()}}_createExchangeParams(e,r){return t(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(r),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{var t;const r=e.track.getTrackId(),{userId:i}=Ye(r),n=null===(t=this._roomResources[i])||void 0===t?void 0:t.filter((e=>r===`${e.msid}_${e.mediaType}`)).length;return n})).map((e=>({simulcast:e.subTiny?lt.TINY:lt.NORMAL,resolution:"",uri:this._getResourceById(e.track.getTrackId()).uri}))),switchstream:!1}}))}_getResourceState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}unpublish(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unpublish(e)))}))}__unpublish(i){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.SUCCESS};const t=this._context.getCurrentId();if(!e.validate("tracks",i,(()=>i.every((e=>e.getUserId()===t&&e instanceof Oe))),!0))return r.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`),{code:exports.RCRTCCode.PARAMS_ERROR};const o=i.map((e=>e.getTrackId())),s=o.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===s.length)return{code:exports.RCRTCCode.SUCCESS};const a=this._roomResources[t].filter((e=>!s.includes(e)));o.forEach((e=>this._pc.removeLocalTrackById(e))),null===(n=this._polarisReport)||void 0===n||n.sendR2(xt.PUBLISH,Pt.END,o),this._pc.clearReTryExchangeTimer();const c=yield this._createExchangeParams(this._subscribedList,!1),d=yield this._exchangeHandle(c);if(d.code!==exports.RCRTCCode.SUCCESS)return r.error(`exchange failed -> code: ${d.code}`),{code:d.code};const{publishList:u,sdp:l,resultCode:p,message:h,mcuPublishList:m}=d.data;p!==exports.RCRTCCode.SUCCESS&&r.error(`unpublish streams failed -> code: ${p}, msg: ${h}`);const _=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],C=yield this._context.setRTCTotalRes(this._roomId,je(ct.UNPUBLISH,s),Ve(a),ct.TOTAL_CONTENT_RESOURCE,Ve(_));if(C!==e.ErrorCode.SUCCESS)return r.error("send unpublish notification failed:",C),{code:exports.RCRTCCode.SIGNAL_ERROR};r.debug(`unpublish success -> tracks: ${o.join(",")}`);const R=yield this._pc.setRemoteAnswer(l.sdp);if(R!==exports.RCRTCCode.SUCCESS)return{code:R};const f=u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(We(e))},e)));return this._roomResources[t]=f,{code:exports.RCRTCCode.SUCCESS}}))}_getResourceById(e){const{userId:t}=Ye(e);return this._roomResources[t].find((t=>We(t)===e))}_isValidResourceId(e){var t;const{userId:r}=Ye(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>We(t)===e)))}subscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__subscribe(e,!1)))}))}__subscribe(i,n=!1){var o;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Dt||e.track instanceof Dt))),!0))return r.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`subscribe -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`);const t=this._subscribedList.map((e=>Object.assign({},e))),s=i.map((e=>e instanceof Dt?{track:e}:e));let a=!1;const c=[];return s.forEach((e=>{const r=e.track.getTrackId();c.push(r);const i=t.find((e=>e.track.getTrackId()===r));i&&i.subTiny===e.subTiny||(i?i.subTiny=e.subTiny:t.push(e),a=!0)})),a||n?(null===(o=this._polarisReport)||void 0===o||o.sendR2(xt.SUBSCRIBE,Pt.BEGIN,c),this._updateSubListHandle(t,!0)):{code:exports.RCRTCCode.SUCCESS}}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe(e)))}))}__unsubscribe(i){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.SUCCESS};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Dt))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`);const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(xt.SUBSCRIBE,Pt.END,i.map((e=>e.getTrackId()))),this._updateSubListHandle(t,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}getLocalTrack(e){return this._pc.getLocalTrack(e)}getLocalTracks(){return this._pc.getLocalTracks()}getRemoteTrack(e){return this._remoteTracks[e]||null}updateSubList(e){return t(this,void 0,void 0,(function*(){return a((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(i,n=!1){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",i,(()=>e.isArray(i)&&i.every((e=>e instanceof Dt||e.track instanceof Dt))),!0))return r.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${n}, tracks: ${i.map(wt)}`);let t=i.map((e=>e instanceof Dt?{track:e}:Object.assign({},e)));const o={};t=t.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!o[t]&&(o[t]=!0):(r.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const s=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let e=!1;if(t.forEach((t=>{const r=s.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);s.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),s.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const a=yield this._createExchangeParams(t,!1),c=yield this._exchangeHandle(a),d=t.map((e=>e.track.getTrackId()));if(c.code!==exports.RCRTCCode.SUCCESS)return{code:c.code};const{sdp:u,resultCode:l,message:p}=c.data;if(l!==exports.RCRTCCode.SUCCESS)return r.error(`change subscribe list failed: ${l}`),{code:l};r.debug(`subscribe success: ${d.join(",")}`);const h=yield this._pc.setRemoteAnswer(u.sdp);if(h!==exports.RCRTCCode.SUCCESS)return{code:h};for(const e in this._remoteTracks){const r=t.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(r)}return this._subscribedList.splice(0,this._subscribedList.length,...t),{code:exports.RCRTCCode.SUCCESS}}))}registerRoomEventListener(e){this._appListener=e}registerReportListener(e){this._pc.registerReportListener(e)}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Mt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(i){return t(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return r.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:n}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,i);if(t!==e.ErrorCode.SUCCESS)return void r.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);r.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(n)}`);const o=[],s={},a={},c={},d=at(n),u=Object.keys(d),l=Object.keys(this._roomResources);for(let e=u.length-1;e>=0;e-=1){const t=u[e],r=l.indexOf(t);if(-1===r){o.push(t),s[t]=qe(d[t]);continue}const i=this._roomResources[t],n=d[t],{publishedList:p,modifiedList:h,unpublishedList:m}=ze(i,n,!0);s[t]=qe(p),a[t]=qe(m),c[t]=qe(h),l.splice(r,1)}l.length&&l.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,d),l.length&&this._callAppListener("onUserLeave",l),o.length&&this._callAppListener("onUserJoin",o);for(const e in a){const t=a[e];if(t.length){const e=t.map((e=>this._remoteTracks[We(e)]));yield this._onUserUnpublish(e)}}return Object.keys(s).forEach((e=>{const t=s[e];if(0===t.length)return;const r=t.map((e=>{const t=We(e),{userId:r,tag:i,mediaType:n}=Ye(t),o=this._remoteTracks[t]=n===exports.RCMediaType.AUDIO_ONLY?new At(i,r):new Nt(i,r);return o.__innerSetRemoteMuted(0===e.state),o}));this._onTrackPublish(r)})),Object.keys(c).forEach((e=>{c[e].forEach((e=>{const t=We(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:n}}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_afterChangedRole(e){}_removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}}var $t,jt,Vt;exports.BackgroundPictureFillMode=void 0,($t=exports.BackgroundPictureFillMode||(exports.BackgroundPictureFillMode={}))[$t.CROP=1]="CROP",$t[$t.WHOLE=2]="WHOLE",exports.MixLayoutMode=void 0,(jt=exports.MixLayoutMode||(exports.MixLayoutMode={}))[jt.CUSTOMIZE=1]="CUSTOMIZE",jt[jt.SUSPENSION=2]="SUSPENSION",jt[jt.ADAPTATION=3]="ADAPTATION",exports.MixVideoRenderMode=void 0,(Vt=exports.MixVideoRenderMode||(exports.MixVideoRenderMode={}))[Vt.CROP=1]="CROP",Vt[Vt.WHOLE=2]="WHOLE";const Bt=()=>({version:1,mode:exports.MixLayoutMode.SUSPENSION});class Ft{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=Bt()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return r.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:i,userId:n}=Ye(e);return t!==exports.RCMediaType.VIDEO_ONLY?(r.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=Ke(n,i),this)}setMixLayoutMode(e){return[exports.MixLayoutMode.CUSTOMIZE,exports.MixLayoutMode.SUSPENSION,exports.MixLayoutMode.ADAPTATION].includes(e)?(this._values.mode=e,this):(r.error(`layout mode is invalid: ${e}`),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const n=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=n.backgroundPicture||(n.backgroundPicture={fillMode:exports.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(e,t)}}else n.exparams={renderMode:t};else n.backgroundColor=t;else{const e=n[r]||(n[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(!Ze(e))return r.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:i}=Xe(e);return this._addOutputValue("video",{width:t,height:i},"normal"),this}setOutputVideoFPS(e){if(!et(e))return r.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=tt(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(t){return!e.isNumber(t)||t<=0?r.error(`bitrate is invalid: ${t}`):this._addOutputValue("video",{bitrate:t},"normal"),this}setOutputTinyVideoResolution(e){if(!Ze(e))return r.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:i}=Xe(e);return this._addOutputValue("video",{width:t,height:i},"tiny"),this}setOutputTinyVideoFPS(e){if(!et(e))return r.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=tt(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(t){return!e.isNumber(t)||t<=0?r.error(`bitrate is invalid: ${t}`):this._addOutputValue("video",{bitrate:t},"tiny"),this}setOutputVideoRenderMode(e){return[exports.MixVideoRenderMode.CROP,exports.MixVideoRenderMode.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):r.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(t){return e.isNumber(t)&&t>0?this._addOutputValue("audio",t):r.error(`bitrate is invalid: ${t}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):r.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(t,i,n,o,s){var a,c,d;if(!e.isHttpUrl(t))return r.error(`uri is invalid: ${t}`),this;if([i,n,o,s].some((t=>!e.isNumber(t)||t<0||t>1)))return r.error(`some attrs of (x, y, w, h) is invalid: ${i}, ${n}, ${o}, ${s}`),this;const u=(null===(d=null===(c=null===(a=this._values.output)||void 0===a?void 0:a.video)||void 0===c?void 0:c.backgroundPicture)||void 0===d?void 0:d.picture)||[];return u.push({uri:t,w:o,h:s,x:i,y:n}),this._addOutputValue("video",{picture:u},"backgroundPicture"),this}removeOutputBackgroundPicture(t){var i,n,o;if(!e.isHttpUrl(t))return r.error(`uri is invalid: ${t}`),this;let s=null===(o=null===(n=null===(i=this._values.output)||void 0===i?void 0:i.video)||void 0===n?void 0:n.backgroundPicture)||void 0===o?void 0:o.picture;return s&&(s=s.filter((e=>e.uri!==t)),this._addOutputValue("video",{pictures:s},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[exports.BackgroundPictureFillMode.CROP,exports.BackgroundPictureFillMode.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):r.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(t){var i,n;const o=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!o.test(e))))return r.error(`urls is invalid: ${t}`),this;const s=(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.cdn)||void 0===n?void 0:n.concat())||[];let a=!1;return t.forEach((e=>{s.some((t=>t.pushurl===e))||(a=!0,s.push({pushurl:e}))})),s.length>5?(r.error("publish stream url no more than 5"),this):(a&&this._addOutputValue("cdn",s),this)}removePublishStreamUrls(t){var i,n;const o=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!o.test(e))))return r.error(`urls is invalid: ${t}`),this;const s=(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.cdn)||void 0===n?void 0:n.concat())||[];for(let e=s.length-1;e>=0;e-=1){const{pushurl:r}=s[e],i=t.indexOf(r);i>=0&&(t.splice(i,1),s.splice(e,1))}return this._addOutputValue("cdn",s),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(t,i,n,o,s){if(!this._isValidTrackId(t))return r.error(`trackId is invalid: ${t}`),this;if(!e.isNumber(i)||!e.isNumber(n))return r.error(`some attrs of (x, y) is invalid: ${i}, ${n}`),this;if([o,s].some((t=>!e.isNumber(t)||t<0)))return r.error(`some attrs of (width, height) is invalid: ${o}, ${s}`),this;const{userId:a,tag:c,mediaType:d}=Ye(t);if(d!==exports.RCMediaType.VIDEO_ONLY)return r.error(`kind of resource is not 'video': ${t}`),this;const u=Ke(a,c);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:a,stream_id:u,x:i,y:n,width:o,height:s}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return r.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:i,mediaType:n}=Ye(e);if(n!==exports.RCMediaType.VIDEO_ONLY)return r.error(`kind of resource is not 'video': ${e}`),this;const o=Ke(t,i),s=this._values.input||(this._values.input={video:[]});return s.video=s.video.filter((e=>e.stream_id===o)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,r,i,n;return t(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:o}=yield this._onFlush(t);return o===exports.RCRTCCode.SUCCESS&&((null===(r=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===r?void 0:r.width)||(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.video.normal)||void 0===n?void 0:n.fps))&&this._sendCDNInfoSignal(),this._values=Bt(),{code:o}}))}}var Ht,Gt,Jt;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(Ht||(Ht={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(Gt||(Gt={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Jt||(Jt={}));class Wt extends Ut{constructor(t,r,i,n,o,s,a,c,d=!1){var u;super(t,r,i,n,e.RTCMode.LIVE,o,s,a,d),this._livingType=c,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new Ft(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this));const l=null===(u=n.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===u?void 0:u.value;l&&(this._CDNUris=JSON.parse(l)[0])}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._mcuConfigBuilder}_onMCUConfigFlush(e){return t(this,void 0,void 0,(function*(){const t={"App-Key":this._context.getAppkey(),Token:this._token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},{code:i,res:n}=yield this._service.setMcuConfig(t,e);return i!==exports.RCRTCCode.SUCCESS?(r.error(`set MCU config failed: ${i}`),{code:i}):(r.info("set MCU config success"),n.pull_url&&(this._CDNUris=JSON.parse(n.pull_url)),{code:i,res:n})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var r,i;return t(this,void 0,void 0,(function*(){const t=yield e.__onReconnected.call(this,this._livingType);if(!t||!t.data)return;const n=t.data.roomInfo,o=null===(r=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;if(!o)return;const s=JSON.parse(o);(null===(i=this._CDNUris)||void 0===i?void 0:i.enableInnerCDN)!==s.enableInnerCDN&&this._callAppListener("onCDNEnableChange",s.enableInnerCDN),this._CDNUris=s}))}enableInnerCDN(i){return t(this,void 0,void 0,(function*(){if(!e.isBoolean(i))return r.error("`enable` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};this._CDNEnable=i;const n={version:2,output:{inCDNModel:i?Ht.OPEN:Ht.STOP}},{code:o}=yield this._onMCUConfigFlush(n);if(o!==exports.RCRTCCode.SUCCESS)return r.error(`enableInnerCDN failed -> code: ${o}`),{code:exports.RCRTCCode.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==Gt.SPREAD)return r.info("enableInnerCDN succeed"),{code:exports.RCRTCCode.SUCCESS};const{code:s}=yield a((()=>t(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return s===exports.RCRTCCode.SUCCESS?(r.info("enableInnerCDN succeed"),{code:exports.RCRTCCode.SUCCESS}):(r.error(`enableInnerCDN failed -> code: ${s}`),{code:s})}))}_sendCDNInfoSignal(){return t(this,void 0,void 0,(function*(){this._CDNUris=Object.assign({},this._CDNUris,{enableInnerCDN:this._CDNEnable});return(yield Promise.all([this._spreadCDNInfo(this._CDNUris),this._setRoomCDNInfo(this._CDNUris)])).every((e=>e.code===exports.RCRTCCode.SUCCESS))?{code:exports.RCRTCCode.SUCCESS}:{code:exports.RCRTCCode.SIGNAL_ERROR}}))}_spreadCDNInfo(i){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,ct.TOTAL_CONTENT_RESOURCE,JSON.stringify([i]));return t!==e.ErrorCode.SUCCESS?(r.error(`spreadCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("spreadCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}_setRoomCDNInfo(i){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([i]),!0,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`setRoomCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("setRoomCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}_resourceHandle(e,r,i){const n=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var o;return t(this,void 0,void 0,(function*(){n._resourceHandle.call(this,e,r,i),e.cdn_uris&&((null===(o=this._CDNUris)||void 0===o?void 0:o.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var r,i,n;return t(this,void 0,void 0,(function*(){const t=yield this._service.exchange(this._getRTCReqestHeaders(),e),o=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;return t.code===exports.RCRTCCode.SUCCESS&&o?(this._CDNUris=JSON.parse(o),(null===(n=this._CDNUris)||void 0===n?void 0:n.broadcast)===Gt.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),t):t}))}_afterChangedRole(e){const t=at(e),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var n,o,s;const a=i.filter((e=>e!==r));a.length>0&&this._callAppListener("onUserJoin",a);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},ct.TOTAL_CONTENT_RESOURCE,e);(null===(n=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===n?void 0:n.value)&&(null===(o=this._CDNUris)||void 0===o?void 0:o.push_mode)===Jt.MANUAL&&this._callAppListener("onCDNEnableChange",null===(s=this._CDNUris)||void 0===s?void 0:s.enableInnerCDN)}))}__getCDNEnable(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.enableInnerCDN}__getCDNPushMode(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.push_mode}}class Yt extends Ut{constructor(t,r,i,n,o,s,a){super(t,r,i,n,e.RTCMode.RTC,o,s,a,!1)}}const Kt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${rt.browser}|${rt.version}`,ClientVersion:"5.2.1","Client-Session-Id":"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),"Request-Id":Date.now().toString()});class qt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let i;try{i=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return r.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===i.strategy)return[];const n=null===(t=i.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!n||0===n.length)return[];const o=n[0],s=[];return o.mediaServer&&s.push(o.mediaServer.replace(/^(https?:\/\/)?/,"https://")),o.backupMediaServer&&o.backupMediaServer.forEach((e=>{s.push(e.replace(/^(https?:\/\/)?/,"https://"))})),s})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(i,n,o){return t(this,void 0,void 0,(function*(){const t=this.getNaviMS();if(0===t.length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(o.rtcFinger=this._rtcFinger);for(let s=0;s<t.length;s+=1){const a=`${t[s]}${i}`,c=Kt();r.debug(`request -> Request-Id: ${c["Request-Id"]}, url: ${a}`);const{status:d,data:u}=yield this._runtime.httpReq({url:a,body:JSON.stringify(o),headers:Object.assign(Object.assign({},c),n),method:e.HttpMethod.POST,timeout:this._timeout});if(200===d){const e=JSON.parse(u);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),r.debug(`request success -> Request-Id: ${c["Request-Id"]}`),{code:exports.RCRTCCode.SUCCESS,data:e}}r.warn(`request failed -> Request-Id: ${c["Request-Id"]}, status: ${d}, url: ${a}`),this._failedMs.push(...this._msInNavi.splice(s,1))}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}exchange(e,r){var i;return t(this,void 0,void 0,(function*(){const t=yield this._request("/exchange",e,r);if(t.code===exports.RCRTCCode.SUCCESS&&(null===(i=t.data)||void 0===i?void 0:i.resultCode)===exports.RCRTCCode.SUCCESS){const e=t.data.urls;e&&(this._configUrl=e.configUrl)}return t}))}exit(e){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(i,n){return t(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND};const t=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,o=Kt();r.debug(`request -> Request-Id: ${o["Request-Id"]}, url: ${t}`);const{status:s,data:a}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},o),i),body:JSON.stringify(n),method:e.HttpMethod.POST});if(200===s){r.debug(`request success -> Request-Id: ${o["Request-Id"]}`);const e=JSON.parse(a);return{code:e.resultCode,res:e}}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(i,n){return t(this,void 0,void 0,(function*(){const t=Kt(),{status:o,data:s}=yield this._runtime.httpReq({url:n,headers:Object.assign(Object.assign({},t),i),method:e.HttpMethod.GET});if(200===o){const e=JSON.parse(s);return{code:e.resultCode,res:e}}return r.warn(`request failed -> Request-Id: ${t["Request-Id"]}, status: ${o}, url: ${n}`),{code:exports.RCRTCCode.REQUEST_FAILED}}))}}var zt,Qt,Xt;exports.RCLivingType=void 0,(zt=exports.RCLivingType||(exports.RCLivingType={}))[zt.VIDEO=0]="VIDEO",zt[zt.AUDIO=1]="AUDIO";class Zt{constructor(e,t,r){this._context=e,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new qt(t,e,r.mediaServer)}_getReqHeaders(i){return t(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),n=t;if(!this._rtcToken){const{code:t,data:o}=yield this._context.getRTCToken(n,e.RTCMode.LIVE,i);if(t!==e.ErrorCode.SUCCESS)return r.error(`getRTCToken failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._rtcToken=o.rtcToken}return{code:exports.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:n,RoomType:e.RTCMode.LIVE,Token:this._rtcToken}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return t(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===exports.RCRTCCode.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,r,i,n=!1){return t(this,void 0,void 0,(function*(){return a((()=>this.__subscribe(e,r,i,n)))}))}__subscribe(i,n,o,s=!1){var a;return t(this,void 0,void 0,(function*(){const t=[];if(st(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:t};if(!this._fromRetry&&(null===(a=this._pc)||void 0===a||a.clearReTryExchangeTimer()),this._fromRetry=!1,!e.isString(i))return r.error(`liveUrl is invalid: ${i}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCLivingType.AUDIO,exports.RCLivingType.VIDEO].includes(n))return r.error(`livingType is invalid: ${n}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCMediaType.AUDIO_ONLY,exports.RCMediaType.VIDEO_ONLY,exports.RCMediaType.AUDIO_VIDEO].includes(o))return r.error(`mediaType is invalid: ${o}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(this._liveUrl&&this._liveUrl!==i)return{code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:t};this._pc||(this._pc=new It(this._reTryExchange.bind(this)),this._pc.on(It.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=i;const{code:c,headers:d}=yield this._getReqHeaders(n);if(c!==exports.RCRTCCode.SUCCESS)return{code:c,tracks:t};const u=`rc_mcu_${Date.now()}`,l="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new At(l,u),new Nt(l,u)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const p={sdp:yield this._pc.createOffer(!0),liveUrl:i,mediaType:o,simulcast:s?lt.TINY:lt.NORMAL,switchstream:!1},h=yield this._service.broadcastSubscribe(d,p);if(h.code!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed: ${h.code}`),{code:h.code,tracks:t};const m=h.data;if(m.resultCode!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed! code: ${m.resultCode}; message: ${m.message}`),{code:m.resultCode,tracks:t};r.debug(`andience subscribe success: ${i}`),this._livingType=n,this._mediaType=o,this._subTiny=s;const{sdp:_,subscribedList:C}=m,R=[];return C.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];R.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(_.sdp),{code:exports.RCRTCCode.SUCCESS,tracks:R}}))}unsubscribe(){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return t(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:exports.RCRTCCode.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:i}=yield this._service.broadcastExit(t);return i!==exports.RCRTCCode.SUCCESS?r.error(`broadcast unsubscribe failed: ${i}`):r.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:i}}))}registerReportListener(e){var t;this._reportListener=e,null===(t=this._pc)||void 0===t||t.registerReportListener(e)}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,i;const n=e.receiver.track,o="audio"===n.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY,s=this._subTracks[o];s.__innerSetMediaStreamTrack(n);try{null===(i=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===i||i.call(t,s)}catch(e){r.error(e)}}}exports.RCInnerCDNPullKind=void 0,(Qt=exports.RCInnerCDNPullKind||(exports.RCInnerCDNPullKind={})).RTMP="rtmp",Qt.FLV="flv",Qt.HLS="hls",exports.RCInnerCDNPullIsHttps=void 0,(Xt=exports.RCInnerCDNPullIsHttps||(exports.RCInnerCDNPullIsHttps={}))[Xt.NOT_HTTPS=0]="NOT_HTTPS",Xt[Xt.HTTPS=1]="HTTPS";const er=Object.assign(Object.assign({},Xe(exports.RCResolution.W176_H144)),{frameRate:tt(exports.RCFrameRate.FPS_15)});class tr{constructor(e,t,i,n,o,s){this._context=e,this._runtime=t,this._initOptions=i,this._roomId=n,this._joinResData=o,this._livingType=s,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._service=new qt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new Lt(this._context,this._runtime,this._roomId,this,bt.Audience),this._polarisReport.sendR1(),this._pc=new It(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(It.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,i=e.receiver.track,n=[t,"audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),o=this._remoteTracks[n];o?(o.__innerSetMediaStreamTrack(i),this._callAppListener("onTrackReady",o)):r.warn("cannot found RCRemoteTrack:",i.id)})),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var i;if(t!==this._roomId)return void r.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);r.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const n=[],o=null===(i=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===i?void 0:i.value;o&&this._diffCDNUris(JSON.parse(JSON.parse(o).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:o}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return n.push(...t),void this._diffAnchorResource(i,o)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}"RC_RTC_SESSIONID"===t&&(this._sessionId=r)})),this._diffRoomResource(n)}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return t(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return t(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=We(e),{userId:n,tag:o,mediaType:s}=Ye(r),a=[this._roomId,o,s].join("_");if(!this._remoteTracks[a]){const r=s===exports.RCMediaType.AUDIO_ONLY?new At(o,"",this._roomId):new Nt(o,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,i){return t(this,void 0,void 0,(function*(){const t=this._roomAnchorRes[i]||(this._roomAnchorRes[i]=[]),{publishedList:n,unpublishedList:o,modifiedList:s}=ze(t,e);if(n.length){const e=t.map(We),i=[],o=[];if(n.forEach((r=>{const n=We(r),s=e.indexOf(n),{userId:a,tag:c,mediaType:d}=Ye(n);s>-1?t[s]=r:t.push(r);let u=this._remoteTracks[n];this._roomRes[n]=r,u?u.isSubscribed()&&i.push(u):(u=d===exports.RCMediaType.AUDIO_ONLY?new At(c,a):new Nt(c,a),this._remoteTracks[n]=u,o.push(u)),u.__innerSetRemoteMuted(0===r.state)})),i.length){const e=i.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:t}=yield a((()=>this._subscribeHandle(i,!0)));t!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${t}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",o)}if(o.length){const e=o.map(We);for(let r=t.length-1;r>=0;r-=1){const i=t[r];e.includes(We(i))&&t.splice(r,1)}const r=o.map((e=>{const t=We(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(r,"onAnchorTrackUnpublish")}if(s.length){const e=t.map(We);for(let r=0;r<s.length;r++){const i=s[r],n=We(i),o=e.indexOf(n);t[o].state=i.state;const a=this._remoteTracks[n];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,r){return t(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(r,e)}))}_callAppListener(e,...t){var i;const n=null===(i=this._appListener)||void 0===i?void 0:i[e];if(n)try{n(...t)}catch(e){r.error(e)}}_reTryExchange(){return t(this,void 0,void 0,(function*(){a((()=>t(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),i=yield this._exchangeHandle(t);if(i.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${i.code}`),{code:i.code};const{sdp:n,resultCode:o}=i.data;if(o!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${o}`),{code:o};this._pc.clearReTryExchangeTimer();const s=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(s.length>0){const t=s[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,i=[this._roomId,"RongCloudRTC"].join("_");n.sdp=n.sdp.replace(new RegExp(r,"g"),i)}const a=yield this._pc.setRemoteAnswer(n.sdp);return a!==exports.RCRTCCode.SUCCESS?{code:a}:void 0}))))}))}_createSubscribeParams(e,r,i){return t(this,void 0,void 0,(function*(){const t=yield this._pc.createOffer(i),n={resolutionInfo:[]},o={min:0,max:0};Object.keys(r).forEach((e=>{const{mediaStream:i,tinyStream:s}=r[e];[i,s].forEach(((r,i)=>{var s;const a=1===i?[e,"tiny"].join("_"):e;t.sdp=null===(s=t.sdp)||void 0===s?void 0:s.replace(new RegExp(r.id,"g"),a);const c=r.getVideoTracks()[0];if(!c)return;const d=0===i,{width:u,height:l,frameRate:p}=d?Ge(c):er;n.resolutionInfo.push({trackId:c.id,simulcast:d?lt.NORMAL:lt.TINY,resolution:`${u}x${l}`});const h=Ie(u,l),m=be(p);o.min+=h.minBitrate*m,o.max+=h.maxBitrate*m}))}));return{reqBody:{sdp:t,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?lt.TINY:lt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:o,offer:t}}))}_subscribeHandle(r,i=!1){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",r,(()=>e.isArray(r)&&r.length>0&&r.every((e=>e instanceof Dt||e.track instanceof Dt))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))),o=r.map((e=>e instanceof Dt?{track:e}:e));let s=!1;const a=[];return o.forEach((e=>{const r=e.track.getTrackId();a.push(r);const i=t.find((e=>e.track.getTrackId()===r));i&&i.subTiny===e.subTiny||(i?i.subTiny=e.subTiny:t.push(e),s=!0)})),s||i?(null===(n=this._polarisReport)||void 0===n||n.sendR2(xt.SUBSCRIBE,Pt.BEGIN,a),this._updateSubListHandle(t,!0)):{code:exports.RCRTCCode.SUCCESS}}))}_getReqHeaders(){const t=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:t,Token:this._joinResData.token,RoomType:e.RTCMode.LIVE,UserId:t,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(i,n=!1){var o;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",i,(()=>e.isArray(i)&&i.every((e=>e instanceof Dt||e.track instanceof Dt))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};let t=i.map((e=>e instanceof Dt?{track:e}:Object.assign({},e)));const s={};t=t.filter((e=>{const t=e.track.getTrackId();return!s[t]&&(s[t]=!0)})).map((e=>Object.assign({},e)));const a=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let e=!1;if(t.forEach((t=>{const r=a.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);a.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),a.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const{reqBody:c}=yield this._createSubscribeParams(t,{},!1),d=yield this._exchangeHandle(c);if(a.length){const e=[];a.forEach((t=>{e.push(t.track.getTrackId())})),null===(o=this._pc.reportParser)||void 0===o||o.clearLatestPacketsRecv(e)}if(d.code!==exports.RCRTCCode.SUCCESS)return{code:d.code};const{sdp:u,resultCode:l,message:p}=d.data;if(l!==exports.RCRTCCode.SUCCESS)return r.error("change subscribe list failed:",p,l),{code:l};t.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Ye(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const h=yield this._pc.setRemoteAnswer(u.sdp);if(h!==exports.RCRTCCode.SUCCESS)return{code:h};for(const e in this._remoteTracks){const r=t.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(r)}return this._subscribedList.splice(0,this._subscribedList.length,...t),{code:exports.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){var r,i,n,o,s,a,c,d;return t(this,void 0,void 0,(function*(){if((null===(r=this._CDNUris)||void 0===r?void 0:r.url)&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!(null===(i=this._CDNUris)||void 0===i?void 0:i.url)&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:e.fps});const t=(null===(n=this._CDNUris)||void 0===n?void 0:n.w)&&e.w&&(null===(o=this._CDNUris)||void 0===o?void 0:o.w)!==e.w,u=(null===(s=this._CDNUris)||void 0===s?void 0:s.h)&&e.h&&(null===(a=this._CDNUris)||void 0===a?void 0:a.h)!==e.h,l=(null===(c=this._CDNUris)||void 0===c?void 0:c.fps)&&e.fps&&(null===(d=this._CDNUris)||void 0===d?void 0:d.fps)!==e.fps;(t||u||l)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:e.fps}),this._CDNUris=e}))}_getCDNPlayUrl(e,i){var n,o;return t(this,void 0,void 0,(function*(){const{w:t,h:s,fps:a}=e,c=this._initOptions.pullInnerCDNProtocol||exports.RCInnerCDNPullKind.FLV,d=this._initOptions.pullInnerCDNUseHttps===exports.RCInnerCDNPullIsHttps.NOT_HTTPS?exports.RCInnerCDNPullIsHttps.NOT_HTTPS:exports.RCInnerCDNPullIsHttps.HTTPS;if(!(null===(n=this._CDNUris)||void 0===n?void 0:n.url)&&!i)return r.error(`cdn_uris url is empty, the anchor need to start CDN, code: ${exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const u={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},l=[];t&&l.push(`w=${t}`),s&&l.push(`h=${s}`),a&&l.push(`fps=${a}`),l.push(`kind=${c}`),l.push(`is_https=${d}`);const p=l.join("&");let h=`${i||(null===(o=this._CDNUris)||void 0===o?void 0:o.url)}?`;p&&(h+=p);const{code:m,res:_}=yield this._service.getCDNResourceInfo(u,h);return m!==exports.RCRTCCode.SUCCESS?(r.error(`getCDNPlayUrl failed: ${m}`),{code:m}):(r.info(`getCDNPlayUrl success: ${null==_?void 0:_.data.pull_url}`),{code:m,CDNPlayUrl:null==_?void 0:_.data.pull_url})}))}getCDNPlayUrl(e,i){return t(this,void 0,void 0,(function*(){if(e&&!Ze(e))return r.error("`resolution` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};if(i&&!et(i))return r.error("`fps` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};const{width:t,height:n}=e?Xe(e):{width:null,height:null},o=i?tt(i):null,s={};return t&&(s.w=t),n&&(s.h=n),o&&(s.fps=o),this._getCDNPlayUrl(s)}))}subscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(i){var n;return t(this,void 0,void 0,(function*(){if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Dt))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(xt.SUBSCRIBE,Pt.END,i.map((e=>e.getTrackId()))),this._updateSubListHandle(t,!1)}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe(e)))}))}__destroy(e){var r;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),this._pc.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._pc}getLocalTrack(e){return{}}__onReconnected(){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.joinLivingRoomAsAudience(this._roomId,e.RTCMode.LIVE);t!==e.ErrorCode.SUCCESS&&r.error("join living room error when on reconnected")}))}registerRoomEventListener(e){var t;this._appListener=e,e&&(null===(t=this._joinResData.kvEntries)||void 0===t?void 0:t.length)&&this.singalDataChange(this._joinResData.kvEntries,this._roomId)}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Mt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}registerReportListener(e){var t;null===(t=this._pc)||void 0===t||t.registerReportListener(e)}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}}const rr=(e,t)=>{const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r};class ir{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,St.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new qt(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(t){var r;return t.conversationType===e.ConversationType.RTC_ROOM&&(null===(r=this._crtRoom)||void 0===r||r.__parseInnerMessage(t),!0)}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t){return a((()=>this._joinRTCRoom(e,t)))}_joinRTCRoom(i,o){return t(this,void 0,void 0,(function*(){if(st(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.debug(`joinRoom -> roomId: ${i}; joinType: ${o||e.RTCJoinType.KICK}`);const{code:t,data:s}=yield this._context.joinRTCRoom(i,e.RTCMode.RTC,void 0,o);if(t!==e.ErrorCode.SUCCESS){r.error(`joinRoom failed -> code: ${t}`);return{code:t===n.JOIN_REFUSED?exports.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:t}}r.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(s)}`);const a=new Yt(this._context,this._runtime,i,s,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=a,{room:a,code:exports.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}joinLivingRoom(e,t){return a((()=>this._joinLivingRoom(e,t)))}_joinLivingRoom(i,n){return t(this,void 0,void 0,(function*(){if(st(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.debug(`joinRoom, roomId: ${i}`);const{code:t,data:o}=yield this._context.joinRTCRoom(i,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error(`joinRoom failed -> code: ${t}`),{code:t};r.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(o)}`);const s=new Wt(this._context,this._runtime,i,o,this._service,this._options,this._releaseCrtRoomObj.bind(this),n,!1);this._crtRoom=s;const a={room:s,code:exports.RCRTCCode.SUCCESS,userIds:s.getRemoteUserIds(),tracks:s.getRemoteTracks()};return s.__getCDNPushMode()===Jt.MANUAL&&Object.assign(a,{CDNEnable:s.__getCDNEnable()}),a}))}getAudienceClient(){return this._audience||(this._audience=new Zt(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(t){r.debug(`signal server connection state change: ${t}`),t===e.ConnectionStatus.CONNECTED&&this._crtRoom&&this._crtRoom.__onReconnected()}_onIMDisconnect(){r.debug("TODO -> on IM disconnect")}_onIMUninit(){r.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return a((()=>this._leaveRoom(e)))}_leaveRoom(e){return t(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),r.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,i="getUserMedia"){return t(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices[i](e);return{code:exports.RCRTCCode.SUCCESS,stream:t}}catch(e){if("Permission denied"===e.message)return{code:exports.RCRTCCode.PERMISSION_DENIED};r.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===i?exports.RCRTCCode.GET_USER_MEDIA_FAILED:exports.RCRTCCode.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",r){return t(this,void 0,void 0,(function*(){if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==r?void 0:r.micphoneId,sampleRate:null==r?void 0:r.sampleRate}});if(n!==exports.RCRTCCode.SUCCESS)return{code:n};const o=i.getAudioTracks()[0];return{code:n,track:new we(e,t,o)}}))}createCameraVideoTrack(e="RongCloudRTC",r){return t(this,void 0,void 0,(function*(){if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};const i=Ze(null==r?void 0:r.resolution)?r.resolution:exports.RCResolution.W640_H480,{width:n,height:o}=Xe(i),{stream:s,code:a}=yield this._getMediaStream({video:{deviceId:null==r?void 0:r.cameraId,frameRate:tt((null==r?void 0:r.frameRate)||exports.RCFrameRate.FPS_15),width:n,height:o}});if(a!==exports.RCRTCCode.SUCCESS)return{code:a};const c=s.getVideoTracks()[0];return{code:a,track:new Ue(e,t,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",r){var i,n,o,s,a;return t(this,void 0,void 0,(function*(){const t=[];if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};const c=this._context.getCurrentId();if(!c)return{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const d=Ze(null===(i=null==r?void 0:r.video)||void 0===i?void 0:i.resolution)?r.video.resolution:exports.RCResolution.W640_H480,{width:u,height:l}=Xe(d),{stream:p,code:h}=yield this._getMediaStream({video:{deviceId:null===(n=null==r?void 0:r.video)||void 0===n?void 0:n.cameraId,frameRate:tt((null===(o=null==r?void 0:r.video)||void 0===o?void 0:o.frameRate)||exports.RCFrameRate.FPS_15),width:u,height:l},audio:{deviceId:null===(s=null==r?void 0:r.audio)||void 0===s?void 0:s.micphoneId,sampleRate:null===(a=null==r?void 0:r.audio)||void 0===a?void 0:a.sampleRate}});return h!==exports.RCRTCCode.SUCCESS||p.getTracks().forEach((r=>{"video"===r.kind?t.push(new Ue(e,c,r)):t.unshift(new we(e,c,r))})),{code:h,tracks:t}}))}createScreenVideoTrack(e="screenshare",r){return t(this,void 0,void 0,(function*(){if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};if(!nt())return{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==r?void 0:r.chromeMediaSourceId))return{code:exports.RCRTCCode.PARAMS_ERROR};const n=Ze(null==r?void 0:r.resolution)?r.resolution:exports.RCResolution.W1280_H720,{width:o,height:s}=Xe(n),a=i?{mandatory:{chromeMediaSourceId:r.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:o,maxWidth:o,minHeight:s,maxHeight:s}}:{frameRate:tt((null==r?void 0:r.frameRate)||exports.RCFrameRate.FPS_15),width:o,height:s},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==exports.RCRTCCode.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new $e(e,t,u)}}))}createLocalAudioTrack(e,r){return t(this,void 0,void 0,(function*(){if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS};if(!r||"[object MediaStreamTrack]"!==r.toString()||"audio"!==r.kind)return{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();return t?{code:exports.RCRTCCode.SUCCESS,track:new Le(e,t,r)}:{code:exports.RCRTCCode.INVALID_USER_ID}}))}createLocalVideoTrack(e,r){return t(this,void 0,void 0,(function*(){if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS};if(!r||"[object MediaStreamTrack]"!==r.toString()||"video"!==r.kind)return{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();return t?{code:exports.RCRTCCode.SUCCESS,track:new De(e,t,r)}:{code:exports.RCRTCCode.INVALID_USER_ID}}))}createLocalFileTracks(i,n,o){return t(this,void 0,void 0,(function*(){if(!Be(i))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:[]};if(!it())return{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const t=n instanceof File?URL.createObjectURL(n):n;if(!e.isHttpUrl(t)&&!/^blob:/.test(t))return r.warn(`createLocalFileTracks failed: params error -> url: ${t}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:[]};const s=this._context.getCurrentId();return s?new Promise((e=>{const n=document.createElement("video");(null==o?void 0:o.withoutAudio)&&(n.muted=!0),n.onloadedmetadata=()=>{const a=[];let c;try{const e=n.mozCaptureStream?"mozCaptureStream":"captureStream";c=n[e]()}catch(i){r.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${t}`),r.error(i),e({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:a})}const[d,u]=rr(c,o);d&&a.push(new Me(i,s,d,n)),u&&a.push(new Ne(i,s,u,n)),0===a.length&&(n.pause(),n.src=""),n.onerror=null,e({code:exports.RCRTCCode.SUCCESS,tracks:a})},n.onerror=()=>{r.error(`create RCLocalFileTrack failed -> url: ${t}`),e({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},n.src=t,n.loop=!0,n.play()})):{code:exports.RCRTCCode.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,r,i){return t(this,void 0,void 0,(function*(){const t=[];if(!Be(e))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};if(!(r instanceof MediaStream))return{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};const n=this._context.getCurrentId();if(!n)return{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const[o,s]=rr(r,i);return o&&t.push(new Le(e,n,o)),s&&t.push(new De(e,n,s)),{code:exports.RCRTCCode.SUCCESS,tracks:t}}))}joinLivingRoomAsAudience(i,n){return t(this,void 0,void 0,(function*(){if(st(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:t,data:o}=yield this._context.joinLivingRoomAsAudience(i,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error("audienceJoinLivingRoomError:",t),{code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};r.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(o)}`);const s=new tr(this._context,this._runtime,this._options,i,o,n);return this._crtAudienceLivingRoom=s,{room:s,code:exports.RCRTCCode.SUCCESS}}))}leaveLivingRoomAsAudience(e){return t(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:exports.RCRTCCode.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}}))}upgradeToAnchorRoom(i){return t(this,void 0,void 0,(function*(){if(!e.validate("room._roomId",i._roomId,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(i._roomId,e.RTCIdentityChangeType.ViewerToAnchor,i._livingType);if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const o=new Wt(this._context,this._runtime,i._roomId,n,this._service,this._options,this._releaseCrtRoomObj.bind(this),i._livingType,!0);return this._crtRoom=o,this._crtAudienceLivingRoom=null,{room:o,code:exports.RCRTCCode.SUCCESS}}))}downgradeToAudienceRoom(i){return t(this,void 0,void 0,(function*(){if(!e.validate("room._roomId",i._roomId,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(i._roomId,e.RTCIdentityChangeType.AnchorToViewer,i.getLivingType());if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};r.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(n)}`);const o=new tr(this._context,this._runtime,this._options,i._roomId,n,i.getLivingType());return this._crtAudienceLivingRoom=o,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:o,code:exports.RCRTCCode.SUCCESS}}))}getJoinedRoomInfo(){return t(this,void 0,void 0,(function*(){const{code:t,data:i}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return t!==e.ErrorCode.SUCCESS?(r.error("getJoinedUserInfo error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:exports.RCRTCCode.SUCCESS,data:i}}))}}var nr;exports.RCKickReason=void 0,(nr=exports.RCKickReason||(exports.RCKickReason={}))[nr.SERVER_KICK=1]="SERVER_KICK",nr[nr.OTHER_KICK=2]="OTHER_KICK";const or={tag:"RCRTC",verify:t=>"browser"!==t.tag?(r.error(`RCRTC Plugin is not support the runtime '${t.tag}'`),!1):Fe?(e.VersionManage.add("plugin-rtc","5.2.1"),!!e.VersionManage.validEngine("~4.5.1")||(r.error(`The current engine version '${e.VersionManage.getInfo().engine}' error, plugin-rtc required engine version at least '~4.5.1'.`),!1)):(r.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(t,i,n={})=>(r.setLogLevel(n.logLevel),r.setLogStdout(n.logStdout),r.warn("RCRTC Version: 5.2.1, Commit: 39edcf1817086fcfcede93a3d4c3f2a35fd21932"),r.warn(`browserInfo.browser -> ${rt.browser}`),r.warn(`browserInfo.supportsUnifiedPlan -> ${rt.supportsUnifiedPlan}`),r.warn(`browserInfo.version -> ${rt.version}`),e.assert("options.mediaServer",n.mediaServer,(t=>!(!e.isHttpUrl(t)||"https:"===location.protocol&&!/^https/.test(t)))),e.assert("options.timeout",n.timeout,(t=>e.isNumber(t)&&t>=5e3&&t<=3e4)),e.assert("options.pingGap",n.pingGap,(t=>e.isNumber(t)&&t>=3e3&&t<=1e4)),new ir(t,i,n))},sr={transResolution:Xe,transFrameRate:tt,parseTrackId:Ye,ifSupportLocalFileTrack:it,ifSupportScreenShare:nt};Object.defineProperty(exports,"RTCJoinType",{enumerable:!0,get:function(){return e.RTCJoinType}}),exports.RCAbstractRoom=Ut,exports.RCAudienceClient=Zt,exports.RCAudienceLivingRoom=tr,exports.RCCameraVideoTrack=Ue,exports.RCLivingRoom=Wt,exports.RCLocalAudioTrack=Le,exports.RCLocalFileAudioTrack=Me,exports.RCLocalFileTrack=Ae,exports.RCLocalFileVideoTrack=Ne,exports.RCLocalTrack=Oe,exports.RCLocalVideoTrack=De,exports.RCMCUConfigBuilder=Ft,exports.RCMicphoneAudioTrack=we,exports.RCRTCClient=ir,exports.RCRTCRoom=Yt,exports.RCRemoteAudioTrack=At,exports.RCRemoteTrack=Dt,exports.RCRemoteVideoTrack=Nt,exports.RCScreenVideoTrack=$e,exports.RCTag={DEFAULT:"RongCloudRTC"},exports.RCTrack=Pe,exports.device=xe,exports.helper=sr,exports.installer=or;
|
|
15
|
+
***************************************************************************** */function t(e,t,r,i){return new(r||(r=Promise))((function(n,s){function o(e){try{c(i.next(e))}catch(e){s(e)}}function a(e){try{c(i.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}const r=new e.Logger("RCRTC");var i,n;exports.RCRTCCode=void 0,(i=exports.RCRTCCode||(exports.RCRTCCode={}))[i.SUCCESS=1e4]="SUCCESS",i[i.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",i[i.PARAMS_ERROR=50001]="PARAMS_ERROR",i[i.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",i[i.NOT_IN_ROOM=50003]="NOT_IN_ROOM",i[i.SERVICE_INVALID=50004]="SERVICE_INVALID",i[i.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",i[i.SIGNAL_ERROR=53001]="SIGNAL_ERROR",i[i.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",i[i.REQUEST_FAILED=53004]="REQUEST_FAILED",i[i.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",i[i.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",i[i.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",i[i.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",i[i.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",i[i.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",i[i.PERMISSION_DENIED=53012]="PERMISSION_DENIED",i[i.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",i[i.INVALID_TAGS=53014]="INVALID_TAGS",i[i.INVALID_USER_ID=53015]="INVALID_USER_ID",i[i.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",i[i.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",i[i.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",i[i.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",i[i.TRACK_NOT_READY=53020]="TRACK_NOT_READY",i[i.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",i[i.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",i[i.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",i[i.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",i[i.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",i[i.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",i[i.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",i[i.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",i[i.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(n||(n={}));class s{constructor(){this.queue=[],this.locked=!1}checkToStart(){return t(this,void 0,void 0,(function*(){if(0===this.queue.length||this.locked)return;this.locked=!0;const{resolve:e,task:t,reject:r}=this.queue.shift();let i;try{i=yield t(),e(i)}catch(e){r(e)}this.locked=!1,this.checkToStart()}))}push(e){const t=new Promise(((t,r)=>{this.queue.push({resolve:t,task:e,reject:r})}));return this.checkToStart(),t}}const o=new s,a=e=>o.push(e);let c=!0,d=!0;function u(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function l(e,t,r){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,n=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return n.apply(this,arguments);const s=e=>{const t=r(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,s),n.apply(this,[e,s])};const s=i.removeEventListener;i.removeEventListener=function(e,r){if(e!==t||!this._eventMap||!this._eventMap[t])return s.apply(this,arguments);if(!this._eventMap[t].has(r))return s.apply(this,arguments);const i=this._eventMap[t].get(r);return this._eventMap[t].delete(r),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function p(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(c=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function h(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(d=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function m(){if("object"==typeof window){if(c)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function _(e,t){d&&console.warn(e+" is deprecated, please use "+t+" instead.")}function C(e){return"[object Object]"===Object.prototype.toString.call(e)}function R(e){return C(e)?Object.keys(e).reduce((function(t,r){const i=C(e[r]),n=i?R(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function f(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?f(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{f(e,e.get(t),r)}))})))}function v(e,t,r){const i=r?"outbound-rtp":"inbound-rtp",n=new Map;if(null===t)return n;const s=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)})),s.forEach((t=>{e.forEach((r=>{r.type===i&&r.trackId===t.id&&f(e,r,n)}))})),n}const T=m;function g(e,t){const r=e&&e.navigator;if(!r.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((r=>{if("require"===r||"advanced"===r||"mediaSource"===r)return;const i="object"==typeof e[r]?e[r]:{ideal:e[r]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const n=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[n("min",r)]=i.ideal,t.optional.push(e),e={},e[n("max",r)]=i.ideal,t.optional.push(e)):(e[n("",r)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[n("",r)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[n(e,r)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},n=function(e,n){if(t.version>=61)return n(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});const o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&(!r.mediaDevices.getSupportedConstraints||!r.mediaDevices.getSupportedConstraints().facingMode||o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:"user"!==s.exact&&"user"!==s.ideal||(t=["front"]),t)return r.mediaDevices.enumerateDevices().then((r=>{let o=(r=r.filter((e=>"videoinput"===e.kind))).find((e=>t.some((t=>e.label.toLowerCase().includes(t)))));return!o&&r.length&&t.includes("back")&&(o=r[r.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=i(e.video),T("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return T("chrome: "+JSON.stringify(e)),n(e)},s=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(r.getUserMedia=function(e,t,i){n(e,(e=>{r.webkitGetUserMedia(e,t,(e=>{i&&i(s(e))}))}))}.bind(r),r.mediaDevices.getUserMedia){const e=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(t){return n(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>Promise.reject(s(e))))))}}}function S(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function y(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.track.id)):{track:r.track};const n=new Event("track");n.track=r.track,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)})),t.stream.getTracks().forEach((r=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===r.id)):{track:r};const n=new Event("track");n.track=r,n.receiver=i,n.transceiver={receiver:i},n.streams=[t.stream],this.dispatchEvent(n)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else l(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function E(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let n=r.apply(this,arguments);return n||(n=t(this,e),this._senders.push(n)),n};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.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 I(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,r,i]=arguments;if(arguments.length>0&&"function"==typeof e)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof e))return t.apply(this,[]);const n=function(e){const t={};return e.result().forEach((e=>{const r={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{r[t]=e.stat(t)})),t[r.id]=r})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const i=function(e){r(s(n(e)))};return t.apply(this,[i,e])}return new Promise(((e,r)=>{t.apply(this,[function(t){e(s(n(t)))},r])})).then(r,i)}}function k(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>v(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),l(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>v(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,r,i;return this.getSenders().forEach((r=>{r.track===e&&(t?i=!0:t=r)})),this.getReceivers().forEach((t=>(t.track===e&&(r?i=!0:r=t),t.track===e))),i||t&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function b(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){if(!r)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[r.id]?-1===this._shimmedLocalStreams[r.id].indexOf(i)&&this._shimmedLocalStreams[r.id].push(i):this._shimmedLocalStreams[r.id]=[r,i],i};const r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();r.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const r=this._shimmedLocalStreams[t].indexOf(e);-1!==r&&this._shimmedLocalStreams[t].splice(r,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),n.apply(this,arguments)}}function x(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return b(e);const r=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=r.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{if(this.getSenders().find((t=>t.track===e)))throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const r=new e.MediaStream(t.getTracks());this._streams[t.id]=r,this._reverseStreams[r.id]=t,t=r}i.apply(this,[t])};const n=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(n.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:r})}function o(e,t){let r=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],n=e._streams[i.id];r=r.replace(new RegExp(i.id,"g"),n.id)})),new RTCSessionDescription({type:t.type,sdp:r})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},n.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,r){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");const n=this.getSenders().find((e=>e.track===t));if(n)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const s=this._streams[r.id];if(s)s.addTrack(t),Promise.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[r.id]=i,this._reverseStreams[i.id]=r,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?r.apply(this,[t=>{const r=s(this,t);e[0].apply(null,[r])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):r.apply(this,arguments).then((e=>s(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const a=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=o(this,arguments[0]),a.apply(this,arguments)):a.apply(this,arguments)};const c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=c.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((r=>{this._streams[r].getTracks().find((t=>e.track===t))&&(t=this._streams[r])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function O(e,t){l(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var L=Object.freeze({__proto__:null,shimMediaStream:S,shimOnTrack:y,shimGetSendersWithDtmf:E,shimGetStats:I,shimSenderReceiverGetStats:k,shimAddTrackRemoveTrackWithNative:b,shimAddTrackRemoveTrack:x,shimPeerConnection:P,fixNegotiationNeeded:O,shimGetUserMedia:g,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(r){return t(r).then((t=>{const i=r.video&&r.video.width,n=r.video&&r.video.height,s=r.video&&r.video.frameRate;return r.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:s||3}},i&&(r.video.mandatory.maxWidth=i),n&&(r.video.mandatory.maxHeight=n),e.navigator.mediaDevices.getUserMedia(r)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});var D,N,A=(D=function(e){var t={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((function(e){return e.trim()}))},t.splitSections=function(e){return e.split("\nm=").map((function(e,t){return(t>0?"m="+e:e).trim()+"\r\n"}))},t.getDescription=function(e){var r=t.splitSections(e);return r&&r[0]},t.getMediaSections=function(e){var r=t.splitSections(e);return r.shift(),r},t.matchPrefix=function(e,r){return t.splitLines(e).filter((function(e){return 0===e.indexOf(r)}))},t.parseCandidate=function(e){for(var t,r={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[0],component:parseInt(t[1],10),protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]},i=8;i<t.length;i+=2)switch(t[i]){case"raddr":r.relatedAddress=t[i+1];break;case"rport":r.relatedPort=parseInt(t[i+1],10);break;case"tcptype":r.tcpType=t[i+1];break;case"ufrag":r.ufrag=t[i+1],r.usernameFragment=t[i+1];break;default:r[t[i]]=t[i+1]}return r},t.writeCandidate=function(e){var t=[];t.push(e.foundation),t.push(e.component),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);var r=e.type;return t.push("typ"),t.push(r),"host"!==r&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substr(14).split(" ")},t.parseRtpMap=function(e){var t=e.substr(9).split(" "),r={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),r.name=t[0],r.clockRate=parseInt(t[1],10),r.channels=3===t.length?parseInt(t[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(e){var t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);var r=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==r?"/"+r:"")+"\r\n"},t.parseExtmap=function(e){var t=e.substr(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1]}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+"\r\n"},t.parseFmtp=function(e){for(var t,r={},i=e.substr(e.indexOf(" ")+1).split(";"),n=0;n<i.length;n++)r[(t=i[n].trim().split("="))[0].trim()]=t[1];return r},t.writeFmtp=function(e){var t="",r=e.payloadType;if(void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){var i=[];Object.keys(e.parameters).forEach((function(t){e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+r+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){var t=e.substr(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){var t="",r=e.payloadType;return void 0!==e.preferredPayloadType&&(r=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((function(e){t+="a=rtcp-fb:"+r+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){var t=e.indexOf(" "),r={ssrc:parseInt(e.substr(7,t-7),10)},i=e.indexOf(":",t);return i>-1?(r.attribute=e.substr(t+1,i-t-1),r.value=e.substr(i+1)):r.attribute=e.substr(t+1),r},t.parseSsrcGroup=function(e){var t=e.substr(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((function(e){return parseInt(e,10)}))}},t.getMid=function(e){var r=t.matchPrefix(e,"a=mid:")[0];if(r)return r.substr(6)},t.parseFingerprint=function(e){var t=e.substr(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1]}},t.getDtlsParameters=function(e,r){return{role:"auto",fingerprints:t.matchPrefix(e+r,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){var r="a=setup:"+t+"\r\n";return e.fingerprints.forEach((function(e){r+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),r},t.parseCryptoLine=function(e){var t=e.substr(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;var t=e.substr(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,r){return t.matchPrefix(e+r,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,r){var i=t.matchPrefix(e+r,"a=ice-ufrag:")[0],n=t.matchPrefix(e+r,"a=ice-pwd:")[0];return i&&n?{usernameFragment:i.substr(12),password:n.substr(10)}:null},t.writeIceParameters=function(e){return"a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n"},t.parseRtpParameters=function(e){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" "),n=3;n<i.length;n++){var s=i[n],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){var a=t.parseRtpMap(o),c=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(a.parameters=c.length?t.parseFmtp(c[0]):{},a.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),r.codecs.push(a),a.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(a.name.toUpperCase())}}}return t.matchPrefix(e,"a=extmap:").forEach((function(e){r.headerExtensions.push(t.parseExtmap(e))})),r},t.writeRtpDescription=function(e,r){var i="";i+="m="+e+" ",i+=r.codecs.length>0?"9":"0",i+=" UDP/TLS/RTP/SAVPF ",i+=r.codecs.map((function(e){return void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType})).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",r.codecs.forEach((function(e){i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));var n=0;return r.codecs.forEach((function(e){e.maxptime>n&&(n=e.maxptime)})),n>0&&(i+="a=maxptime:"+n+"\r\n"),i+="a=rtcp-mux\r\n",r.headerExtensions&&r.headerExtensions.forEach((function(e){i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){var r,i=[],n=t.parseRtpParameters(e),s=-1!==n.fecMechanisms.indexOf("RED"),o=-1!==n.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute})),c=a.length>0&&a[0].ssrc,d=t.matchPrefix(e,"a=ssrc-group:FID").map((function(e){return e.substr(17).split(" ").map((function(e){return parseInt(e,10)}))}));d.length>0&&d[0].length>1&&d[0][0]===c&&(r=d[0][1]),n.codecs.forEach((function(e){if("RTX"===e.name.toUpperCase()&&e.parameters.apt){var t={ssrc:c,codecPayloadType:parseInt(e.parameters.apt,10)};c&&r&&(t.rtx={ssrc:r}),i.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:c,mechanism:o?"red+ulpfec":"red"},i.push(t))}})),0===i.length&&c&&i.push({ssrc:c});var u=t.matchPrefix(e,"b=");return u.length&&(u=0===u[0].indexOf("b=TIAS:")?parseInt(u[0].substr(7),10):0===u[0].indexOf("b=AS:")?1e3*parseInt(u[0].substr(5),10)*.95-16e3:void 0,i.forEach((function(e){e.maxBitrate=u}))),i},t.parseRtcpParameters=function(e){var r={},i=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"cname"===e.attribute}))[0];i&&(r.cname=i.value,r.ssrc=i.ssrc);var n=t.matchPrefix(e,"a=rtcp-rsize");r.reducedSize=n.length>0,r.compound=0===n.length;var s=t.matchPrefix(e,"a=rtcp-mux");return r.mux=s.length>0,r},t.parseMsid=function(e){var r,i=t.matchPrefix(e,"a=msid:");if(1===i.length)return{stream:(r=i[0].substr(7).split(" "))[0],track:r[1]};var n=t.matchPrefix(e,"a=ssrc:").map((function(e){return t.parseSsrcMedia(e)})).filter((function(e){return"msid"===e.attribute}));return n.length>0?{stream:(r=n[0].value.split(" "))[0],track:r[1]}:void 0},t.parseSctpDescription=function(e){var r,i=t.parseMLine(e),n=t.matchPrefix(e,"a=max-message-size:");n.length>0&&(r=parseInt(n[0].substr(19),10)),isNaN(r)&&(r=65536);var s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substr(12),10),protocol:i.fmt,maxMessageSize:r};if(t.matchPrefix(e,"a=sctpmap:").length>0){var o=t.matchPrefix(e,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(o[0],10),protocol:o[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){var r=[];return r="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&r.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,21)},t.writeSessionBoilerplate=function(e,r,i){var n=void 0!==r?r:2;return"v=0\r\no="+(i||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+n+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.writeMediaSection=function(e,r,i,n){var s=t.writeRtpDescription(e.kind,r);if(s+=t.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=t.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===i?"actpass":"active"),s+="a=mid:"+e.mid+"\r\n",e.direction?s+="a="+e.direction+"\r\n":e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o="msid:"+n.id+" "+e.rtpSender.track.id+"\r\n";s+="a="+o,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+o,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+o,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+t.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+t.localCName+"\r\n"),s},t.getDirection=function(e,r){for(var i=t.splitLines(e),n=0;n<i.length;n++)switch(i[n]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[n].substr(2)}return r?t.getDirection(r):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substr(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){var r=t.splitLines(e)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},t.parseOLine=function(e){var r=t.matchPrefix(e,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;for(var r=t.splitLines(e),i=0;i<r.length;i++)if(r[i].length<2||"="!==r[i].charAt(1))return!1;return!0},e.exports=t},D(N={exports:{}},N.exports),N.exports);function M(e,t,r,i,n){var s=A.writeRtpDescription(e.kind,t);if(s+=A.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=A.writeDtlsParameters(e.dtlsTransport.getLocalParameters(),"offer"===r?"actpass":n||"active"),s+="a=mid:"+e.mid+"\r\n",e.rtpSender&&e.rtpReceiver?s+="a=sendrecv\r\n":e.rtpSender?s+="a=sendonly\r\n":e.rtpReceiver?s+="a=recvonly\r\n":s+="a=inactive\r\n",e.rtpSender){var o=e.rtpSender._initialTrackId||e.rtpSender.track.id;e.rtpSender._initialTrackId=o;var a="msid:"+(i?i.id:"-")+" "+o+"\r\n";s+="a="+a,s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" "+a,e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" "+a,s+="a=ssrc-group:FID "+e.sendEncodingParameters[0].ssrc+" "+e.sendEncodingParameters[0].rtx.ssrc+"\r\n")}return s+="a=ssrc:"+e.sendEncodingParameters[0].ssrc+" cname:"+A.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+A.localCName+"\r\n"),s}function w(e,t){var r={codecs:[],headerExtensions:[],fecMechanisms:[]},i=function(e,t){e=parseInt(e,10);for(var r=0;r<t.length;r++)if(t[r].payloadType===e||t[r].preferredPayloadType===e)return t[r]},n=function(e,t,r,n){var s=i(e.parameters.apt,r),o=i(t.parameters.apt,n);return s&&o&&s.name.toLowerCase()===o.name.toLowerCase()};return e.codecs.forEach((function(i){for(var s=0;s<t.codecs.length;s++){var o=t.codecs[s];if(i.name.toLowerCase()===o.name.toLowerCase()&&i.clockRate===o.clockRate){if("rtx"===i.name.toLowerCase()&&i.parameters&&o.parameters.apt&&!n(i,o,e.codecs,t.codecs))continue;(o=JSON.parse(JSON.stringify(o))).numChannels=Math.min(i.numChannels,o.numChannels),r.codecs.push(o),o.rtcpFeedback=o.rtcpFeedback.filter((function(e){for(var t=0;t<i.rtcpFeedback.length;t++)if(i.rtcpFeedback[t].type===e.type&&i.rtcpFeedback[t].parameter===e.parameter)return!0;return!1}));break}}})),e.headerExtensions.forEach((function(e){for(var i=0;i<t.headerExtensions.length;i++){var n=t.headerExtensions[i];if(e.uri===n.uri){r.headerExtensions.push(n);break}}})),r}function U(e,t,r){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"]}}[t][e].indexOf(r)}function $(e,t){var r=e.getRemoteCandidates().find((function(e){return t.foundation===e.foundation&&t.ip===e.ip&&t.port===e.port&&t.priority===e.priority&&t.protocol===e.protocol&&t.type===e.type}));return r||e.addRemoteCandidate(t),!r}function j(e,t){var r=new Error(t);return r.name=e,r.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[e],r}var V=function(e,t){function r(t,r){r.addTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("addtrack",{track:t}))}function i(t,r,i,n){var s=new Event("track");s.track=r,s.receiver=i,s.transceiver={receiver:i},s.streams=n,e.setTimeout((function(){t._dispatchEvent("track",s)}))}var n=function(r){var i=this,n=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach((function(e){i[e]=n[e].bind(n)})),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",r=JSON.parse(JSON.stringify(r||{})),this.usingBundle="max-bundle"===r.bundlePolicy,"negotiate"===r.rtcpMuxPolicy)throw j("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(r.rtcpMuxPolicy||(r.rtcpMuxPolicy="require"),r.iceTransportPolicy){case"all":case"relay":break;default:r.iceTransportPolicy="all"}switch(r.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:r.bundlePolicy="balanced"}if(r.iceServers=function(e,t){var r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((function(e){if(e&&(e.urls||e.url)){var i=e.urls||e.url;e.url&&!e.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var n="string"==typeof i;return n&&(i=[i]),i=i.filter((function(e){return 0!==e.indexOf("turn:")||-1===e.indexOf("transport=udp")||-1!==e.indexOf("turn:[")||r?0===e.indexOf("stun:")&&t>=14393&&-1===e.indexOf("?transport=udp"):(r=!0,!0)})),delete e.url,e.urls=n?i[0]:i,!!i.length}}))}(r.iceServers||[],t),this._iceGatherers=[],r.iceCandidatePoolSize)for(var s=r.iceCandidatePoolSize;s>0;s--)this._iceGatherers.push(new e.RTCIceGatherer({iceServers:r.iceServers,gatherPolicy:r.iceTransportPolicy}));else r.iceCandidatePoolSize=0;this._config=r,this.transceivers=[],this._sdpSessionId=A.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(n.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(n.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),n.prototype.onicecandidate=null,n.prototype.onaddstream=null,n.prototype.ontrack=null,n.prototype.onremovestream=null,n.prototype.onsignalingstatechange=null,n.prototype.oniceconnectionstatechange=null,n.prototype.onconnectionstatechange=null,n.prototype.onicegatheringstatechange=null,n.prototype.onnegotiationneeded=null,n.prototype.ondatachannel=null,n.prototype._dispatchEvent=function(e,t){this._isClosed||(this.dispatchEvent(t),"function"==typeof this["on"+e]&&this["on"+e](t))},n.prototype._emitGatheringStateChange=function(){var e=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",e)},n.prototype.getConfiguration=function(){return this._config},n.prototype.getLocalStreams=function(){return this.localStreams},n.prototype.getRemoteStreams=function(){return this.remoteStreams},n.prototype._createTransceiver=function(e,t){var r=this.transceivers.length>0,i={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:e,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&r)i.iceTransport=this.transceivers[0].iceTransport,i.dtlsTransport=this.transceivers[0].dtlsTransport;else{var n=this._createIceAndDtlsTransports();i.iceTransport=n.iceTransport,i.dtlsTransport=n.dtlsTransport}return t||this.transceivers.push(i),i},n.prototype.addTrack=function(t,r){if(this._isClosed)throw j("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw j("InvalidAccessError","Track already exists.");for(var n=0;n<this.transceivers.length;n++)this.transceivers[n].track||this.transceivers[n].kind!==t.kind||(i=this.transceivers[n]);return i||(i=this._createTransceiver(t.kind)),this._maybeFireNegotiationNeeded(),-1===this.localStreams.indexOf(r)&&this.localStreams.push(r),i.track=t,i.stream=r,i.rtpSender=new e.RTCRtpSender(t,i.dtlsTransport),i.rtpSender},n.prototype.addStream=function(e){var r=this;if(t>=15025)e.getTracks().forEach((function(t){r.addTrack(t,e)}));else{var i=e.clone();e.getTracks().forEach((function(e,t){var r=i.getTracks()[t];e.addEventListener("enabled",(function(e){r.enabled=e.enabled}))})),i.getTracks().forEach((function(e){r.addTrack(e,i)}))}},n.prototype.removeTrack=function(t){if(this._isClosed)throw j("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(t instanceof e.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var r=this.transceivers.find((function(e){return e.rtpSender===t}));if(!r)throw j("InvalidAccessError","Sender was not created by this connection.");var i=r.stream;r.rtpSender.stop(),r.rtpSender=null,r.track=null,r.stream=null,-1===this.transceivers.map((function(e){return e.stream})).indexOf(i)&&this.localStreams.indexOf(i)>-1&&this.localStreams.splice(this.localStreams.indexOf(i),1),this._maybeFireNegotiationNeeded()},n.prototype.removeStream=function(e){var t=this;e.getTracks().forEach((function(e){var r=t.getSenders().find((function(t){return t.track===e}));r&&t.removeTrack(r)}))},n.prototype.getSenders=function(){return this.transceivers.filter((function(e){return!!e.rtpSender})).map((function(e){return e.rtpSender}))},n.prototype.getReceivers=function(){return this.transceivers.filter((function(e){return!!e.rtpReceiver})).map((function(e){return e.rtpReceiver}))},n.prototype._createIceGatherer=function(t,r){var i=this;if(r&&t>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var n=new e.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(n,"state",{value:"new",writable:!0}),this.transceivers[t].bufferedCandidateEvents=[],this.transceivers[t].bufferCandidates=function(e){var r=!e.candidate||0===Object.keys(e.candidate).length;n.state=r?"completed":"gathering",null!==i.transceivers[t].bufferedCandidateEvents&&i.transceivers[t].bufferedCandidateEvents.push(e)},n.addEventListener("localcandidate",this.transceivers[t].bufferCandidates),n},n.prototype._gather=function(t,r){var i=this,n=this.transceivers[r].iceGatherer;if(!n.onlocalcandidate){var s=this.transceivers[r].bufferedCandidateEvents;this.transceivers[r].bufferedCandidateEvents=null,n.removeEventListener("localcandidate",this.transceivers[r].bufferCandidates),n.onlocalcandidate=function(e){if(!(i.usingBundle&&r>0)){var s=new Event("icecandidate");s.candidate={sdpMid:t,sdpMLineIndex:r};var o=e.candidate,a=!o||0===Object.keys(o).length;if(a)"new"!==n.state&&"gathering"!==n.state||(n.state="completed");else{"new"===n.state&&(n.state="gathering"),o.component=1,o.ufrag=n.getLocalParameters().usernameFragment;var c=A.writeCandidate(o);s.candidate=Object.assign(s.candidate,A.parseCandidate(c)),s.candidate.candidate=c,s.candidate.toJSON=function(){return{candidate:s.candidate.candidate,sdpMid:s.candidate.sdpMid,sdpMLineIndex:s.candidate.sdpMLineIndex,usernameFragment:s.candidate.usernameFragment}}}var d=A.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=A.getDescription(i._localDescription.sdp)+d.join("");var u=i.transceivers.every((function(e){return e.iceGatherer&&"completed"===e.iceGatherer.state}));"gathering"!==i.iceGatheringState&&(i.iceGatheringState="gathering",i._emitGatheringStateChange()),a||i._dispatchEvent("icecandidate",s),u&&(i._dispatchEvent("icecandidate",new Event("icecandidate")),i.iceGatheringState="complete",i._emitGatheringStateChange())}},e.setTimeout((function(){s.forEach((function(e){n.onlocalcandidate(e)}))}),0)}},n.prototype._createIceAndDtlsTransports=function(){var t=this,r=new e.RTCIceTransport(null);r.onicestatechange=function(){t._updateIceConnectionState(),t._updateConnectionState()};var i=new e.RTCDtlsTransport(r);return i.ondtlsstatechange=function(){t._updateConnectionState()},i.onerror=function(){Object.defineProperty(i,"state",{value:"failed",writable:!0}),t._updateConnectionState()},{iceTransport:r,dtlsTransport:i}},n.prototype._disposeIceAndDtlsTransports=function(e){var t=this.transceivers[e].iceGatherer;t&&(delete t.onlocalcandidate,delete this.transceivers[e].iceGatherer);var r=this.transceivers[e].iceTransport;r&&(delete r.onicestatechange,delete this.transceivers[e].iceTransport);var i=this.transceivers[e].dtlsTransport;i&&(delete i.ondtlsstatechange,delete i.onerror,delete this.transceivers[e].dtlsTransport)},n.prototype._transceive=function(e,r,i){var n=w(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:A.localCName,compound:e.rtcpParameters.compound},e.recvEncodingParameters.length&&(n.rtcp.ssrc=e.recvEncodingParameters[0].ssrc),e.rtpSender.send(n)),i&&e.rtpReceiver&&n.codecs.length>0&&("video"===e.kind&&e.recvEncodingParameters&&t<15019&&e.recvEncodingParameters.forEach((function(e){delete e.rtx})),e.recvEncodingParameters.length?n.encodings=e.recvEncodingParameters:n.encodings=[{}],n.rtcp={compound:e.rtcpParameters.compound},e.rtcpParameters.cname&&(n.rtcp.cname=e.rtcpParameters.cname),e.sendEncodingParameters.length&&(n.rtcp.ssrc=e.sendEncodingParameters[0].ssrc),e.rtpReceiver.receive(n))},n.prototype.setLocalDescription=function(e){var t,r,i=this;if(-1===["offer","answer"].indexOf(e.type))return Promise.reject(j("TypeError",'Unsupported type "'+e.type+'"'));if(!U("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(j("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=A.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=A.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=A.splitSections(i._remoteDescription.sdp),r=t.shift();var n=A.matchPrefix(r,"a=ice-lite").length>0;t.forEach((function(e,t){var s=i.transceivers[t],o=s.iceGatherer,a=s.iceTransport,c=s.dtlsTransport,d=s.localCapabilities,u=s.remoteCapabilities;if(!(A.isRejected(e)&&0===A.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var l=A.getIceParameters(e,r),p=A.getDtlsParameters(e,r);n&&(p.role="server"),i.usingBundle&&0!==t||(i._gather(s.mid,t),"new"===a.state&&a.start(o,l,n?"controlling":"controlled"),"new"===c.state&&c.start(p));var h=w(d,u);i._transceive(s,h.codecs.length>0,!1)}}))}return i._localDescription={type:e.type,sdp:e.sdp},"offer"===e.type?i._updateSignalingState("have-local-offer"):i._updateSignalingState("stable"),Promise.resolve()},n.prototype.setRemoteDescription=function(n){var s=this;if(-1===["offer","answer"].indexOf(n.type))return Promise.reject(j("TypeError",'Unsupported type "'+n.type+'"'));if(!U("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(j("InvalidStateError","Can not set remote "+n.type+" in state "+s.signalingState));var o={};s.remoteStreams.forEach((function(e){o[e.id]=e}));var a=[],c=A.splitSections(n.sdp),d=c.shift(),u=A.matchPrefix(d,"a=ice-lite").length>0,l=A.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=l;var p=A.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!p&&p.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var p=A.splitLines(i),h=A.getKind(i),m=A.isRejected(i)&&0===A.matchPrefix(i,"a=bundle-only").length,_=p[0].substr(2).split(" ")[2],C=A.getDirection(i,d),R=A.parseMsid(i),f=A.getMid(i)||A.generateIdentifier();if(m||"application"===h&&("DTLS/SCTP"===_||"UDP/DTLS/SCTP"===_))s.transceivers[c]={mid:f,kind:h,protocol:_,rejected:!0};else{var v,T,g,S,y,E,I,k,b;!m&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(h,!0));var x,P,O=A.parseRtpParameters(i);m||(x=A.getIceParameters(i,d),(P=A.getDtlsParameters(i,d)).role="client"),I=A.parseRtpEncodingParameters(i);var L=A.parseRtcpParameters(i),D=A.matchPrefix(i,"a=end-of-candidates",d).length>0,N=A.matchPrefix(i,"a=candidate:").map((function(e){return A.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!m&&l&&c>0&&s.transceivers[c]&&(s._disposeIceAndDtlsTransports(c),s.transceivers[c].iceGatherer=s.transceivers[0].iceGatherer,s.transceivers[c].iceTransport=s.transceivers[0].iceTransport,s.transceivers[c].dtlsTransport=s.transceivers[0].dtlsTransport,s.transceivers[c].rtpSender&&s.transceivers[c].rtpSender.setTransport(s.transceivers[0].dtlsTransport),s.transceivers[c].rtpReceiver&&s.transceivers[c].rtpReceiver.setTransport(s.transceivers[0].dtlsTransport)),"offer"!==n.type||m){if("answer"===n.type&&!m){T=(v=s.transceivers[c]).iceGatherer,g=v.iceTransport,S=v.dtlsTransport,y=v.rtpReceiver,E=v.sendEncodingParameters,k=v.localCapabilities,s.transceivers[c].recvEncodingParameters=I,s.transceivers[c].remoteCapabilities=O,s.transceivers[c].rtcpParameters=L,N.length&&"new"===g.state&&(!u&&!D||l&&0!==c?N.forEach((function(e){$(v.iceTransport,e)})):g.setRemoteCandidates(N)),l&&0!==c||("new"===g.state&&g.start(T,x,"controlling"),"new"===S.state&&S.start(P)),!w(v.localCapabilities,v.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&v.sendEncodingParameters[0].rtx&&delete v.sendEncodingParameters[0].rtx,s._transceive(v,"sendrecv"===C||"recvonly"===C,"sendrecv"===C||"sendonly"===C),!y||"sendrecv"!==C&&"sendonly"!==C?delete v.rtpReceiver:(b=y.track,R?(o[R.stream]||(o[R.stream]=new e.MediaStream),r(b,o[R.stream]),a.push([b,y,o[R.stream]])):(o.default||(o.default=new e.MediaStream),r(b,o.default),a.push([b,y,o.default])))}}else{(v=s.transceivers[c]||s._createTransceiver(h)).mid=f,v.iceGatherer||(v.iceGatherer=s._createIceGatherer(c,l)),N.length&&"new"===v.iceTransport.state&&(!D||l&&0!==c?N.forEach((function(e){$(v.iceTransport,e)})):v.iceTransport.setRemoteCandidates(N)),k=e.RTCRtpReceiver.getCapabilities(h),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),E=v.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,U=!1;if("sendrecv"===C||"sendonly"===C){if(U=!v.rtpReceiver,y=v.rtpReceiver||new e.RTCRtpReceiver(v.dtlsTransport,h),U)b=y.track,R&&"-"===R.stream||(R?(o[R.stream]||(o[R.stream]=new e.MediaStream,Object.defineProperty(o[R.stream],"id",{get:function(){return R.stream}})),Object.defineProperty(b,"id",{get:function(){return R.track}}),M=o[R.stream]):(o.default||(o.default=new e.MediaStream),M=o.default)),M&&(r(b,M),v.associatedRemoteMediaStreams.push(M)),a.push([b,y,M])}else v.rtpReceiver&&v.rtpReceiver.track&&(v.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===v.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),v.associatedRemoteMediaStreams=[]);v.localCapabilities=k,v.remoteCapabilities=O,v.rtpReceiver=y,v.rtcpParameters=L,v.sendEncodingParameters=E,v.recvEncodingParameters=I,s._transceive(s.transceivers[c],!1,U)}}})),void 0===s._dtlsRole&&(s._dtlsRole="offer"===n.type?"active":"passive"),s._remoteDescription={type:n.type,sdp:n.sdp},"offer"===n.type?s._updateSignalingState("have-remote-offer"):s._updateSignalingState("stable"),Object.keys(o).forEach((function(t){var r=o[t];if(r.getTracks().length){if(-1===s.remoteStreams.indexOf(r)){s.remoteStreams.push(r);var n=new Event("addstream");n.stream=r,e.setTimeout((function(){s._dispatchEvent("addstream",n)}))}a.forEach((function(e){var t=e[0],n=e[1];r.id===e[2].id&&i(s,t,n,[r])}))}})),a.forEach((function(e){e[2]||i(s,e[0],e[1],[])})),e.setTimeout((function(){s&&s.transceivers&&s.transceivers.forEach((function(e){e.iceTransport&&"new"===e.iceTransport.state&&e.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),e.iceTransport.addRemoteCandidate({}))}))}),4e3),Promise.resolve()},n.prototype.close=function(){this.transceivers.forEach((function(e){e.iceTransport&&e.iceTransport.stop(),e.dtlsTransport&&e.dtlsTransport.stop(),e.rtpSender&&e.rtpSender.stop(),e.rtpReceiver&&e.rtpReceiver.stop()})),this._isClosed=!0,this._updateSignalingState("closed")},n.prototype._updateSignalingState=function(e){this.signalingState=e;var t=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",t)},n.prototype._maybeFireNegotiationNeeded=function(){var t=this;"stable"===this.signalingState&&!0!==this.needNegotiation&&(this.needNegotiation=!0,e.setTimeout((function(){if(t.needNegotiation){t.needNegotiation=!1;var e=new Event("negotiationneeded");t._dispatchEvent("negotiationneeded",e)}}),0))},n.prototype._updateIceConnectionState=function(){var e,t={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&!e.rejected&&t[e.iceTransport.state]++})),e="new",t.failed>0?e="failed":t.checking>0?e="checking":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0?e="connected":t.completed>0&&(e="completed"),e!==this.iceConnectionState){this.iceConnectionState=e;var r=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",r)}},n.prototype._updateConnectionState=function(){var e,t={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach((function(e){e.iceTransport&&e.dtlsTransport&&!e.rejected&&(t[e.iceTransport.state]++,t[e.dtlsTransport.state]++)})),t.connected+=t.completed,e="new",t.failed>0?e="failed":t.connecting>0?e="connecting":t.disconnected>0?e="disconnected":t.new>0?e="new":t.connected>0&&(e="connected"),e!==this.connectionState){this.connectionState=e;var r=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",r)}},n.prototype.createOffer=function(){var r=this;if(r._isClosed)return Promise.reject(j("InvalidStateError","Can not call createOffer after close"));var i=r.transceivers.filter((function(e){return"audio"===e.kind})).length,n=r.transceivers.filter((function(e){return"video"===e.kind})).length,s=arguments[0];if(s){if(s.mandatory||s.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");void 0!==s.offerToReceiveAudio&&(i=!0===s.offerToReceiveAudio?1:!1===s.offerToReceiveAudio?0:s.offerToReceiveAudio),void 0!==s.offerToReceiveVideo&&(n=!0===s.offerToReceiveVideo?1:!1===s.offerToReceiveVideo?0:s.offerToReceiveVideo)}for(r.transceivers.forEach((function(e){"audio"===e.kind?--i<0&&(e.wantReceive=!1):"video"===e.kind&&--n<0&&(e.wantReceive=!1)}));i>0||n>0;)i>0&&(r._createTransceiver("audio"),i--),n>0&&(r._createTransceiver("video"),n--);var o=A.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||A.generateIdentifier();i.mid=a,i.iceGatherer||(i.iceGatherer=r._createIceGatherer(n,r.usingBundle));var c=e.RTCRtpSender.getCapabilities(o);t<15019&&(c.codecs=c.codecs.filter((function(e){return"rtx"!==e.name}))),c.codecs.forEach((function(e){"H264"===e.name&&void 0===e.parameters["level-asymmetry-allowed"]&&(e.parameters["level-asymmetry-allowed"]="1"),i.remoteCapabilities&&i.remoteCapabilities.codecs&&i.remoteCapabilities.codecs.forEach((function(t){e.name.toLowerCase()===t.name.toLowerCase()&&e.clockRate===t.clockRate&&(e.preferredPayloadType=t.payloadType)}))})),c.headerExtensions.forEach((function(e){(i.remoteCapabilities&&i.remoteCapabilities.headerExtensions||[]).forEach((function(t){e.uri===t.uri&&(e.id=t.id)}))}));var d=i.sendEncodingParameters||[{ssrc:1001*(2*n+1)}];s&&t>=15019&&"video"===o&&!d[0].rtx&&(d[0].rtx={ssrc:d[0].ssrc+1}),i.wantReceive&&(i.rtpReceiver=new e.RTCRtpReceiver(i.dtlsTransport,o)),i.localCapabilities=c,i.sendEncodingParameters=d})),"max-compat"!==r._config.bundlePolicy&&(o+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),o+="a=ice-options:trickle\r\n",r.transceivers.forEach((function(e,t){o+=M(e,e.localCapabilities,"offer",e.stream,r._dtlsRole),o+="a=rtcp-rsize\r\n",!e.iceGatherer||"new"===r.iceGatheringState||0!==t&&r.usingBundle||(e.iceGatherer.getLocalCandidates().forEach((function(e){e.component=1,o+="a="+A.writeCandidate(e)+"\r\n"})),"completed"===e.iceGatherer.state&&(o+="a=end-of-candidates\r\n"))}));var a=new e.RTCSessionDescription({type:"offer",sdp:o});return Promise.resolve(a)},n.prototype.createAnswer=function(){var r=this;if(r._isClosed)return Promise.reject(j("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(j("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=A.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.usingBundle&&(i+="a=group:BUNDLE "+r.transceivers.map((function(e){return e.mid})).join(" ")+"\r\n"),i+="a=ice-options:trickle\r\n";var n=A.getMediaSections(r._remoteDescription.sdp).length;r.transceivers.forEach((function(e,s){if(!(s+1>n)){if(e.rejected)return"application"===e.kind?"DTLS/SCTP"===e.protocol?i+="m=application 0 DTLS/SCTP 5000\r\n":i+="m=application 0 "+e.protocol+" webrtc-datachannel\r\n":"audio"===e.kind?i+="m=audio 0 UDP/TLS/RTP/SAVPF 0\r\na=rtpmap:0 PCMU/8000\r\n":"video"===e.kind&&(i+="m=video 0 UDP/TLS/RTP/SAVPF 120\r\na=rtpmap:120 VP8/90000\r\n"),void(i+="c=IN IP4 0.0.0.0\r\na=inactive\r\na=mid:"+e.mid+"\r\n");var o;if(e.stream)"audio"===e.kind?o=e.stream.getAudioTracks()[0]:"video"===e.kind&&(o=e.stream.getVideoTracks()[0]),o&&t>=15019&&"video"===e.kind&&!e.sendEncodingParameters[0].rtx&&(e.sendEncodingParameters[0].rtx={ssrc:e.sendEncodingParameters[0].ssrc+1});var a=w(e.localCapabilities,e.remoteCapabilities);!a.codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&e.sendEncodingParameters[0].rtx&&delete e.sendEncodingParameters[0].rtx,i+=M(e,a,"answer",e.stream,r._dtlsRole),e.rtcpParameters&&e.rtcpParameters.reducedSize&&(i+="a=rtcp-rsize\r\n")}}));var s=new e.RTCSessionDescription({type:"answer",sdp:i});return Promise.resolve(s)},n.prototype.addIceCandidate=function(e){var t,r=this;return e&&void 0===e.sdpMLineIndex&&!e.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise((function(i,n){if(!r._remoteDescription)return n(j("InvalidStateError","Can not add ICE candidate without a remote description"));if(e&&""!==e.candidate){var s=e.sdpMLineIndex;if(e.sdpMid)for(var o=0;o<r.transceivers.length;o++)if(r.transceivers[o].mid===e.sdpMid){s=o;break}var a=r.transceivers[s];if(!a)return n(j("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?A.parseCandidate(e.candidate):{};if("tcp"===c.protocol&&(0===c.port||9===c.port))return i();if(c.component&&1!==c.component)return i();if((0===s||s>0&&a.iceTransport!==r.transceivers[0].iceTransport)&&!$(a.iceTransport,c))return n(j("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=A.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=A.getDescription(r._remoteDescription.sdp)+t.join("")}else for(var u=0;u<r.transceivers.length&&(r.transceivers[u].rejected||(r.transceivers[u].iceTransport.addRemoteCandidate({}),(t=A.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=A.getDescription(r._remoteDescription.sdp)+t.join(""),!r.usingBundle));u++);i()}))},n.prototype.getStats=function(t){if(t&&t instanceof e.MediaStreamTrack){var r=null;if(this.transceivers.forEach((function(e){e.rtpSender&&e.rtpSender.track===t?r=e.rtpSender:e.rtpReceiver&&e.rtpReceiver.track===t&&(r=e.rtpReceiver)})),!r)throw j("InvalidAccessError","Invalid selector.");return r.getStats()}var i=[];return this.transceivers.forEach((function(e){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach((function(t){e[t]&&i.push(e[t].getStats())}))})),Promise.all(i).then((function(e){var t=new Map;return e.forEach((function(e){e.forEach((function(e){t.set(e.id,e)}))})),t}))};["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach((function(t){var r=e[t];if(r&&r.prototype&&r.prototype.getStats){var i=r.prototype.getStats;r.prototype.getStats=function(){return i.apply(this).then((function(e){var t=new Map;return Object.keys(e).forEach((function(r){var i;e[r].type={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[(i=e[r]).type]||i.type,t.set(r,e[r])})),t}))}}}));var s=["createOffer","createAnswer"];return s.forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[0]||"function"==typeof e[1]?t.apply(this,[arguments[2]]).then((function(t){"function"==typeof e[0]&&e[0].apply(null,[t])}),(function(t){"function"==typeof e[1]&&e[1].apply(null,[t])})):t.apply(this,arguments)}})),(s=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]||"function"==typeof e[2]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)}),(function(t){"function"==typeof e[2]&&e[2].apply(null,[t])})):t.apply(this,arguments)}})),["getStats"].forEach((function(e){var t=n.prototype[e];n.prototype[e]=function(){var e=arguments;return"function"==typeof e[1]?t.apply(this,arguments).then((function(){"function"==typeof e[1]&&e[1].apply(null)})):t.apply(this,arguments)}})),n};function B(e){const t=e&&e.navigator,r=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(e){return r(e).catch((e=>Promise.reject(function(e){return{name:{PermissionDeniedError:"NotAllowedError"}[e.name]||e.name,message:e.message,constraint:e.constraint,toString(){return this.name}}}(e))))}}function F(e){"getDisplayMedia"in e.navigator&&e.navigator.mediaDevices&&(e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=e.navigator.getDisplayMedia.bind(e.navigator)))}function H(e,t){if(e.RTCIceGatherer&&(e.RTCIceCandidate||(e.RTCIceCandidate=function(e){return e}),e.RTCSessionDescription||(e.RTCSessionDescription=function(e){return e}),t.version<15025)){const t=Object.getOwnPropertyDescriptor(e.MediaStreamTrack.prototype,"enabled");Object.defineProperty(e.MediaStreamTrack.prototype,"enabled",{set(e){t.set.call(this,e);const r=new Event("enabled");r.enabled=e,this.dispatchEvent(r)}})}e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)&&Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=new e.RTCDtmfSender(this):"video"===this.track.kind&&(this._dtmf=null)),this._dtmf}}),e.RTCDtmfSender&&!e.RTCDTMFSender&&(e.RTCDTMFSender=e.RTCDtmfSender);const r=V(e,t.version);e.RTCPeerConnection=function(e){return e&&e.iceServers&&(e.iceServers=function(e,t){let r=!1;return(e=JSON.parse(JSON.stringify(e))).filter((e=>{if(e&&(e.urls||e.url)){let t=e.urls||e.url;e.url&&!e.urls&&_("RTCIceServer.url","RTCIceServer.urls");const i="string"==typeof t;return i&&(t=[t]),t=t.filter((e=>{if(0===e.indexOf("stun:"))return!1;const t=e.startsWith("turn")&&!e.startsWith("turn:[")&&e.includes("transport=udp");return t&&!r?(r=!0,!0):t&&!r})),delete e.url,e.urls=i?t[0]:t,!!t.length}}))}(e.iceServers,t.version),m("ICE servers after filtering:",e.iceServers)),new r(e)},e.RTCPeerConnection.prototype=r.prototype}function G(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var J=Object.freeze({__proto__:null,shimPeerConnection:H,shimReplaceTrack:G,shimGetUserMedia:B,shimGetDisplayMedia:F});function W(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){_("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),r.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in r.mediaDevices.getSupportedConstraints())){const e=function(e,t,r){t in e&&!(r in e)&&(e[r]=e[t],delete e[t])},t=r.mediaDevices.getUserMedia.bind(r.mediaDevices);if(r.mediaDevices.getUserMedia=function(r){return"object"==typeof r&&"object"==typeof r.audio&&(r=JSON.parse(JSON.stringify(r)),e(r.audio,"autoGainControl","mozAutoGainControl"),e(r.audio,"noiseSuppression","mozNoiseSuppression")),t(r)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const r=t.apply(this,arguments);return e(r,"mozAutoGainControl","autoGainControl"),e(r,"mozNoiseSuppression","noiseSuppression"),r}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(r){return"audio"===this.kind&&"object"==typeof r&&(r=JSON.parse(JSON.stringify(r)),e(r,"autoGainControl","mozAutoGainControl"),e(r,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[r])}}}}function Y(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function K(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const r=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const r={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[e,n,s]=arguments;return i.apply(this,[e||null]).then((e=>{if(t.version<53&&!n)try{e.forEach((e=>{e.type=r[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:r[t.type]||t.type}))}))}return e})).then(n,s)}}function q(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const r=e.RTCPeerConnection.prototype.addTrack;r&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=r.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function z(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),l(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Q(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){_("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function X(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Z(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];const e=arguments[1],r=e&&"sendEncodings"in e;r&&e.sendEncodings.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(r){const{sender:t}=i,r=t.getParameters();(!("encodings"in r)||1===r.encodings.length&&0===Object.keys(r.encodings[0]).length)&&(r.encodings=e.sendEncodings,t.sendEncodings=e.sendEncodings,this.setParametersPromises.push(t.setParameters(r).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function ee(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function te(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function re(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var ie=Object.freeze({__proto__:null,shimOnTrack:Y,shimPeerConnection:K,shimSenderGetStats:q,shimReceiverGetStats:z,shimRemoveStream:Q,shimRTCDataChannel:X,shimAddTransceiver:Z,shimGetParameters:ee,shimCreateOffer:te,shimCreateAnswer:re,shimGetUserMedia:W,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(r){if(!r||!r.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===r.video?r.video={mediaSource:t}:r.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(r)})}});function ne(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach((r=>t.call(this,r,e))),e.getVideoTracks().forEach((r=>t.call(this,r,e)))},e.RTCPeerConnection.prototype.addTrack=function(e,...r){return r&&r.forEach((e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const r=e.getTracks();this.getSenders().forEach((e=>{r.includes(e.track)&&this.removeTrack(e)}))})}}function se(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);const t=new Event("addstream");t.stream=e,this.dispatchEvent(t)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const r=new Event("addstream");r.stream=t,e.dispatchEvent(r)}))}),t.apply(e,arguments)}}}function oe(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,r=t.createOffer,i=t.createAnswer,n=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],n=r.apply(this,[i]);return t?(n.then(e,t),Promise.resolve()):n},t.createAnswer=function(e,t){const r=arguments.length>=2?arguments[2]:arguments[0],n=i.apply(this,[r]);return t?(n.then(e,t),Promise.resolve()):n};let a=function(e,t,r){const i=n.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i};t.setLocalDescription=a,a=function(e,t,r){const i=s.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.setRemoteDescription=a,a=function(e,t,r){const i=o.apply(this,[e]);return r?(i.then(t,r),Promise.resolve()):i},t.addIceCandidate=a}function ae(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,r=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>r(ce(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function ce(e){return e&&void 0!==e.video?Object.assign({},e,{video:R(e.video)}):e}function de(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,r){if(e&&e.iceServers){const t=[];for(let r=0;r<e.iceServers.length;r++){let i=e.iceServers[r];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(_("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[r])}e.iceServers=t}return new t(e,r)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function ue(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function le(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio"),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const r=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&r?"sendrecv"===r.direction?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":"recvonly"===r.direction&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):!0!==e.offerToReceiveVideo||r||this.addTransceiver("video")}return t.apply(this,arguments)}}function pe(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var he=Object.freeze({__proto__:null,shimLocalStreamsAPI:ne,shimRemoteStreamsAPI:se,shimCallbacksAPI:oe,shimGetUserMedia:ae,shimConstraints:ce,shimRTCIceServerUrls:de,shimTrackEventTransceiver:ue,shimCreateOfferLegacy:le,shimAudioContext:pe});function me(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const r=new t(e),i=A.parseCandidate(e.candidate),n=Object.assign(r,i);return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,l(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function _e(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const r=function(e){if(!e||!e.sdp)return!1;const t=A.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=A.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const r=parseInt(t[1],10);return r!=r?-1:r},n=function(e){let r=65536;return"firefox"===t.browser&&(r=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),r},s=function(e,r){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const n=A.matchPrefix(e.sdp,"a=max-message-size:");return n.length>0?i=parseInt(n[0].substr(19),10):"firefox"===t.browser&&-1!==r&&(i=2147483637),i},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){const{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(r(arguments[0])){const e=i(arguments[0]),t=n(e),r=s(arguments[0],e);let o;o=0===t&&0===r?Number.POSITIVE_INFINITY:0===t||0===r?Math.max(t,r):Math.min(t,r);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>o}),this._sctp=a}return o.apply(this,arguments)}}function Ce(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const r=e.send;e.send=function(){const i=arguments[0],n=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&n>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return r.apply(e,arguments)}}const r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=r.apply(this,arguments);return t(e,this),e},l(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function Re(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const r=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const r=new Event("connectionstatechange",e);t.dispatchEvent(r)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),r.apply(this,arguments)}}))}function fe(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const r=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const r=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==e.trim())).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:r}):t.sdp=r}return r.apply(this,arguments)}}function ve(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const r=e.RTCPeerConnection.prototype.addIceCandidate;r&&0!==r.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():r.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}var Te=Object.freeze({__proto__:null,shimRTCIceCandidate:me,shimMaxMessageSize:_e,shimSendThrowTypeError:Ce,shimConnectionState:Re,removeExtmapAllowMixed:fe,shimAddIceCandidateNullOrEmpty:ve});const ge=function({window:e}={},t={shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0}){const r=m,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const{navigator:r}=e;if(r.mozGetUserMedia)t.browser="firefox",t.version=u(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=u(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=u(r.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!e.RTCPeerConnection||!r.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=u(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Te,extractVersion:u,disableLog:p,disableWarnings:h};switch(i.browser){case"chrome":if(!L||!P||!t.shimChrome)return r("Chrome shim is not included in this adapter release."),n;if(null===i.version)return r("Chrome shim can not determine version, not shimming."),n;r("adapter.js shimming chrome."),n.browserShim=L,ve(e,i),g(e,i),S(e),P(e,i),y(e),x(e,i),E(e),I(e),k(e),O(e,i),me(e),Re(e),_e(e,i),Ce(e),fe(e,i);break;case"firefox":if(!ie||!K||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=ie,ve(e,i),W(e,i),K(e,i),Y(e),Q(e),q(e),z(e),X(e),Z(e),ee(e),te(e),re(e),me(e),Re(e),_e(e,i),Ce(e);break;case"edge":if(!J||!H||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=J,B(e),F(e),H(e,i),G(e),_e(e,i),Ce(e);break;case"safari":if(!he||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=he,ve(e,i),de(e),le(e),oe(e),ne(e),se(e),ue(e),ae(e),pe(e),me(e),_e(e,i),Ce(e),fe(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var Se,ye,Ee;exports.RCFrameRate=void 0,(Se=exports.RCFrameRate||(exports.RCFrameRate={})).FPS_10="FPS_10",Se.FPS_15="FPS_15",Se.FPS_24="FPS_24",Se.FPS_30="FPS_30",exports.RCResolution=void 0,(ye=exports.RCResolution||(exports.RCResolution={})).W176_H132="W176_H132",ye.W176_H144="W176_H144",ye.W256_H144="W256_H144",ye.W320_H180="W320_H180",ye.W240_H240="W240_H240",ye.W320_H240="W320_H240",ye.W480_H360="W480_H360",ye.W640_H360="W640_H360",ye.W480_H480="W480_H480",ye.W640_H480="W640_H480",ye.W720_H480="W720_H480",ye.W1280_H720="W1280_H720",ye.W1920_H1080="W1920_H1080",exports.RCMediaType=void 0,(Ee=exports.RCMediaType||(exports.RCMediaType={}))[Ee.AUDIO_ONLY=0]="AUDIO_ONLY",Ee[Ee.VIDEO_ONLY=1]="VIDEO_ONLY",Ee[Ee.AUDIO_VIDEO=2]="AUDIO_VIDEO";const Ie={[exports.RCResolution.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[exports.RCResolution.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[exports.RCResolution.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[exports.RCResolution.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[exports.RCResolution.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[exports.RCResolution.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[exports.RCResolution.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[exports.RCResolution.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[exports.RCResolution.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[exports.RCResolution.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[exports.RCResolution.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[exports.RCResolution.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[exports.RCResolution.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},ke=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in Ie){const t=Ie[e],s=Math.abs(t.width*t.height-r);s<i&&(n=t,i=s)}return n},be={10:1,15:1,24:1.5,30:1.5},xe=e=>{let t=Number.MAX_VALUE,r=1;for(const i in be){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=be[i])}return r},Pe={getCameras:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>t(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class Oe extends e.EventEmitter{constructor(e,t,r,i,n){super(),this._tag=e,this._userId=t,this._kind=r,this._isLocalTrack=i,this._roomId=n,this._localMuted=!1,this._remoteMuted=!1,this._streamId=[this._userId||this._roomId,this._tag].join("_"),this._id=[this._streamId,this.isAudioTrack()?0:1].join("_")}getStreamId(){return this._streamId}getTrackId(){return this._id}getUserId(){return this._userId}__innerGetMediaStreamTrack(){return this._msTrack}getTag(){return this._tag}isLocalTrack(){return this._isLocalTrack}isVideoTrack(){return"video"===this._kind}isAudioTrack(){return"audio"===this._kind}isReady(){var e;return"live"===(null===(e=this._msTrack)||void 0===e?void 0:e.readyState)}__innerSetMediaStreamTrack(e){this._msTrack=e,this._setLocalMuted(this._localMuted);const t=this._msStream=this._msStream||new MediaStream,r=t.getTracks()[0];r&&t.removeTrack(r),e?t.addTrack(e):this._element&&(this._element.pause(),this._element.srcObject=null)}_setLocalMuted(e){this._msTrack&&(this._msTrack.enabled=!e),this._localMuted=e}mute(){r.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){r.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(i,n){return t(this,void 0,void 0,(function*(){if(!this._msTrack)return r.warn(`the track is not ready to play -> id: ${this._id}`),{code:exports.RCRTCCode.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&r.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==n?void 0:n.volume){if(!e.isNumber(null==n?void 0:n.volume))return r.error(`${null==n?void 0:n.volume} is not a number, the valid range of options.volume is 0-100`),{code:exports.RCRTCCode.PARAMS_ERROR};(null==n?void 0:n.volume)<0&&(n.volume=0,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==n?void 0:n.volume)>100&&(n.volume=100,r.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==n?void 0:n.audioDeviceId){if(!(yield Pe.getSpeakers()).map((e=>e.deviceId)).includes(n.audioDeviceId))return r.error(`the options.audioDeviceId is invalid --\x3e ${n.audioDeviceId}`),{code:exports.RCRTCCode.PARAMS_ERROR}}const t=this.isVideoTrack();if(t&&(!i||!(i instanceof HTMLVideoElement)))return r.error(`the video track need an <video> to play -> id: ${this._id}`),{code:exports.RCRTCCode.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=t?i:this._element||new Audio,this._localMuted&&this._setLocalMuted(!1),this._element.srcObject&&this._element.srcObject===this._msStream||this._element.pause(),this._element.onloadstart=e=>{var t;r.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;r.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;r.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;r.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;r.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;r.info(`HTMLMediaElement oncanplay -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onvolumechange=e=>{var t;const i=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));r.info(`HTMLMediaElement onvolumechange -> volume: ${i}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,t&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),t||!(null==n?void 0:n.volume)&&0!==(null==n?void 0:n.volume)||(this._element.volume=(null==n?void 0:n.volume)/100);try{(null==n?void 0:n.audioDeviceId)&&!t?yield this._element.setSinkId(n.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(r.error(`setSinkId failed -> ${e.message}`),{code:exports.RCRTCCode.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(r.error(e),{code:exports.RCRTCCode.TRACK_PLAY_ERROR})}return{code:exports.RCRTCCode.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class Le extends Oe{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(Le.EVENT_LOCAL_TRACK_END,this),this.removeAll(Le.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(Le.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;r.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(Le.__INNER_EVENT_DESTROY__,this)}setBitrate(t=0,i=0,n=0){!e.isNumber(t)||!e.isNumber(i)||!e.isNumber(n)||t<=0||i<=0||t<i?r.error("setBitrate params error ->"):this._bitrateInfo={max:t,min:i,start:n}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?qe(this._msTrack):{min:0,max:0};return{min:(null===(e=this._bitrateInfo)||void 0===e?void 0:e.min)||r,max:(null===(t=this._bitrateInfo)||void 0===t?void 0:t.max)||i}}}Le.EVENT_LOCAL_TRACK_END="local-track-end",Le.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Le.__INNER_EVENT_DESTROY__="inner-destroy";class De extends Le{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,i){r.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Ne extends Le{constructor(e,t,r,i=!1){super(e,t,"video",r),this._isTiny=i}__isTiny(){return this._isTiny}getStreamId(){const e=super.getStreamId();return this._isTiny?`${e}_tiny`:e}getTrackId(){const e=super.getTrackId();return this._isTiny?`${e}_tiny`:e}}class Ae extends Le{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,Ae.__innerSetMapping(this.getTrackId(),n)}static __innerSetMapping(e,t){const r=this._mapping.get(t)||[];r.push(e),this._mapping.set(t,r)}static __innerRemoveMapping(e,t){var r,i;const n=null===(r=this._mapping.get(t))||void 0===r?void 0:r.filter((t=>t!==e));n&&n.length>0?this._mapping.set(t,n):(this._mapping.delete(t),t.pause(),t.src="",null===(i=t.parentNode)||void 0===i||i.removeChild(t))}destroy(){this.isAudioTrack()&&this.mute(),Ae.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}Ae._mapping=new Map;class Me extends Ae{constructor(e,t,r,i){super(e,t,"video",r,i)}}class we extends Ae{constructor(e,t,r,i){super(e,t,"audio",r,i)}_setLocalMuted(e){this._resource&&(this._resource.muted=e),super._setLocalMuted(e)}play(){return this._setLocalMuted(!1),Promise.resolve({code:exports.RCRTCCode.SUCCESS})}}class Ue extends De{}class $e extends Ne{}class je extends Ne{}class Ve extends Oe{constructor(e,t,r,i){super(e,t,r,!1,i),this._isSubscribed=!1}__innerSetRemoteMuted(e){this._remoteMuted=e}__innerSetSubscribed(e){this._isSubscribed=e}isSubscribed(){return this._isSubscribed}}class Be extends Ve{constructor(e,t,r){super(e,t,"audio",r)}}class Fe extends Ve{constructor(e,t,r){super(e,t,"video",r)}}const He=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),Ge=e=>JSON.stringify(e),Je=e=>/^[a-zA-Z\d-=]+$/g.test(e),We="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),Ye=t=>{if(void 0===t)return 0;if(e.isNumber(t))return t;const r=t;return r.exact||r.ideal||r.max||0},Ke=e=>{const t=e.getConstraints();return{width:Ye(t.width),height:Ye(t.height),frameRate:Ye(t.frameRate)}},qe=e=>{const{width:t,height:r,frameRate:i}=Ke(e),n=ke(t,r),s=xe(i);return{min:n.minBitrate*s,max:n.maxBitrate*s}},ze=e=>[e.msid,e.mediaType].join("_"),Qe=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Xe=(e,t)=>[e,t].join("_"),Ze=e=>e.map((e=>Object.assign({},e))),et=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],s=[];return t.forEach((t=>{const n=ze(t);let o=e.findIndex((e=>ze(e)===n));if(r&&(o=e.findIndex((e=>e.uri===t.uri))),-1===o)return void i.push(t);const a=e[o];a.uri!==t.uri?i.push(t):a.state!==t.state&&s.push(t),e.splice(o,1)})),n.push(...e),{publishedList:i,unpublishedList:n,modifiedList:s}},tt=()=>{let e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return e=e.replace(/-/g,"")+"0",e=parseInt(e,16),e=(e=>{const t="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ+/".split(""),r=t.length+1;let i=+e;const n=[];do{const e=i%r;i=(i-e)/r,n.unshift(t[e])}while(i);return n.join("")})(e),e.length>22&&(e=e.slice(0,22)),e},rt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},it=e=>!!exports.RCResolution[e],nt=e=>!!exports.RCFrameRate[e],st=e=>parseInt(e.replace("FPS_","")),ot=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=ge.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function at(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function ct(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const dt=e=>"[object Null]"===Object.prototype.toString.call(e),ut=e=>1===e.type,lt=e=>{const t={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const n=[],s=e.users[i];if(s.uris)try{n.push(...JSON.parse(s.uris))}catch(e){r.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}t[i]=n})),t};var pt,ht;!function(e){e.PUBLISH="RCRTC:PublishResource",e.UNPUBLISH="RCRTC:UnpublishResource",e.MODIFY="RCRTC:ModifyResource",e.TOTAL_CONTENT_RESOURCE="RCRTC:TotalContentResources",e.STATE="RCRTC:state",e.ROOM_NOTIFY="RCRTC:RoomNtf",e.USER_NOTIFY="RCRTC:UserNtf",e.KICK="RCRTC:kick"}(pt||(pt={})),exports.RCRTCPingResult=void 0,(ht=exports.RCRTCPingResult||(exports.RCRTCPingResult={})).SUCCESS="Success",ht.FAIL="Fail";class mt{constructor(e,t,r,i=1e4){this._roomId=e,this._roomMode=t,this._context=r,this._gap=i,this._latestTimestamp=Date.now(),this._timer=null}start(){return t(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var i,n,s;return t(this,void 0,void 0,(function*(){const t=yield new Promise((t=>{this._context.rtcPing(this._roomId,this._roomMode).then(t).catch((i=>{r.error(`rtcping receive unknown error -> ${i}`),t(e.ErrorCode.UNKNOWN)})),setTimeout(t,1e4,e.ErrorCode.TIMEOUT)})),o=Date.now();if(t===e.ErrorCode.SUCCESS)return this._latestTimestamp=o,void(null===(i=this.onPingResult)||void 0===i||i.call(this,exports.RCRTCPingResult.SUCCESS));null===(n=this.onPingResult)||void 0===n||n.call(this,exports.RCRTCPingResult.FAIL),r.warn(`rtcping failed -> code: ${t}`),(40003===t||o-this._latestTimestamp>6e4)&&(this.stop(),null===(s=this.onFailed)||void 0===s||s.call(this,40003===t))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var _t;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(_t||(_t={}));const Ct=(e,t)=>Math.round(8*t/e),Rt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},ft=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},vt=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return Rt(e/t,3);const n=t-i;if(0===n)return 0;const s=e-r;return s<0||n<0?0:Rt(s/n,3)},Tt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!dt(t)||!dt(r)||0!==i};class gt{constructor(e,t){this._rtcPeerConn=e,this._sdpSemantics=t,this._latestPacketsSent={},this._latestBytesSent={},this._latestBytesRecv={},this._latestPacketsRecv={}}updateBytesSent(e,t,r){let i,n;if(this._latestBytesSent[e]&&t<this._latestBytesSent[e].bytesSent&&this.clearLatestpacketsSent([e]),this._latestBytesSent[e]){const{bytesSent:s,timestamp:o}=this._latestBytesSent[e];i=t-s,n=r-o,this._latestBytesSent[e]={bytesSent:t,timestamp:r}}else i=t,n=1e3,this._latestBytesSent[e]={bytesSent:t,timestamp:r};return Ct(n,i)}updateBytesRecv(e,t,r){let i,n;if(this._latestBytesRecv[e]&&t<this._latestBytesRecv[e].bytesRecv&&this.clearLatestPacketsRecv([e]),this._latestBytesRecv[e]){const{bytesRecv:s,timestamp:o}=this._latestBytesRecv[e];i=t-s,n=r-o,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r}}else i=t,n=1e3,this._latestBytesRecv[e]={bytesRecv:t,timestamp:r};return Ct(n,i)}updateSenderPacketsLost(e,t,r){let i;if(Object.prototype.hasOwnProperty.call(this._latestPacketsSent[e],"packetsSent")){const{packetsLost:n,packetsSent:s}=this._latestPacketsSent[e];i=vt(t,r,n,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?s:r}else i=vt(t,r),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=r;return i}updateReceiverPacketsLost(e,t,r){let i;if(this._latestPacketsRecv[e]){const{packetsLost:n,packetsRecv:s}=this._latestPacketsRecv[e];i=vt(t,r+t,n,s+n)}else i=vt(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===exports.RCMediaType.VIDEO_ONLY){const t=`${e}_tiny`;delete this._latestPacketsSent[t],delete this._latestBytesSent[t]}delete this._latestPacketsSent[e],delete this._latestBytesSent[e]}))}clearLatestPacketsRecv(e){e.forEach((e=>{delete this._latestPacketsRecv[e],delete this._latestBytesRecv[e]}))}parseRTCStatsReport(e){const t=e.keys(),r={};let i=t.next();for(;!i.done;){const n=i.value,s=e.get(n);/^RTCCodec_/.test(n)||(r[n]=s),i=t.next()}return r}formatRCRTCStateReport(e){return{senders:[],receivers:[]}}getAudioLevelList(e){return[]}getResourceIdByParseSdp(e){var t,r;const i=e.ssrc,n=e.kind||e.mediaType,s=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,o=null===(r=this._rtcPeerConn.currentRemoteDescription)||void 0===r?void 0:r.sdp;let a;a="unified-plan"===this._sdpSemantics?new RegExp("a=msid:(.*?) "):new RegExp(`a=ssrc:${i} msid:(.*?) `);const c=null==s?void 0:s.split("\r\nm="),d=null==c?void 0:c.filter((e=>e.includes(`a=ssrc:${i}`)))[0],u=null==d?void 0:d.match(a);let l=u?u[1]:"";if(l)return`${l}_${"video"===n?1:0}`;const p=null==o?void 0:o.split("\r\nm="),h=null==p?void 0:p.filter((e=>e.includes(`a=ssrc:${i}`)))[0],m=null==h?void 0:h.match(a);return l=m?m[1]:"",`${l}_${"video"===n?1:0}`}isValidSender(e){var t;const r=null===(t=this._rtcPeerConn.currentLocalDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}isValidReceiver(e){var t;const r=null===(t=this._rtcPeerConn.currentRemoteDescription)||void 0===t?void 0:t.sdp,{ssrc:i}=e;return!(null==r?void 0:r.split("\r\nm=").some((e=>e.includes(i)&&e.includes("a=inactive"))))}}class St extends gt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const o=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(o))return;const{id:a,kind:c,transportId:d,mediaSourceId:u,remoteId:l,packetsSent:p,bytesSent:h,trackId:m,encoderImplementation:_,pliCount:C,nackCount:R,firCount:f}=o;if(!m)return;let{framesPerSecond:v,frameWidth:T,frameHeight:g}=o;"video"!==c||T||g||v||(T=e[m].frameWidth,g=e[m].frameHeight,v=u?e[u].framesPerSecond:null);const S=e[l];let y=null,E=null,I=0;S&&(y=S.jitter,E=S.roundTripTime,I=S.packetsLost),n+=I;const k=this.getResourceIdByParseSdp(o),b=u?e[u].audioLevel:e[m].audioLevel;let x=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),S?x=this.updateSenderPacketsLost(k,I,p):this._latestPacketsSent[k].crtPacketsSent=p;let P=this.updateBytesSent(k,h,r);P<0&&(P=0),s+=P,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:x,remoteResource:!1,audioLevel:b||0===b?ft(b):null,frameWidth:T,frameHeight:g,frameRate:v,bitrate:P,jitter:y?Math.round(1e3*y):y,rtt:E,encoderImplementation:_,pliCount:C,nackCount:R,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));i.filter((e=>/RTCRemoteInboundRtp(Video|Audio)Stream_/.test(e))).forEach((r=>{const{localId:i,jitter:n,roundTripTime:s,packetsLost:o}=e[r],a=t.senders.filter((e=>e.id===i))[0];if(a&&!Tt(a)){const t=this.getResourceIdByParseSdp(e[a.id]);a.jitter=Math.round(1e3*n),a.rtt=s;const r=this._latestPacketsSent[t].crtPacketsSent;a.packetsLostRate=this.updateSenderPacketsLost(t,o,r)}}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,framesPerSecond:p,kind:h,codecImplementationName:m,nackCount:_,pliCount:C}=s;if(!a)return;let{frameWidth:R,frameHeight:f,audioLevel:v}=s;"video"===h?R||f||(R=e[a].frameWidth,f=e[a].frameHeight):v||(v=e[a].audioLevel),n+=c;const T=this.getResourceIdByParseSdp(s),g=this.updateReceiverPacketsLost(T,c,d);let S=this.updateBytesRecv(T,l,r);S<0&&(S=0),o+=S,t.receivers.push({trackId:T,kind:h,packetsLostRate:g,remoteResource:!0,audioLevel:v||0===v?ft(v):null,frameWidth:R,frameHeight:f,frameRate:p,bitrate:S,jitter:u?Math.round(1e3*u):0,codecImplementationName:m,nackCount:_,pliCount:C,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,p=e[u],{ip:h,port:m,networkType:_}=p,C=e[l],{ip:R,port:f,protocol:v}=C;t.iceCandidatePair={IP:h,port:m,networkType:_,remoteIP:R,remotePort:f,protocol:v,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTPAudioStream_/.test(e))).forEach((r=>{var i;const n=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const{mediaSourceId:s,trackId:o}=n,a=this.getResourceIdByParseSdp(n),c=s&&e[s]?e[s].audioLevel:(null===(i=e[o])||void 0===i?void 0:i.audioLevel)||null;t.push({trackId:a,audioLevel:c||0===c?ft(c):null})}));return r.filter((e=>/^RTCInboundRTPAudioStream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n}=i,s=i.audioLevel||e[n].audioLevel,o=this.getResourceIdByParseSdp(i);t.push({trackId:o,audioLevel:s||0===s?ft(s):null})})),t}}class yt extends gt{formatRCRTCStateReport(e){const t=+new Date,r={senders:[],receivers:[],timestamp:t};let i=0,n=0,s=0;for(const o in e){const a=e[o],c=a.type;if("outbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(a))continue;const{id:s,kind:o,bytesSent:c,packetsSent:d,bitrateMean:u,framerateMean:l,nackCount:p,pliCount:h,remoteId:m}=a,{jitter:_,roundTripTime:C,packetsLost:R}=m?e[m]:{jitter:null,roundTripTime:null,packetsLost:0},f=this.getResourceIdByParseSdp(a);i+=R;let v=null;!this._latestPacketsSent[f]&&(this._latestPacketsSent[f]={}),m?v=this.updateSenderPacketsLost(f,R,d):this._latestPacketsSent[f].crtPacketsSent=d;let T=0;"video"===o?u&&(T=Math.floor(u/1e3)):T=this.updateBytesSent(f,c,t),T<0&&(T=0),n+=T,r.senders.push({trackId:f,kind:o,packetsLostRate:v,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:T,jitter:_?Math.round(1e3*_):null,rtt:C,encoderImplementation:null,pliCount:h,nackCount:p,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}if("remote-inbound-rtp"===c){const{localId:t}=a,i=this.getResourceIdByParseSdp(e[t]),n=r.senders.filter((e=>e.trackId===i))[0];n&&Tt(n)&&(n.jitter=Math.round(1e3*a.jitter),n.rtt=a.rtt,n.packetsLostRate=this.updateSenderPacketsLost(i,a.packetsLost,this._latestPacketsSent[i].crtPacketsSent))}if("inbound-rtp"===c){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(a))continue;const{id:e,packetsLost:n,bytesReceived:o,packetsReceived:c,jitter:d,framerateMean:u,kind:l,bitrateMean:p,nackCount:h,pliCount:m}=a,_=this.getResourceIdByParseSdp(a);i+=n;const C=this.updateReceiverPacketsLost(_,n,c);let R=0;"video"===l?p&&(R=Math.floor(p/1e3)):R=this.updateBytesRecv(_,o,t),R<0&&(R=0),s+=R,r.receivers.push({trackId:_,kind:l,packetsLostRate:C,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:R,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:h,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}if("candidate-pair"===c&&"succeeded"===a.state){const t=e[a.localCandidateId],{address:o,port:c}=t,d=e[a.remoteCandidateId],{address:u,port:l,protocol:p}=d;r.iceCandidatePair={IP:o,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:p,bitrateRecv:s,bitrateSend:n,rtt:null,availableOutgoingBitrate:null,availableIncomingBitrate:null,totalPacketsLost:i}}}return r.iceCandidatePair&&(r.iceCandidatePair.bitrateSend=n),r.iceCandidatePair&&(r.iceCandidatePair.bitrateRecv=s),r}getAudioLevelList(e){const t=[];for(const r in e){const i=e[r],n=i.type;if("outbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}if("inbound-rtp"===n){if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))continue;const{kind:e}=i;if("video"===e)continue;const r=this.getResourceIdByParseSdp(i);t.push({trackId:r,audioLevel:null})}}return t}}class Et extends gt{formatRCRTCStateReport(e){const t={senders:[],receivers:[]},r=Math.floor(e.RTCPeerConnection.timestamp);t.timestamp=r;const i=Object.keys(e);let n=0,s=0;i.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const n=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(n))return;const o=this.getResourceIdByParseSdp(n),{mediaType:a,transportId:c,remoteId:d,packetsSent:u,bytesSent:l,trackId:p,encoderImplementation:h,pliCount:m,nackCount:_,firCount:C}=n;if(!p)return;const{audioLevel:R,frameHeight:f,frameWidth:v}=e[p];let T=this.updateBytesSent(o,l,r);T<0&&(T=0),s+=T,t.senders.push({trackId:o,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:R||0===R?ft(R):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:T,jitter:null,rtt:null,encoderImplementation:h,pliCount:m,nackCount:_,googFirsSent:-1,samplingRate:-1,googRenderDelayMs:-1,trackState:-1})}));let o=0;i.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((i=>{const s=e[i];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(s))return;const{trackId:a,packetsLost:c,packetsReceived:d,jitter:u,bytesReceived:l,mediaType:p,nackCount:h,pliCount:m}=s,_=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:C,frameWidth:R,audioLevel:f}=e[a];n+=c;const v=this.updateReceiverPacketsLost(_,c,d);let T=this.updateBytesRecv(_,l,r);T<0&&(T=0),o+=T,t.receivers.push({trackId:_,kind:p,packetsLostRate:v,remoteResource:!0,audioLevel:f||0===f?ft(f):null,frameWidth:R,frameHeight:C,frameRate:null,bitrate:T,jitter:u,codecImplementationName:null,nackCount:h,pliCount:m,rtt:null,samplingRate:-1,googFirsReceived:-1,googRenderDelayMs:-1,trackState:-1})}));const a=i.filter((e=>/^RTCTransport_/.test(e)))[0];if(a){const r=e[a],{selectedCandidatePairId:i}=r;if(i){const r=e[i],{availableOutgoingBitrate:a,availableIncomingBitrate:c,currentRoundTripTime:d,localCandidateId:u,remoteCandidateId:l}=r,p=e[u],{address:h,port:m}=p,_=e[l],{address:C,port:R,protocol:f}=_;t.iceCandidatePair={IP:h||null,port:m,networkType:null,remoteIP:C,remotePort:R,protocol:f,bitrateRecv:o,bitrateSend:s,rtt:1e3*d,availableOutgoingBitrate:a,availableIncomingBitrate:c,totalPacketsLost:n},t.receivers.forEach((e=>{e.rtt=d}))}}return t}getAudioLevelList(e){const t=[],r=Object.keys(e);r.filter((e=>/^RTCOutboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidSender(i))return;const{trackId:n,mediaType:s}=i;if("video"===s)return;const o=this.getResourceIdByParseSdp(i),a=e[n];t.push({trackId:o,audioLevel:a||0===a?ft(a):null})}));return r.filter((e=>/^RTCInboundRTP(Video|Audio)Stream_/.test(e))).forEach((r=>{const i=e[r];if("unified-plan"===this._sdpSemantics&&!this.isValidReceiver(i))return;const{trackId:n,mediaType:s}=i;if(!n||"video"===s)return;const{audioLevel:o}=e[n],a=this.getResourceIdByParseSdp(i);t.push({trackId:a,audioLevel:o||0===o?ft(o):null})})),t}}class It{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:i,supportsUnifiedPlan:n}=ot;r.debug(`sdpSemantics, browser: ${t}, version: ${i}, supportsUnifiedPlan: ${n}`),n?/chrome/i.test(t)?this._sdpSemantics=i>92?"unified-plan":i<72?"plan-b":e:/firefox/i.test(t)?this._sdpSemantics="unified-plan":/safari/i.test(t)?this._sdpSemantics=i<12?"plan-b":"unified-plan":this._sdpSemantics="unified-plan":this._sdpSemantics="plan-b"}static getSdpSemantics(){return It._sdpSemantics}getOutboundVideoInfo(){const e=[];for(const t in this._outboundStreams){const r=this._outboundStreams[t].getVideoTracks()[0];if(!r)continue;const i=/_tiny$/.test(t),{width:n,height:s}=Ke(r);e.push({trackId:r.id,simulcast:i?_t.TINY:_t.NORMAL,resolution:`${n}x${s}`})}return e}setRemoteAnswer(e){return t(this,void 0,void 0,(function*(){e=e.replace(/\s+\r\n/g,"\r\n");try{yield this._peer.setRemoteDescription({type:"answer",sdp:e})}catch(e){return r.error(e),exports.RCRTCCode.SET_REMOTE_DESCRIPTION_FAILED}return exports.RCRTCCode.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(ot.browser)?new St(e,t):/Firefox/i.test(ot.browser)?new yt(e,t):/Safari/i.test(ot.browser)?new Et(e,t):null}}class kt extends It{constructor(){super(...arguments),this.senders={},this._localTracks=[]}addLocalTrack(e){this._localTracks.includes(e)||this._localTracks.push(e);const t=e.getStreamId(),r=e.__innerGetMediaStreamTrack(),i=this._outboundStreams[t]||(this._outboundStreams[t]=new MediaStream);i.getTracks().forEach((e=>{e.kind===r.kind&&i.removeTrack(e)})),i.addTrack(r);const n=e.getTrackId(),s=this.senders[n];s?s.replaceTrack(r):this.senders[n]=this._peer.addTrack(r,i)}removeLocalTrack(e){const t=this._localTracks.findIndex((t=>t===e));t>=0&&this._localTracks.splice(t,1);const r=e.getTrackId(),i=this.senders[r];i&&(i.replaceTrack(null),this._peer.removeTrack(i),delete this.senders[r])}updateSubRemoteTracks(e){}updateRecvTransceiverMap(e,t){}setBitrate(e,t,r){this._maxBitrate=e,this._minBitrate=t,this._startBitrate=r||.7*e}createOffer(e){return t(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e,offerToReceiveAudio:!0,offerToReceiveVideo:!0});for(const e in this._outboundStreams){const r=this._outboundStreams[e].id;t.sdp=t.sdp.replace(new RegExp(r,"g"),e)}return yield this._peer.setLocalDescription(t),{type:"offer",semantics:"plan-b",sdp:t.sdp}}))}setRemoteAnswer(e){let t=0,r=0;this._localTracks.forEach((e=>{const{min:i,max:n}=e.getBitrate();r+=i,t+=n})),t=this._maxBitrate&&this._maxBitrate>0?Math.min(t,this._maxBitrate):t,r=this._minBitrate&&this._minBitrate>0?Math.max(r,this._minBitrate):r;const i=this._startBitrate||Math.round(.7*t),n=`b=AS:${t}`;e=e.replace(/[\r\n]+m=video[^\r\n]+/,(e=>`${e}\r\n${n}`));const s=[`;x-google-min-bitrate=${r}`,`;x-google-max-bitrate=${t}`,`;x-google-start-bitrate=${i}`].join("");return e=e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+s)),super.setRemoteAnswer(e)}}class bt extends It{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,i){r.warn("the interface named `setBitrate` is invalid while sdpSemantics value is `unified-plan`")}addLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId(),i=e.__innerGetMediaStreamTrack();this._localTracks[t]=e;const n=this._outboundStreams[r]||(this._outboundStreams[r]=new MediaStream);n.getTracks().forEach((e=>{e.kind===i.kind&&n.removeTrack(e)})),n.addTrack(i);const s=this._sendTransceiver[t];s?(s.sender.replaceTrack(i),s.direction="sendonly"):this._sendTransceiver[t]=this._peer.addTransceiver(i,{direction:"sendonly",streams:[n]})}removeLocalTrack(e){const t=e.getTrackId(),r=e.getStreamId();e.__innerGetMediaStreamTrack(),delete this._localTracks[t];const i=this._sendTransceiver[t];if(!i)return;i.direction="inactive",this._peer.removeTrack(i.sender),i.sender.replaceTrack(null);const n=this._outboundStreams[r];(e.isAudioTrack()?n.getAudioTracks():n.getVideoTracks()).forEach((e=>n.removeTrack(e)));const s=this._sendTransceiver[`${t}_tiny`];if(!s||"inactive"===s.direction)return;s.direction="inactive";const o=s.sender,a=o.track;this._peer.removeTrack(o),o.replaceTrack(null);this._outboundStreams[`${r}_tiny`].removeTrack(a),a.stop()}updateRecvTransceiverMap(e,t){const{mediaType:r}=Qe(e);this._recvTransceiver[e]=t;const i=r===exports.RCMediaType.AUDIO_ONLY?this._recvAudio:this._recvVideo,n=i.findIndex((e=>e===t));n>=0&&i.splice(n,1)}updateSubRemoteTracks(e){const t=e.slice(),r=this._subedTracks.slice();this._subedTracks=e.slice();for(let e=t.length-1;e>=0;e-=1){const i=t[e],n=r.findIndex((e=>e===i));n>=0&&(t.splice(e,1),r.splice(n,1))}r.length&&r.forEach((e=>{const t=e.getTrackId();e.__innerSetMediaStreamTrack(void 0);const r=this._recvTransceiver[t];r&&(r.direction="inactive")}));const i={audio:0,video:0};t.length&&t.forEach((e=>{const t=e.isAudioTrack()?"audio":"video",r=this._recvTransceiver[e.getTrackId()];r?r.direction="recvonly":i[t]+=1}));for(let e=this._recvAudio.length;e<i.audio;e+=1)this._recvAudio.push(this._peer.addTransceiver("audio",{direction:"recvonly"}));for(let e=this._recvVideo.length;e<i.video;e+=1)this._recvVideo.push(this._peer.addTransceiver("video",{direction:"recvonly"}))}createOffer(e){return t(this,void 0,void 0,(function*(){const t=yield this._peer.createOffer({iceRestart:e});let r=t.sdp;for(const e in this._outboundStreams){const t=this._outboundStreams[e].id;r=r.replace(new RegExp(t,"g"),e)}return r=(e=>e.split(/\r\n(?=m=)/).map((e=>(e=>/a=(recvonly|inactive)/.test(e)?e.replace(/\r\na=(ssrc|msid)[^\r\n]+/g,""):e)(e))).join("\r\n"))(r),r=r.replace(/a=ice-options:trickle/g,"a=ice-options:trickle\r\na=ice-options:renomination"),t.sdp=r,yield this._peer.setLocalDescription(t),{type:"offer",semantics:"unified-plan",sdp:r}}))}setRemoteAnswer(e){e=e.split(/\r\n(?=m=)/).map((e=>{var t;const r=e.match(/a=mid:[^\s]+/);if(!r)return e;const i=r[0].replace("a=mid:","");let n="";for(const e in this._sendTransceiver){if(this._sendTransceiver[e].mid===i){n=e;break}}if(!n)return e;const s=null===(t=this._localTracks[n])||void 0===t?void 0:t.getBitrate();if(!s)return e;const{max:o,min:a}=s,c=o&&o>0?s.start||.7*o:0,d=[];if(o&&o>0&&d.push(`;x-google-max-bitrate=${o}`),a&&a>0&&d.push(`;x-google-min-bitrate=${a}`),c>0&&d.push(`;x-google-start-bitrate=${c}`),0===d.length)return e;const u=d.join("");return e.replace(/[\r\n]+[^\r\n]+profile-level-id[^\r\n]+/g,(e=>e+u))})).join("\r\n");const t=/[\r\n]+\r\n[\r\n]+/g;return t.test(e)&&(r.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class xt extends e.EventEmitter{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=It.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new kt(i):new bt(i),this._rtcPeerConn.oniceconnectionstatechange=this._onICEConnectionStateChange.bind(this),this._rtcPeerConn.onconnectionstatechange=this._onConnectionStateChange.bind(this),this._rtcPeerConn.ontrack=this._onTrackReady.bind(this),this.reportParser=this._sdpStrategy.getStatParsr(this._rtcPeerConn,r)}getLocalTracks(){return Object.values(this.pubLocalTracks)}_onConnectionStateChange(){r.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;r.info(`oniceconnectionstatechange -> ${this._rtcPeerConn.iceConnectionState}`),"connected"===this._rtcPeerConn.iceConnectionState&&(this._reportStatsTimer&&clearInterval(this._reportStatsTimer),this._reportStatsTimer=setInterval(this._reportHandle.bind(this),1e3)),"failed"!==this._rtcPeerConn.iceConnectionState&&"disconnected"!==this._rtcPeerConn.iceConnectionState||(r.warn("iceconenction state is `failed`, exchange SDP to try again."),this._reTryExchange(),this._reTryExchangeTimer=setInterval(this._reTryExchange,15e3));try{null===(t=null===(e=this._reportListener)||void 0===e?void 0:e.onICEConnectionStateChange)||void 0===t||t.call(e,this._rtcPeerConn.iceConnectionState)}catch(e){r.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(xt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,r,i){return t(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,r,i)}))}createOffer(e){return t(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return r.debug(`offer -> ${JSON.stringify(t.sdp)}`),t}))}setRemoteAnswer(e){return t(this,void 0,void 0,(function*(){return r.debug(`answer -> ${JSON.stringify(e)}`),this._sdpStrategy.setRemoteAnswer(e)}))}getLocalTrack(e){return this.pubLocalTracks[e]||null}addLocalTrack(e){this.pubLocalTracks[e.getTrackId()]=e,this._sdpStrategy.addLocalTrack(e),e.off(Le.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Le.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Le.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Le.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}removeLocalTrackById(e){const t=this.getLocalTrack(e);t&&this.removeLocalTrack(t)}removeAllLocalTrack(){Object.keys(this.pubLocalTracks).forEach((e=>{/_tiny$/.test(e)||this.removeLocalTrackById(e)}))}removeLocalTrack(e){const t=e.getTrackId();delete this.pubLocalTracks[t],this._sdpStrategy.removeLocalTrack(e),e.__innerSetPublished(!1),e.off(Le.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Le.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this);const r=`${t}_tiny`,i=this.getLocalTrack(r);i&&(this._sdpStrategy.removeLocalTrack(i),delete this.pubLocalTracks[r],i.destroy())}_updateRecvTransceiverMap(e,t){this._sdpStrategy.updateRecvTransceiverMap(e,t)}updateSubRemoteTracks(e){this._sdpStrategy.updateSubRemoteTracks(e)}getOutboundVideoInfo(){return this._sdpStrategy.getOutboundVideoInfo()}_onLocalTrackMuted(e){const t=this.getLocalTrack(`${e.getTrackId()}_tiny`);t&&(t.__innerGetMediaStreamTrack().enabled=!e.isLocalMuted()),this.emit(Le.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(Le.__INNER_EVENT_DESTROY__,e)}registerReportListener(e){this._reportListener=e}_createRCRTCStateReport(e){const{timestamp:t,iceCandidatePair:r,senders:i,receivers:n}=JSON.parse(JSON.stringify(e));null==r||delete r.totalPacketsLost;for(const e in r)dt(r[e])&&delete r[e];return{timestamp:t,iceCandidatePair:r,senders:i.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t})),receivers:n.map((e=>{const t={};return e.trackId&&(t.trackId=e.trackId),e.kind&&(t.kind=e.kind),(e.packetsLostRate||0===e.packetsLostRate)&&(t.packetsLostRate=e.packetsLostRate),t.remoteResource=e.remoteResource,(e.audioLevel||0===e.audioLevel)&&(t.audioLevel=e.audioLevel),e.frameWidth&&(t.frameWidth=e.frameWidth),e.frameHeight&&(t.frameHeight=e.frameHeight),e.frameRate&&(t.frameRate=e.frameRate),(e.bitrate||0===e.bitrate)&&(t.bitrate=e.bitrate),e.jitter&&(t.jitter=e.jitter),t}))}}_getStatsData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);return null===(r=this.reportParser)||void 0===r?void 0:r.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,r;return t(this,void 0,void 0,(function*(){const t=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(t);if(!i)return[];return null===(r=this.reportParser)||void 0===r?void 0:r.getAudioLevelList(i)}))}_reportHandle(){var e,r,i;return t(this,void 0,void 0,(function*(){const t=yield this._getStatsData();if(!t)return;(t.senders.length||t.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(t));const n=this._createRCRTCStateReport(t);null===(i=null===(r=this._reportListener)||void 0===r?void 0:r.onStateReport)||void 0===i||i.call(r,n)}))}getRTCPeerConn(){return this._rtcPeerConn}destroy(){this.clear(),this.clearReTryExchangeTimer(),this._reportStatsTimer&&(clearInterval(this._reportStatsTimer),this._reportStatsTimer=null),this.registerReportListener(null),this._rtcPeerConn.close(),this.reportParser=null}clearReTryExchangeTimer(){clearInterval(this._reTryExchangeTimer),this._reTryExchangeTimer=null}}var Pt,Ot,Lt,Dt,Nt;xt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(Pt||(Pt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(Ot||(Ot={}));class At{constructor(e,t,r,i,n=Ot.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(t){this._context.getConnectionStatus()===e.ConnectionStatus.CONNECTED&&this._context.setRTCState(this._roomId,t)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=tt(),this._runtime.localStorage.setItem(e,t)),t}_getRealResourceId(e){let t=e;const r=e.indexOf("_tiny");return r>-1&&(t=e.slice(0,r)),t}_getPolarisTrackId(e){let t="";const r=e.split("_");if(e.includes("_tiny")){const e=r.pop(),i=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===exports.RCMediaType.AUDIO_ONLY?"audio":"video",i=r.pop();t=[r.join("_"),i,e].join("_")}return t}sendR3R4Data(e){const{iceCandidatePair:t,senders:r,receivers:i}=e,n=(null==t?void 0:t.bitrateSend)||-1,s=(null==t?void 0:t.bitrateRecv)||-1,o=(null==t?void 0:t.networkType)||"unknown",a=(null==t?void 0:t.rtt)||-1,c=`${(null==t?void 0:t.IP)||-1}:${null==t?void 0:t.port}`,d=(null==t||t.remoteIP,null==t||t.remotePort,(null==t?void 0:t.availableIncomingBitrate)||-1),u=(null==t?void 0:t.availableOutgoingBitrate)||-1,l=(null==t?void 0:t.totalPacketsLost)||-1,p=this._context.getCurrentId();let h=`R3\t${n}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${p}\r`,m=`R4\t${s}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${p}\r`;const _=r.map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:p,pliCount:h,rtt:m,googFirsSent:_,encoderImplementation:C}=e,R=this._getPolarisTrackId(r),f=this._getRealResourceId(r);return{trackId:R,googCodecName:C||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:p||0===p?p:-1,pliCount:h||0===h?h:-1,rtt:m||-1,googFirsSent:_,samplingRate:n,googRenderDelayMs:u,encoderImplementation:C||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(f))||void 0===t?void 0:t.isLocalMuted())?Pt.DISABLE:Pt.ENABLE}})),C=i.filter((e=>!!e.trackId)).map((e=>{var t;const{trackId:r,audioLevel:i,samplingRate:n,bitrate:s,packetsLostRate:o,frameRate:a,frameWidth:c,frameHeight:d,googRenderDelayMs:u,jitter:l,nackCount:p,pliCount:h,rtt:m,googFirsReceived:_,codecImplementationName:C}=e,R=this._getPolarisTrackId(r),f=this._getRealResourceId(r);return{trackId:R,googCodecName:C||String(-1),audioLevel:i||0===i?i:-1,bitrate:s||0===s?s:-1,packetsLostRate:o||0===o?o:-1,frameRate:a||-1,resolution:c&&d?`${c} * ${d}`:"-1",jitter:l||-1,nackCount:p||0===p?p:-1,pliCount:h||0===h?h:-1,rtt:m||-1,googFirsReceived:_,samplingRate:n,googRenderDelayMs:u,codecImplementationName:C||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(f))||void 0===t?void 0:t.isLocalMuted())?Pt.DISABLE:Pt.ENABLE}}));h+=_.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsSent}\t${e.encoderImplementation}\t${e.trackState}`)).join("\n"),e.senders.length&&this._send(h+`\r${this._userRole}`),m+=C.map((e=>`${e.trackId}\t${e.googCodecName}\t${e.audioLevel}\t${e.samplingRate}\t${e.bitrate}\t${e.packetsLostRate}\t${e.frameRate}\t${e.resolution}\t${e.googRenderDelayMs}\t${e.jitter}\t${e.nackCount}\t${e.pliCount}\t${e.rtt}\t${e.googFirsReceived}\t${e.codecImplementationName}\t${e.trackState}`)).join("\n"),e.receivers.length&&this._send(m+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.2.4\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${ot.browser}\t${ot.version}\t${this._getClientID()}\t${this._userRole}`;this._send(e)}sendR2(e,t,r){const i=`R2\t${e}\t${t}\t${this._getClientID()}\r${r.join("\t")}\r${this._userRole}`;this._send(i)}}!function(e){e.PUBLISH="publish",e.SUBSCRIBE="subscribe"}(Lt||(Lt={})),function(e){e.BEGIN="begin",e.END="end"}(Dt||(Dt={}));class Mt{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return t(this,void 0,void 0,(function*(){if("new"===this._pc.getRTCPeerConn().iceConnectionState||!this._audioLevelChangeHandler)return;const e=(yield this._pc.getAudioLevelReportData()).map((e=>{const{userId:t}=or.parseTrackId(e.trackId);return{track:this._room.getCrtUserId()===t?this._room.getLocalTrack(e.trackId):this._room.getRemoteTrack(e.trackId),audioLevel:e.audioLevel||0}})).filter((e=>e.track));this._audioLevelChangeHandler(e)}))}onAudioLevelChange(e,t){t<300||t>1e3?r.error('the valid range of onAudioLevelChange params "gap" is: > 300 && < 1000'):e?(this._audioLevelChangeHandler=e,this._timer=setInterval(this._audioLevelReport.bind(this),t)):this._audioLevelChangeHandler=null}clearAudioLevelReportTimer(){this._timer&&(clearInterval(this._timer),this._timer=null)}}exports.RCRTCLiveRole=void 0,(Nt=exports.RCRTCLiveRole||(exports.RCRTCLiveRole={}))[Nt.ANCHOR=1]="ANCHOR",Nt[Nt.AUDIENCE=2]="AUDIENCE";const wt=e=>e instanceof Oe?e.getTrackId():e.track.getTrackId();class Ut{constructor(e,t,i,n,o,c,d,u,l){this._context=e,this._runtime=t,this._roomId=i,this._roomMode=o,this._service=c,this._initOptions=d,this._ntfClearRoomItem=u,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new s,this._appListener=null,this._token=n.token,this._sessionId=n.sessionId,this._roomResources=l?{}:lt(n),this._initRemoteTracks();const p=this._context.getCurrentId(),h=this._roomResources[p]=this._roomResources[p]||[];r.debug(`room data -> ${JSON.stringify(this._roomResources)}`),h.length>0&&a((()=>this._unpublishPrev(h))),l&&this._afterChangedRole(n),this._pinger=new mt(i,this._roomMode,e,this._initOptions.pingGap),this._pinger.onFailed=this._kickoff.bind(this),this._pinger.onPingResult=this._handlePingResult.bind(this),this._pinger.start(),this._polarisReport=new At(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new xt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(xt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(Le.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(Le.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this)}_initRemoteTracks(){const e=this._context.getCurrentId();for(const t in this._roomResources){const r=this._roomResources[t];t!==e&&0!==r.length&&r.forEach((e=>{const t=ze(e),{tag:r,userId:i,mediaType:n}=Qe(t),s=n===exports.RCMediaType.AUDIO_ONLY?new Be(r,i):new Fe(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(t,i,n){r.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),e.assert("max",t,(t=>e.isNumber(t)&&t>Math.max(i||1,200)),!0),e.assert("min",i,(r=>e.isNumber(r)&&r>=1&&(!e.isNumber(t)||r<t)),!0),e.assert("start",n,(r=>e.isNumber(r)&&r>i&&r<=t)),this._pc.setBitrate(t,i,n)}_onTrackReady(e){const t=e.streams[0].id,i=e.receiver.track,n=[t,"audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._remoteTracks[n];s?(s.__innerSetMediaStreamTrack(i),this._callAppListener("onTrackReady",s)):r.warn(`cannot found remote track ${i.id}`)}_callAppListener(e,...t){var i;const n=null===(i=this._appListener)||void 0===i?void 0:i[e];if(n)try{n(...t)}catch(e){r.error(e)}}_onUserUnpublish(e){return t(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._onTrackUnpublish(e)}))}_onTrackUnpublish(e){this._callAppListener("onTrackUnpublish",e)}_unpublishPrev(i){return t(this,void 0,void 0,(function*(){const t=i.slice();i.length=0,r.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const n=yield this._context.setRTCTotalRes(this._roomId,He(pt.UNPUBLISH,t),Ge([]),pt.TOTAL_CONTENT_RESOURCE,Ge([]));n!==e.ErrorCode.SUCCESS?r.error(`unpublish prev uris failed -> code: ${n}`):r.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(t){const{targetId:i,conversationType:n}=t;if(n!==e.ConversationType.RTC_ROOM)return!1;if(i!==this._roomId)return!0;r.info(`recv inner msg -> message: ${JSON.stringify(t)} | roomid: ${this._roomId}`);const s=t.content;switch(t.messageType){case pt.KICK:this._kickoff(!0,s);break;case pt.STATE:this.msgTaskQueue.push((()=>this._stateHandle(s)));break;case pt.MODIFY:case pt.PUBLISH:case pt.UNPUBLISH:case pt.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(s,t.messageType,t.senderUserId)));break;case pt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",t.messageType,t.content);break;case pt.USER_NOTIFY:r.warn(`TODO: ${pt.USER_NOTIFY}`);break;default:this._callAppListener("onMessageReceive",t.messageType,t.content,t.senderUserId,t.messageUId)}return!0}_kickoff(e,t){let i;r.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(i=e.type)})),this._callAppListener("onKickOff",e,i)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,i,n){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void r.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:t,ignore:s}=e;if(s||!t)return;const o=[],c=[],d=[];let u;const l=this._roomResources[n]||(this._roomResources[n]=[]);switch(i){case pt.MODIFY:d.push(...t);break;case pt.PUBLISH:o.push(...t);break;case pt.UNPUBLISH:c.push(...t);break;case pt.TOTAL_CONTENT_RESOURCE:u=et(l,t),o.push(...u.publishedList),c.push(...u.unpublishedList),d.push(...u.modifiedList)}if(o.length>0){const e=l.map(ze),t=[],i=[];if(o.forEach((r=>{const n=ze(r),s=e.indexOf(n),{userId:o,tag:a,mediaType:c}=Qe(n);s>-1?l[s]=r:l.push(r);let d=this._remoteTracks[n];d?d.isSubscribed()&&t.push(d):(d=c===exports.RCMediaType.AUDIO_ONLY?new Be(a,o):new Fe(a,o),this._remoteTracks[n]=d,i.push(d)),d.__innerSetRemoteMuted(0===r.state)})),t.length){const e=t.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:i}=yield a((()=>this.__subscribe(t,!0)));i!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${i}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(i)}if(c.length>0){const e=c.map(ze);for(let t=l.length-1;t>=0;t-=1){const r=l[t];e.includes(ze(r))&&l.splice(t,1)}const t=c.map((e=>{const t=ze(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(d.length>0){const e=l.map(ze);for(let t=0;t<d.length;t+=1){const r=d[t],i=ze(r),n=e.indexOf(i);l[n].state=r.state;const s=this._remoteTracks[i];s.__innerSetRemoteMuted(0===r.state),s.isAudioTrack()?this._onAudioMuteChange(s):this._onVideoMuteChange(s)}}}))}_onTrackPublish(e){this._callAppListener("onTrackPublish",e)}_stateHandle(e){var i;return t(this,void 0,void 0,(function*(){const{users:t}=e;if(0===t.length)return;const n=[],s=[],o=[],a=[];t.forEach((e=>{0==+e.state?(r.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?o.push(e.userId):n.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(r.debug(`user left -> ${e.userId}`),e.switchRoleType?a.push(e.userId):s.push(e.userId))}));const c=[...n,...o],d=[...s,...a];if(d.length){const e=[],t=[];d.forEach((r=>{e.push(...this.getRemoteTracksByUserId(r)),t.push(r)})),e.length&&(yield this.unsubscribe(e),e.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),t.length&&t.forEach((e=>delete this._roomResources[e]))}if(null===(i=this._appListener)||void 0===i?void 0:i.onSwitchRole)return o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.ANCHOR))),a.length&&a.forEach((e=>this._callAppListener("onSwitchRole",e,exports.RCRTCLiveRole.AUDIENCE))),n.length&&this._callAppListener("onUserJoin",n),void(s.length&&this._callAppListener("onUserLeave",s));c.length&&this._callAppListener("onUserJoin",c),d.length&&this._callAppListener("onUserLeave",d)}))}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}__getPC(){return this._pc}getRemoteUserIds(){const e=this._context.getCurrentId();return Object.keys(this._roomResources).filter((t=>t!==e))}getRemoteTracks(){const e=[];return this.getRemoteUserIds().forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),e}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getSessionId(){return this._sessionId}sendMessage(i,n){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.sendMessage(e.ConversationType.RTC_ROOM,this._roomId,{messageType:i,content:n,isStatusMessage:!0});return t!==e.ErrorCode.SUCCESS?(r.error(`send message failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}setRoomAttribute(i,n,s,o=!1){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,i,n,o,e.RTCApiType.ROOM,s);return t!==e.ErrorCode.SUCCESS?(r.error(`SetRoomAttributeValue Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}deleteRoomAttributes(i,n,s=!1){return t(this,void 0,void 0,(function*(){const t=yield this._context.removeRTCData(this._roomId,i,s,e.RTCApiType.ROOM,n);return t!==e.ErrorCode.SUCCESS?(r.error(`DeleteRoomAttribute Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS}}))}getRoomAttributes(i=[],n=!1){return t(this,void 0,void 0,(function*(){const{code:t,data:s}=yield this._context.getRTCData(this._roomId,i,n,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`GetRoomAttributes Failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):{code:exports.RCRTCCode.SUCCESS,data:s}}))}_setUserAttributeValue(t,r,i){return this._context.setRTCData(this._roomId,t,r,!1,e.RTCApiType.PERSON,i)}_deleteUserAttributes(t,r){return this._context.removeRTCData(this._roomId,t,!1,e.RTCApiType.PERSON,r)}_getUserAttributes(t){return this._context.getRTCData(this._roomId,t,!1,e.RTCApiType.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var r;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._pc.removeAllLocalTrack(),this._pinger.stop(),yield this._service.exit(this._getRTCReqestHeaders()),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof Ne&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(i){return t(this,void 0,void 0,(function*(){const t=i.getTrackId(),n=this._context.getCurrentId(),s=[{resourceId:t,enabled:!i.isLocalMuted()}],o=this._roomResources[n]||[],c=[];for(let e=0;e<o.length;e+=1){const t=o[e],r=ze(t),i=s.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=s[i];t.state=e?1:0,c.push(t);break}}const d=yield a((()=>this._context.setRTCTotalRes(this._roomId,He(pt.MODIFY,c),Ge(o),pt.TOTAL_CONTENT_RESOURCE)));d!==e.ErrorCode.SUCCESS&&r.error("notice `track.enabled` change failed -> code: "+d)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof Le?e:e.track;r.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__publish(e)))}))}__publish(i){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Le||e.track instanceof Le))),!0))return r.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof Le?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(i)>10)return r.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PUBLISH_TRACK_LIMIT_EXCEEDED};r.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`),i.forEach((e=>{const{track:t,pubTiny:i}=e instanceof Le?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&i){let e;try{e=t.__innerGetMediaStreamTrack().clone();const r=i.frameRate||exports.RCFrameRate.FPS_15,n=i.resolution||exports.RCResolution.W176_H144,{width:s,height:o}=rt(n),a=st(r);e.applyConstraints({width:s,height:o,frameRate:a})}catch(i){return null==e||e.stop(),void r.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${i.message}`)}this._pc.addLocalTrack(new Ne(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const n=yield this._createExchangeParams(this._subscribedList,!1),s=yield this._exchangeHandle(n);if(s.code!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${this._roomId}, code: ${s.code}`),this._removePubFailedTracks(i),{code:s.code};const{publishList:o,sdp:a,resultCode:c,message:d,urls:u,mcuPublishList:l}=s.data;if(c!==exports.RCRTCCode.SUCCESS)return r.error(`publish failed -> roomId: ${this._roomId}, code: ${c}, msg: ${d}`),this._removePubFailedTracks(i),{code:c};const p=yield this._pc.setRemoteAnswer(a.sdp);if(p!==exports.RCRTCCode.SUCCESS)return{code:p};const h=this._roomResources[t],m=o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ze(e))},e))),{publishedList:_}=et(h,m),C=(null==l?void 0:l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],R=yield this._context.setRTCTotalRes(this._roomId,He(pt.PUBLISH,_),Ge(m),pt.TOTAL_CONTENT_RESOURCE,Ge(C));if(R!==e.ErrorCode.SUCCESS)return r.error(`send publish streams notification failed: ${R}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._roomResources[t]=m;const f=_.map((e=>ze(e)));return this._polarisReport&&this._polarisReport.sendR2(Lt.PUBLISH,Dt.BEGIN,f),i.forEach((e=>{const{track:t}=e instanceof Le?{track:e}:e;t.__innerSetPublished(!0)})),r.debug(`publish success: ${f.join(",")}`),this._roomMode===e.RTCMode.LIVE?{code:exports.RCRTCCode.SUCCESS,liveUrl:null==u?void 0:u.liveUrl}:{code:exports.RCRTCCode.SUCCESS}}))}_reTryExchange(){return t(this,void 0,void 0,(function*(){a((()=>t(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=yield this._exchangeHandle(e);if(t.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${t.code}`),{code:t.code};const{sdp:i,resultCode:n}=t.data;if(n!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==exports.RCRTCCode.SUCCESS?{code:s}:void 0}))))}))}_exchangeHandle(e){return this._service.exchange(this._getRTCReqestHeaders(),e)}_getRTCReqestHeaders(){return{"App-Key":this._context.getAppkey(),RoomId:this._roomId,Token:this._token,RoomType:this._roomMode,UserId:this._context.getCurrentId()}}_createExchangeParams(e,r){return t(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(r),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=Qe(t);if(!this._roomResources[r])return!1;const i=this._roomResources[r].filter((e=>t===`${e.msid}_${e.mediaType}`)).length;return i})).map((e=>({simulcast:e.subTiny?_t.TINY:_t.NORMAL,resolution:"",uri:this._getResourceById(e.track.getTrackId()).uri}))),switchstream:!1}}))}_getResourceState(e){var t;return(null===(t=this.getLocalTrack(e))||void 0===t?void 0:t.isLocalMuted())?0:1}unpublish(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unpublish(e)))}))}__unpublish(i){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.SUCCESS};const t=this._context.getCurrentId();if(!e.validate("tracks",i,(()=>i.every((e=>e.getUserId()===t&&e instanceof Le))),!0))return r.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`),{code:exports.RCRTCCode.PARAMS_ERROR};const s=i.map((e=>e.getTrackId())),o=s.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===o.length)return{code:exports.RCRTCCode.SUCCESS};const a=this._roomResources[t].filter((e=>!o.includes(e)));s.forEach((e=>this._pc.removeLocalTrackById(e))),null===(n=this._polarisReport)||void 0===n||n.sendR2(Lt.PUBLISH,Dt.END,s),this._pc.clearReTryExchangeTimer();const c=yield this._createExchangeParams(this._subscribedList,!1),d=yield this._exchangeHandle(c);if(d.code!==exports.RCRTCCode.SUCCESS)return r.error(`exchange failed -> code: ${d.code}`),{code:d.code};const{publishList:u,sdp:l,resultCode:p,message:h,mcuPublishList:m}=d.data;p!==exports.RCRTCCode.SUCCESS&&r.error(`unpublish streams failed -> code: ${p}, msg: ${h}`);const _=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],C=yield this._context.setRTCTotalRes(this._roomId,He(pt.UNPUBLISH,o),Ge(a),pt.TOTAL_CONTENT_RESOURCE,Ge(_));if(C!==e.ErrorCode.SUCCESS)return r.error("send unpublish notification failed:",C),{code:exports.RCRTCCode.SIGNAL_ERROR};r.debug(`unpublish success -> tracks: ${s.join(",")}`);const R=yield this._pc.setRemoteAnswer(l.sdp);if(R!==exports.RCRTCCode.SUCCESS)return{code:R};const f=u.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ze(e))},e)));return this._roomResources[t]=f,{code:exports.RCRTCCode.SUCCESS}}))}_getResourceById(e){const{userId:t}=Qe(e);return this._roomResources[t].find((t=>ze(t)===e))}_isValidResourceId(e){var t;const{userId:r}=Qe(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>ze(t)===e)))}subscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__subscribe(e,!1)))}))}__subscribe(i,n=!1){var s;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Ve||e.track instanceof Ve))),!0))return r.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`subscribe -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`);const t=this._subscribedList.map((e=>Object.assign({},e))),o=i.map((e=>e instanceof Ve?{track:e}:e));let a=!1;const c=[];return o.forEach((e=>{const r=e.track.getTrackId();c.push(r);const i=t.find((e=>e.track.getTrackId()===r));i&&i.subTiny===e.subTiny||(i?i.subTiny=e.subTiny:t.push(e),a=!0)})),a||n?(null===(s=this._polarisReport)||void 0===s||s.sendR2(Lt.SUBSCRIBE,Dt.BEGIN,c),this._updateSubListHandle(t,!0)):{code:exports.RCRTCCode.SUCCESS}}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe(e)))}))}__unsubscribe(i){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return r.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.SUCCESS};if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Ve))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${i.map(wt)}`);const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(Lt.SUBSCRIBE,Dt.END,i.map((e=>e.getTrackId()))),this._updateSubListHandle(t,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}getLocalTrack(e){return this._pc.getLocalTrack(e)}getLocalTracks(){return this._pc.getLocalTracks()}getRemoteTrack(e){return this._remoteTracks[e]||null}updateSubList(e){return t(this,void 0,void 0,(function*(){return a((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(i,n=!1){return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",i,(()=>e.isArray(i)&&i.every((e=>e instanceof Ve||e.track instanceof Ve))),!0))return r.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};r.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${n}, tracks: ${i.map(wt)}`);let t=i.map((e=>e instanceof Ve?{track:e}:Object.assign({},e)));const s={};t=t.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!s[t]&&(s[t]=!0):(r.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const o=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let e=!1;if(t.forEach((t=>{const r=o.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);o.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),o.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const a=yield this._createExchangeParams(t,!1),c=yield this._exchangeHandle(a),d=t.map((e=>e.track.getTrackId()));if(c.code!==exports.RCRTCCode.SUCCESS)return{code:c.code};const{sdp:u,resultCode:l,message:p,subscribedList:h}=c.data;if(l!==exports.RCRTCCode.SUCCESS)return r.error(`change subscribe list failed: ${l}`),{code:l};r.debug(`subscribe success: ${d.join(",")}`);const m=yield this._pc.setRemoteAnswer(u.sdp);if(m!==exports.RCRTCCode.SUCCESS)return{code:m};const _=null==h?void 0:h.map((e=>`${e.msid}_${e.mediaType}`)),C=t.filter((e=>null==_?void 0:_.includes(e.track.getTrackId()))),R=t.filter((e=>!(null==_?void 0:_.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=C.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...C),R.length?{code:exports.RCRTCCode.SUCCESS,failedList:R}:{code:exports.RCRTCCode.SUCCESS}}))}registerRoomEventListener(e){this._appListener=e}registerReportListener(e){this._pc.registerReportListener(e)}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Mt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(i){return t(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return r.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:n}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,i);if(t!==e.ErrorCode.SUCCESS)return void r.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);r.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(n)}`);const s=[],o={},a={},c={},d=lt(n),u=Object.keys(d),l=Object.keys(this._roomResources);for(let e=u.length-1;e>=0;e-=1){const t=u[e],r=l.indexOf(t);if(-1===r){s.push(t),o[t]=Ze(d[t]);continue}const i=this._roomResources[t],n=d[t],{publishedList:p,modifiedList:h,unpublishedList:m}=et(i,n,!0);o[t]=Ze(p),a[t]=Ze(m),c[t]=Ze(h),l.splice(r,1)}l.length&&l.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,d),l.length&&this._callAppListener("onUserLeave",l),s.length&&this._callAppListener("onUserJoin",s);for(const e in a){const t=a[e];if(t.length){const e=t.map((e=>this._remoteTracks[ze(e)]));yield this._onUserUnpublish(e)}}return Object.keys(o).forEach((e=>{const t=o[e];if(0===t.length)return;const r=t.map((e=>{const t=ze(e),{userId:r,tag:i,mediaType:n}=Qe(t),s=this._remoteTracks[t]=n===exports.RCMediaType.AUDIO_ONLY?new Be(i,r):new Fe(i,r);return s.__innerSetRemoteMuted(0===e.state),s}));this._onTrackPublish(r)})),Object.keys(c).forEach((e=>{c[e].forEach((e=>{const t=ze(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:n}}))}_onAudioMuteChange(e){this._callAppListener("onAudioMuteChange",e)}_onVideoMuteChange(e){this._callAppListener("onVideoMuteChange",e)}_afterChangedRole(e){}_removeRemoteTracks(){const e=Object.values(this._remoteTracks);e.length&&(e.forEach((e=>{e.isAudioTrack()&&e.__releaseMediaElement()})),this._remoteTracks={})}}var $t,jt,Vt;exports.BackgroundPictureFillMode=void 0,($t=exports.BackgroundPictureFillMode||(exports.BackgroundPictureFillMode={}))[$t.CROP=1]="CROP",$t[$t.WHOLE=2]="WHOLE",exports.MixLayoutMode=void 0,(jt=exports.MixLayoutMode||(exports.MixLayoutMode={}))[jt.CUSTOMIZE=1]="CUSTOMIZE",jt[jt.SUSPENSION=2]="SUSPENSION",jt[jt.ADAPTATION=3]="ADAPTATION",exports.MixVideoRenderMode=void 0,(Vt=exports.MixVideoRenderMode||(exports.MixVideoRenderMode={}))[Vt.CROP=1]="CROP",Vt[Vt.WHOLE=2]="WHOLE";const Bt=()=>({version:1,mode:exports.MixLayoutMode.SUSPENSION});class Ft{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=Bt()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return r.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:i,userId:n}=Qe(e);return t!==exports.RCMediaType.VIDEO_ONLY?(r.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=Xe(n,i),this)}setMixLayoutMode(e){return[exports.MixLayoutMode.CUSTOMIZE,exports.MixLayoutMode.SUSPENSION,exports.MixLayoutMode.ADAPTATION].includes(e)?(this._values.mode=e,this):(r.error(`layout mode is invalid: ${e}`),this)}_addOutputValue(e,t,r="normal"){const i=this._values.output||(this._values.output={video:{normal:{width:640,height:480}}});if("cdn"===e)return void(i.cdn=t);if("audio"===e)return void(i.audio={bitrate:t});const n=i.video;if("normal"!==r&&"tiny"!==r)if("backgroundColor"!==r)if("exparams"!==r){if("backgroundPicture"===r){const e=n.backgroundPicture||(n.backgroundPicture={fillMode:exports.BackgroundPictureFillMode.CROP,picture:[]});Object.assign(e,t)}}else n.exparams={renderMode:t};else n.backgroundColor=t;else{const e=n[r]||(n[r]={});Object.assign(e,t)}}setOutputVideoResolution(e){if(!it(e))return r.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:i}=rt(e);return this._addOutputValue("video",{width:t,height:i},"normal"),this}setOutputVideoFPS(e){if(!nt(e))return r.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=st(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(t){return!e.isNumber(t)||t<=0?r.error(`bitrate is invalid: ${t}`):this._addOutputValue("video",{bitrate:t},"normal"),this}setOutputTinyVideoResolution(e){if(!it(e))return r.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:i}=rt(e);return this._addOutputValue("video",{width:t,height:i},"tiny"),this}setOutputTinyVideoFPS(e){if(!nt(e))return r.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=st(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(t){return!e.isNumber(t)||t<=0?r.error(`bitrate is invalid: ${t}`):this._addOutputValue("video",{bitrate:t},"tiny"),this}setOutputVideoRenderMode(e){return[exports.MixVideoRenderMode.CROP,exports.MixVideoRenderMode.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):r.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(t){return e.isNumber(t)&&t>0?this._addOutputValue("audio",t):r.error(`bitrate is invalid: ${t}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):r.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(t,i,n,s,o){var a,c,d;if(!e.isHttpUrl(t))return r.error(`uri is invalid: ${t}`),this;if([i,n,s,o].some((t=>!e.isNumber(t)||t<0||t>1)))return r.error(`some attrs of (x, y, w, h) is invalid: ${i}, ${n}, ${s}, ${o}`),this;const u=(null===(d=null===(c=null===(a=this._values.output)||void 0===a?void 0:a.video)||void 0===c?void 0:c.backgroundPicture)||void 0===d?void 0:d.picture)||[];return u.push({uri:t,w:s,h:o,x:i,y:n}),this._addOutputValue("video",{picture:u},"backgroundPicture"),this}removeOutputBackgroundPicture(t){var i,n,s;if(!e.isHttpUrl(t))return r.error(`uri is invalid: ${t}`),this;let o=null===(s=null===(n=null===(i=this._values.output)||void 0===i?void 0:i.video)||void 0===n?void 0:n.backgroundPicture)||void 0===s?void 0:s.picture;return o&&(o=o.filter((e=>e.uri!==t)),this._addOutputValue("video",{pictures:o},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[exports.BackgroundPictureFillMode.CROP,exports.BackgroundPictureFillMode.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):r.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(t){var i,n;const s=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!s.test(e))))return r.error(`urls is invalid: ${t}`),this;const o=(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.cdn)||void 0===n?void 0:n.concat())||[];let a=!1;return t.forEach((e=>{o.some((t=>t.pushurl===e))||(a=!0,o.push({pushurl:e}))})),o.length>5?(r.error("publish stream url no more than 5"),this):(a&&this._addOutputValue("cdn",o),this)}removePublishStreamUrls(t){var i,n;const s=/^rtmp:\/\/.+/;if(!e.isArray(t)||0===t.length||t.some((e=>!s.test(e))))return r.error(`urls is invalid: ${t}`),this;const o=(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.cdn)||void 0===n?void 0:n.concat())||[];for(let e=o.length-1;e>=0;e-=1){const{pushurl:r}=o[e],i=t.indexOf(r);i>=0&&(t.splice(i,1),o.splice(e,1))}return this._addOutputValue("cdn",o),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(t,i,n,s,o){if(!this._isValidTrackId(t))return r.error(`trackId is invalid: ${t}`),this;if(!e.isNumber(i)||!e.isNumber(n))return r.error(`some attrs of (x, y) is invalid: ${i}, ${n}`),this;if([s,o].some((t=>!e.isNumber(t)||t<0)))return r.error(`some attrs of (width, height) is invalid: ${s}, ${o}`),this;const{userId:a,tag:c,mediaType:d}=Qe(t);if(d!==exports.RCMediaType.VIDEO_ONLY)return r.error(`kind of resource is not 'video': ${t}`),this;const u=Xe(a,c);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:a,stream_id:u,x:i,y:n,width:s,height:o}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return r.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:i,mediaType:n}=Qe(e);if(n!==exports.RCMediaType.VIDEO_ONLY)return r.error(`kind of resource is not 'video': ${e}`),this;const s=Xe(t,i),o=this._values.input||(this._values.input={video:[]});return o.video=o.video.filter((e=>e.stream_id===s)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,r,i,n;return t(this,void 0,void 0,(function*(){const t=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._onFlush(t);return s===exports.RCRTCCode.SUCCESS&&((null===(r=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===r?void 0:r.width)||(null===(n=null===(i=this._values.output)||void 0===i?void 0:i.video.normal)||void 0===n?void 0:n.fps))&&this._sendCDNInfoSignal(),this._values=Bt(),{code:s}}))}}var Ht,Gt,Jt;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(Ht||(Ht={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(Gt||(Gt={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(Jt||(Jt={}));class Wt extends Ut{constructor(t,r,i,n,s,o,a,c,d=!1){var u;super(t,r,i,n,e.RTCMode.LIVE,s,o,a,d),this._livingType=c,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new Ft(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this));const l=null===(u=n.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===u?void 0:u.value;l&&(this._CDNUris=JSON.parse(l)[0])}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._mcuConfigBuilder}_onMCUConfigFlush(e){return t(this,void 0,void 0,(function*(){const t={"App-Key":this._context.getAppkey(),Token:this._token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},{code:i,res:n}=yield this._service.setMcuConfig(t,e);return i!==exports.RCRTCCode.SUCCESS?(r.error(`set MCU config failed: ${i}`),{code:i}):(r.info("set MCU config success"),n.pull_url&&(this._CDNUris=JSON.parse(n.pull_url)),{code:i,res:n})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var r,i;return t(this,void 0,void 0,(function*(){const t=yield e.__onReconnected.call(this,this._livingType);if(!t||!t.data)return;const n=t.data.roomInfo,s=null===(r=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===r?void 0:r.value;if(!s)return;const o=JSON.parse(s);(null===(i=this._CDNUris)||void 0===i?void 0:i.enableInnerCDN)!==o.enableInnerCDN&&this._callAppListener("onCDNEnableChange",o.enableInnerCDN),this._CDNUris=o}))}enableInnerCDN(i){return t(this,void 0,void 0,(function*(){if(!e.isBoolean(i))return r.error("`enable` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};this._CDNEnable=i;const n={version:2,output:{inCDNModel:i?Ht.OPEN:Ht.STOP}},{code:s}=yield this._onMCUConfigFlush(n);if(s!==exports.RCRTCCode.SUCCESS)return r.error(`enableInnerCDN failed -> code: ${s}`),{code:exports.RCRTCCode.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==Gt.SPREAD)return r.info("enableInnerCDN succeed"),{code:exports.RCRTCCode.SUCCESS};const{code:o}=yield a((()=>t(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return o===exports.RCRTCCode.SUCCESS?(r.info("enableInnerCDN succeed"),{code:exports.RCRTCCode.SUCCESS}):(r.error(`enableInnerCDN failed -> code: ${o}`),{code:o})}))}_sendCDNInfoSignal(){return t(this,void 0,void 0,(function*(){this._CDNUris=Object.assign({},this._CDNUris,{enableInnerCDN:this._CDNEnable});return(yield Promise.all([this._spreadCDNInfo(this._CDNUris),this._setRoomCDNInfo(this._CDNUris)])).every((e=>e.code===exports.RCRTCCode.SUCCESS))?{code:exports.RCRTCCode.SUCCESS}:{code:exports.RCRTCCode.SIGNAL_ERROR}}))}_spreadCDNInfo(i){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,pt.TOTAL_CONTENT_RESOURCE,JSON.stringify([i]));return t!==e.ErrorCode.SUCCESS?(r.error(`spreadCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("spreadCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}_setRoomCDNInfo(i){return t(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([i]),!0,e.RTCApiType.ROOM);return t!==e.ErrorCode.SUCCESS?(r.error(`setRoomCDNInfo failed -> code: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR}):(r.info("setRoomCDNInfo succeed"),{code:exports.RCRTCCode.SUCCESS})}))}_resourceHandle(e,r,i){const n=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var s;return t(this,void 0,void 0,(function*(){n._resourceHandle.call(this,e,r,i),e.cdn_uris&&((null===(s=this._CDNUris)||void 0===s?void 0:s.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var r,i,n;return t(this,void 0,void 0,(function*(){const t=yield this._service.exchange(this._getRTCReqestHeaders(),e),s=null===(i=null===(r=t.data)||void 0===r?void 0:r.urls)||void 0===i?void 0:i.pull_url;return t.code===exports.RCRTCCode.SUCCESS&&s?(this._CDNUris=JSON.parse(s),(null===(n=this._CDNUris)||void 0===n?void 0:n.broadcast)===Gt.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),t):t}))}_afterChangedRole(e){const t=lt(e),r=this._context.getCurrentId(),i=Object.keys(t);setTimeout((()=>{var n,s,o;const a=i.filter((e=>e!==r));a.length>0&&this._callAppListener("onUserJoin",a);for(const e in t)e!==r&&this._resourceHandle({uris:t[e]},pt.TOTAL_CONTENT_RESOURCE,e);(null===(n=e.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===n?void 0:n.value)&&(null===(s=this._CDNUris)||void 0===s?void 0:s.push_mode)===Jt.MANUAL&&this._callAppListener("onCDNEnableChange",null===(o=this._CDNUris)||void 0===o?void 0:o.enableInnerCDN)}))}__getCDNEnable(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.enableInnerCDN}__getCDNPushMode(){var e;return null===(e=this._CDNUris)||void 0===e?void 0:e.push_mode}}class Yt extends Ut{constructor(t,r,i,n,s,o,a){super(t,r,i,n,e.RTCMode.RTC,s,o,a,!1)}}const Kt=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${ot.browser}|${ot.version}`,ClientVersion:"5.2.4","Client-Session-Id":"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),"Request-Id":Date.now().toString()});class qt{constructor(e,t,r,i=5e3){this._runtime=e,this._context=t,this._msUrl=r,this._timeout=i,this._msInNavi=[],this._failedMs=[],this._rtcFinger=void 0,this._clusterId="",this._configUrl=""}getNaviMS(){return this._msUrl?[this._msUrl]:this._clusterId?[`https://${this._clusterId}`]:(0===this._msInNavi.length&&(0===this._failedMs.length?this._msInNavi.push(...(e=>{var t;if(!e)return[];let i;try{i=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return r.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===i.strategy)return[];const n=null===(t=i.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!n||0===n.length)return[];const s=n[0],o=[];return s.mediaServer&&o.push(s.mediaServer.replace(/^(https?:\/\/)?/,"https://")),s.backupMediaServer&&s.backupMediaServer.forEach((e=>{o.push(e.replace(/^(https?:\/\/)?/,"https://"))})),o})(this._context.getNaviInfo())):(this._msInNavi.push(...this._failedMs),this._failedMs.length=0)),this._msInNavi.map((e=>e.trim())))}_request(i,n,s){return t(this,void 0,void 0,(function*(){const t=this.getNaviMS();if(0===t.length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(s.rtcFinger=this._rtcFinger);for(let o=0;o<t.length;o+=1){const a=`${t[o]}${i}`,c=Kt();r.debug(`request -> Request-Id: ${c["Request-Id"]}, url: ${a}`);const{status:d,data:u}=yield this._runtime.httpReq({url:a,body:JSON.stringify(s),headers:Object.assign(Object.assign({},c),n),method:e.HttpMethod.POST,timeout:this._timeout});if(200===d){const e=JSON.parse(u);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),r.debug(`request success -> Request-Id: ${c["Request-Id"]}`),{code:exports.RCRTCCode.SUCCESS,data:e}}r.warn(`request failed -> Request-Id: ${c["Request-Id"]}, status: ${d}, url: ${a}`),this._failedMs.push(...this._msInNavi.splice(o,1))}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}exchange(e,r){var i;return t(this,void 0,void 0,(function*(){const t=yield this._request("/exchange",e,r);if(t.code===exports.RCRTCCode.SUCCESS&&(null===(i=t.data)||void 0===i?void 0:i.resultCode)===exports.RCRTCCode.SUCCESS){const e=t.data.urls;e&&(this._configUrl=e.configUrl)}return t}))}exit(e){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/exit",e,{});return t}))}broadcastSubscribe(e,t){return this._request("/broadcast/subscribe",e,t)}broadcastExit(e){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(i,n){return t(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:exports.RCRTCCode.MCU_SERVER_NOT_FOUND};const t=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,s=Kt();r.debug(`request -> Request-Id: ${s["Request-Id"]}, url: ${t}`);const{status:o,data:a}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},s),i),body:JSON.stringify(n),method:e.HttpMethod.POST});if(200===o){r.debug(`request success -> Request-Id: ${s["Request-Id"]}`);const e=JSON.parse(a);return{code:e.resultCode,res:e}}return{code:exports.RCRTCCode.REQUEST_FAILED}}))}getCDNResourceInfo(i,n){return t(this,void 0,void 0,(function*(){const t=Kt(),{status:s,data:o}=yield this._runtime.httpReq({url:n,headers:Object.assign(Object.assign({},t),i),method:e.HttpMethod.GET});if(200===s){const e=JSON.parse(o);return{code:e.resultCode,res:e}}return r.warn(`request failed -> Request-Id: ${t["Request-Id"]}, status: ${s}, url: ${n}`),{code:exports.RCRTCCode.REQUEST_FAILED}}))}}var zt,Qt,Xt;exports.RCLivingType=void 0,(zt=exports.RCLivingType||(exports.RCLivingType={}))[zt.VIDEO=0]="VIDEO",zt[zt.AUDIO=1]="AUDIO";class Zt{constructor(e,t,r){this._context=e,this._rtcToken="",this._liveUrl="",this._subTracks=[],this._livingType=null,this._mediaType=null,this._subTiny=!1,this._fromRetry=!1,this._appListener=null,this._service=new qt(t,e,r.mediaServer)}_getReqHeaders(i){return t(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),n=t;if(!this._rtcToken){const{code:t,data:s}=yield this._context.getRTCToken(n,e.RTCMode.LIVE,i);if(t!==e.ErrorCode.SUCCESS)return r.error(`getRTCToken failed: ${t}`),{code:exports.RCRTCCode.SIGNAL_ERROR};this._rtcToken=s.rtcToken}return{code:exports.RCRTCCode.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:n,RoomType:e.RTCMode.LIVE,Token:this._rtcToken}}}))}_clearSubscribeInfo(){var e;this._liveUrl="",this._livingType=null,this._mediaType=null,this._subTiny=!1,this._subTracks.length=0,null===(e=this._pc)||void 0===e||e.destroy(),this._pc=null}_reTryExchange(){var e;return t(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===exports.RCRTCCode.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,r,i,n=!1){return t(this,void 0,void 0,(function*(){return a((()=>this.__subscribe(e,r,i,n)))}))}__subscribe(i,n,s,o=!1){var a;return t(this,void 0,void 0,(function*(){const t=[];if(ut(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR,tracks:t};if(!this._fromRetry&&(null===(a=this._pc)||void 0===a||a.clearReTryExchangeTimer()),this._fromRetry=!1,!e.isString(i))return r.error(`liveUrl is invalid: ${i}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCLivingType.AUDIO,exports.RCLivingType.VIDEO].includes(n))return r.error(`livingType is invalid: ${n}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(![exports.RCMediaType.AUDIO_ONLY,exports.RCMediaType.VIDEO_ONLY,exports.RCMediaType.AUDIO_VIDEO].includes(s))return r.error(`mediaType is invalid: ${s}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};if(this._liveUrl&&this._liveUrl!==i)return{code:exports.RCRTCCode.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:t};this._pc||(this._pc=new xt(this._reTryExchange.bind(this)),this._pc.on(xt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=i;const{code:c,headers:d}=yield this._getReqHeaders(n);if(c!==exports.RCRTCCode.SUCCESS)return{code:c,tracks:t};const u=`rc_mcu_${Date.now()}`,l="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new Be(l,u),new Fe(l,u)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const p={sdp:yield this._pc.createOffer(!0),liveUrl:i,mediaType:s,simulcast:o?_t.TINY:_t.NORMAL,switchstream:!1},h=yield this._service.broadcastSubscribe(d,p);if(h.code!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed: ${h.code}`),{code:h.code,tracks:t};const m=h.data;if(m.resultCode!==exports.RCRTCCode.SUCCESS)return r.error(`andience subscribe failed! code: ${m.resultCode}; message: ${m.message}`),{code:m.resultCode,tracks:t};r.debug(`andience subscribe success: ${i}`),this._livingType=n,this._mediaType=s,this._subTiny=o;const{sdp:_,subscribedList:C}=m,R=[];return C.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];R.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(_.sdp),{code:exports.RCRTCCode.SUCCESS,tracks:R}}))}unsubscribe(){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return t(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:exports.RCRTCCode.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:i}=yield this._service.broadcastExit(t);return i!==exports.RCRTCCode.SUCCESS?r.error(`broadcast unsubscribe failed: ${i}`):r.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:i}}))}registerReportListener(e){var t;this._reportListener=e,null===(t=this._pc)||void 0===t||t.registerReportListener(e)}registerTrackEventListener(e){this._appListener=e}_onTrackReady(e){var t,i;const n=e.receiver.track,s="audio"===n.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY,o=this._subTracks[s];o.__innerSetMediaStreamTrack(n);try{null===(i=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===i||i.call(t,o)}catch(e){r.error(e)}}}exports.RCInnerCDNPullKind=void 0,(Qt=exports.RCInnerCDNPullKind||(exports.RCInnerCDNPullKind={})).RTMP="rtmp",Qt.FLV="flv",Qt.HLS="hls",exports.RCInnerCDNPullIsHttps=void 0,(Xt=exports.RCInnerCDNPullIsHttps||(exports.RCInnerCDNPullIsHttps={}))[Xt.NOT_HTTPS=0]="NOT_HTTPS",Xt[Xt.HTTPS=1]="HTTPS";const er=Object.assign(Object.assign({},rt(exports.RCResolution.W176_H144)),{frameRate:st(exports.RCFrameRate.FPS_15)});class tr{constructor(e,t,i,n,s,o){this._context=e,this._runtime=t,this._initOptions=i,this._roomId=n,this._joinResData=s,this._livingType=o,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._setInitData(),this._service=new qt(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new At(this._context,this._runtime,this._roomId,this,Ot.Audience),this._polarisReport.sendR1(),this._pc=new xt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(xt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,i=e.receiver.track,n=[t,"audio"===i.kind?exports.RCMediaType.AUDIO_ONLY:exports.RCMediaType.VIDEO_ONLY].join("_"),s=this._remoteTracks[n];s?(s.__innerSetMediaStreamTrack(i),this._callAppListener("onTrackReady",s)):r.warn("cannot found RCRemoteTrack:",i.id)})),this._context.onrtcdatachange=this.singalDataChange.bind(this)}_setInitData(){const{sessionId:e,remoteUserIds:t,remoteRTCUris:r,remoteMUCUris:i,remoteTracks:n,CDNUris:s}=((e,t)=>{const r=t.filter((e=>"RC_RTC_SESSIONID"===e.key))[0].value,i=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],n=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),s=n.length?JSON.parse(n[0].mcu_uris||"[]"):[],o=[];s.forEach((t=>{const{mediaType:r,tag:i}=t,n=r===exports.RCMediaType.AUDIO_ONLY?new Be(i,"",e):new Fe(i,"",e);o.push(n)}));const a=[],c=[];n.forEach((e=>{const t=JSON.parse(e.uris||"[]");a.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,n=i.split("_")[0],s=t===exports.RCMediaType.AUDIO_ONLY?new Be(r,n):new Fe(r,n);c.push(s)}))}));const d=t.filter((e=>"RC_CDN"===e.key)).map((e=>{const t=JSON.parse(e.value||"[]");return JSON.parse(t.cdn_uris)[0]}))[0];return{sessionId:r,remoteUserIds:i||[],remoteRTCUris:a,remoteMUCUris:s,remoteRTCTracks:c,remoteMCUTracks:o,remoteTracks:[...c,...o],CDNUris:d||{}}})(this._roomId,this._joinResData.kvEntries);this._sessionId=e,this._roomAnchorList=t,n.forEach((e=>{this._remoteTracks[e.getTrackId()]=e})),this._CDNUris=s,r.forEach((e=>{const t=e.msid.split("_")[0];this._roomAnchorRes[t]?this._roomAnchorRes[t].push(e):this._roomAnchorRes[t]=[e]})),i.forEach((e=>{const{mediaType:t,tag:r}=e,i=[this._roomId,r,t].join("_");this._roomRes[i]=e})),r.forEach((e=>{const t=ze(e);this._roomRes[t]=e}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinLivingRoomAsAudience` to catch another instance.";return r.warn(e),exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var i;if(t!==this._roomId)return void r.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);r.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const n=[],s=null===(i=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===i?void 0:i.value;s&&this._diffCDNUris(JSON.parse(JSON.parse(s).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:i,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),i=JSON.parse(e.uris||"[]");return n.push(...t),void this._diffAnchorResource(i,s)}if("RC_ANCHOR_LIST"===t){const e=JSON.parse(r||"[]"),{joinUserIds:t,leftUserIds:i}=this._diffAnchorList(e);t.length>0&&this._handleNewJoinedAnchor(t),i.length>0&&this._handleLeftedAnchor(i)}})),this._diffRoomResource(n)}_diffAnchorList(e){const t=e.filter((e=>this._roomAnchorList.indexOf(e)<0));return{leftUserIds:this._roomAnchorList.filter((t=>e.indexOf(t)<0)),joinUserIds:t}}_handleNewJoinedAnchor(e){this._roomAnchorList.push(...e),this._callAppListener("onAnchorJoin",e)}_handleLeftedAnchor(e){return t(this,void 0,void 0,(function*(){this._roomAnchorList=this._roomAnchorList.filter((t=>!(e.indexOf(t)>-1)));const t=[];e.forEach((e=>{t.push(...this.getRemoteTracksByUserId(e)),delete this._roomAnchorRes[e]})),t.length&&(yield this.unsubscribe(t),t.forEach((e=>delete this._remoteTracks[e.getTrackId()]))),this._callAppListener("onAnchorLeave",e)}))}_diffRoomResource(e){return t(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=ze(e),{userId:n,tag:s,mediaType:o}=Qe(r),a=[this._roomId,s,o].join("_");if(!this._remoteTracks[a]){const r=o===exports.RCMediaType.AUDIO_ONLY?new Be(s,"",this._roomId):new Fe(s,"",this._roomId);t.push(r),this._remoteTracks[a]=r,this._roomRes[r.getTrackId()]=e}i.push(a)})),Object.keys(this._remoteTracks).forEach((e=>{i.indexOf(e)<0&&this._remoteTracks[e].isMCUTrack()&&r.push(this._remoteTracks[e])})),t.length>0&&this._callAppListener("onTrackPublish",t),r.length>0&&this._onUserUnpublish(r,"onTrackUnpublish")}))}_diffAnchorResource(e,i){return t(this,void 0,void 0,(function*(){const t=this._roomAnchorRes[i]||(this._roomAnchorRes[i]=[]),{publishedList:n,unpublishedList:s,modifiedList:o}=et(t,e);if(n.length){const e=t.map(ze),i=[],s=[];if(n.forEach((r=>{const n=ze(r),o=e.indexOf(n),{userId:a,tag:c,mediaType:d}=Qe(n);o>-1?t[o]=r:t.push(r);let u=this._remoteTracks[n];this._roomRes[n]=r,u?u.isSubscribed()&&i.push(u):(u=d===exports.RCMediaType.AUDIO_ONLY?new Be(c,a):new Fe(c,a),this._remoteTracks[n]=u,s.push(u)),u.__innerSetRemoteMuted(0===r.state)})),i.length){const e=i.map((e=>e.getTrackId()));r.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:t}=yield a((()=>this._subscribeHandle(i,!0)));t!==exports.RCRTCCode.SUCCESS&&r.error(`resub tracks failed -> code: ${t}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",s)}if(s.length){const e=s.map(ze);for(let r=t.length-1;r>=0;r-=1){const i=t[r];e.includes(ze(i))&&t.splice(r,1)}const r=s.map((e=>{const t=ze(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(r,"onAnchorTrackUnpublish")}if(o.length){const e=t.map(ze);for(let r=0;r<o.length;r++){const i=o[r],n=ze(i),s=e.indexOf(n);t[s].state=i.state;const a=this._remoteTracks[n];a.__innerSetRemoteMuted(0===i.state),a.isAudioTrack()?this._callAppListener("onAudioMuteChange",a):this._callAppListener("onVideoMuteChange",a)}}}))}_onUserUnpublish(e,r){return t(this,void 0,void 0,(function*(){yield this.unsubscribe(e),e.forEach((e=>{this._subscribedList=this._subscribedList.filter((t=>t.track.getTrackId()!==e.getTrackId())),delete this._roomRes[e.getTrackId()],e.__innerDestroy(),delete this._remoteTracks[e.getTrackId()]})),this._callAppListener(r,e)}))}_callAppListener(e,...t){var i;const n=null===(i=this._appListener)||void 0===i?void 0:i[e];if(n)try{n(...t)}catch(e){r.error(e)}}_reTryExchange(){return t(this,void 0,void 0,(function*(){a((()=>t(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),i=yield this._exchangeHandle(t);if(i.code!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${i.code}`),{code:i.code};const{sdp:n,resultCode:s}=i.data;if(s!==exports.RCRTCCode.SUCCESS)return r.error(`reTryExchange failed: ${s}`),{code:s};this._pc.clearReTryExchangeTimer();const o=this._subscribedList.filter((e=>e.track.isMCUTrack()));if(o.length>0){const t=o[0].track.getTrackId(),r=null===(e=this._roomRes[t])||void 0===e?void 0:e.msid,i=[this._roomId,"RongCloudRTC"].join("_");n.sdp=n.sdp.replace(new RegExp(r,"g"),i)}const a=yield this._pc.setRemoteAnswer(n.sdp);return a!==exports.RCRTCCode.SUCCESS?{code:a}:void 0}))))}))}_createSubscribeParams(e,r,i){return t(this,void 0,void 0,(function*(){const t=yield this._pc.createOffer(i),n={resolutionInfo:[]},s={min:0,max:0};Object.keys(r).forEach((e=>{const{mediaStream:i,tinyStream:o}=r[e];[i,o].forEach(((r,i)=>{var o;const a=1===i?[e,"tiny"].join("_"):e;t.sdp=null===(o=t.sdp)||void 0===o?void 0:o.replace(new RegExp(r.id,"g"),a);const c=r.getVideoTracks()[0];if(!c)return;const d=0===i,{width:u,height:l,frameRate:p}=d?Ke(c):er;n.resolutionInfo.push({trackId:c.id,simulcast:d?_t.NORMAL:_t.TINY,resolution:`${u}x${l}`});const h=ke(u,l),m=xe(p);s.min+=h.minBitrate*m,s.max+=h.maxBitrate*m}))}));return{reqBody:{sdp:t,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?_t.TINY:_t.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:t}}))}_subscribeHandle(r,i=!1){var n;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("tracks",r,(()=>e.isArray(r)&&r.length>0&&r.every((e=>e instanceof Ve||e.track instanceof Ve))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))),s=r.map((e=>e instanceof Ve?{track:e}:e));let o=!1;const a=[];return s.forEach((e=>{const r=e.track.getTrackId();a.push(r);const i=t.find((e=>e.track.getTrackId()===r));i&&i.subTiny===e.subTiny||(i?i.subTiny=e.subTiny:t.push(e),o=!0)})),o||i?(null===(n=this._polarisReport)||void 0===n||n.sendR2(Lt.SUBSCRIBE,Dt.BEGIN,a),this._updateSubListHandle(t,!0)):{code:exports.RCRTCCode.SUCCESS}}))}_getReqHeaders(){const t=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:t,Token:this._joinResData.token,RoomType:e.RTCMode.LIVE,UserId:t,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(i,n=!1){var s;return t(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:exports.RCRTCCode.ROOM_HAS_BEEN_DESTROYED};if(!e.validate("resources",i,(()=>e.isArray(i)&&i.every((e=>e instanceof Ve||e.track instanceof Ve))),!0))return{code:exports.RCRTCCode.PARAMS_ERROR};let t=i.map((e=>e instanceof Ve?{track:e}:Object.assign({},e)));const o={};t=t.filter((e=>{const t=e.track.getTrackId();return!o[t]&&(o[t]=!0)})).map((e=>Object.assign({},e)));const a=this._subscribedList.map((e=>Object.assign({},e)));if(!n){let e=!1;if(t.forEach((t=>{const r=a.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);a.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),a.length&&(e=!0),!e)return{code:exports.RCRTCCode.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(t.map((e=>e.track)));const{reqBody:c}=yield this._createSubscribeParams(t,{},!1),d=yield this._exchangeHandle(c);if(a.length){const e=[];a.forEach((t=>{e.push(t.track.getTrackId())})),null===(s=this._pc.reportParser)||void 0===s||s.clearLatestPacketsRecv(e)}if(d.code!==exports.RCRTCCode.SUCCESS)return{code:d.code};const{sdp:u,resultCode:l,message:p,subscribedList:h}=d.data;if(l!==exports.RCRTCCode.SUCCESS)return r.error("change subscribe list failed:",p,l),{code:l};t.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=Qe(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const m=yield this._pc.setRemoteAnswer(u.sdp);if(m!==exports.RCRTCCode.SUCCESS)return{code:m};const _=null==h?void 0:h.map((e=>`${e.msid}_${e.mediaType}`)),C=t.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return _.includes(r)}return null==_?void 0:_.includes(e.track.getTrackId())})),R=null==C?void 0:C.map((e=>`${e.track.getTrackId()}`)),f=t.filter((e=>!(null==R?void 0:R.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=C.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...C),f.length?{code:exports.RCRTCCode.SUCCESS,failedList:f}:{code:exports.RCRTCCode.SUCCESS}}))}_diffCDNUris(e){return t(this,void 0,void 0,(function*(){if(this._CDNUris.url&&!e.url)return this._callAppListener("onCDNInfoDisable"),void(this._CDNUris=e);(!this._CDNUris||!this._CDNUris.url&&e.url)&&this._callAppListener("onCDNInfoEnable",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`});const t=this._CDNUris.w&&e.w&&this._CDNUris.w!==e.w,r=this._CDNUris.h&&e.h&&this._CDNUris.h!==e.h,i=this._CDNUris.fps&&e.fps&&this._CDNUris.fps!==e.fps;(t||r||i)&&this._callAppListener("onCDNInfoChange",{resolution:`W${e.w}_H${e.h}`,fps:`FPS_${e.fps}`}),this._CDNUris=e}))}_getCDNPlayUrl(e){return t(this,void 0,void 0,(function*(){const{w:t,h:i,fps:n}=e,s=this._initOptions.pullInnerCDNProtocol||exports.RCInnerCDNPullKind.FLV,o=this._initOptions.pullInnerCDNUseHttps===exports.RCInnerCDNPullIsHttps.NOT_HTTPS?exports.RCInnerCDNPullIsHttps.NOT_HTTPS:exports.RCInnerCDNPullIsHttps.HTTPS;if(!this._CDNUris.url)return r.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY}`),{code:exports.RCRTCCode.CDN_RESOURCE_IS_EMPTY};const a={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},c=[];t&&c.push(`w=${t}`),i&&c.push(`h=${i}`),n&&c.push(`fps=${n}`),c.push(`kind=${s}`),c.push(`is_https=${o}`);const d=c.join("&");let u=`${this._CDNUris.url}?`;d&&(u+=d);const{code:l,res:p}=yield this._service.getCDNResourceInfo(a,u);return l!==exports.RCRTCCode.SUCCESS?(r.error(`getCDNPlayUrl failed: ${l}`),{code:l}):(r.info(`getCDNPlayUrl success: ${null==p?void 0:p.data.pull_url}`),{code:l,CDNPlayUrl:null==p?void 0:p.data.pull_url})}))}getCDNPlayUrl(e,i){return t(this,void 0,void 0,(function*(){if(e&&!it(e))return r.error("`resolution` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};if(i&&!nt(i))return r.error("`fps` is invalid"),{code:exports.RCRTCCode.PARAMS_ERROR};const{width:t,height:n}=e?rt(e):{width:null,height:null},s=i?st(i):null,o={};return t&&(o.w=t),n&&(o.h=n),s&&(o.fps=s),this._getCDNPlayUrl(o)}))}subscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(i){var n;return t(this,void 0,void 0,(function*(){if(!e.validate("tracks",i,(()=>e.isArray(i)&&i.length>0&&i.every((e=>e instanceof Ve))),!0))return r.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:exports.RCRTCCode.PARAMS_ERROR};const t=this._subscribedList.map((e=>Object.assign({},e))).filter((e=>!i.includes(e.track)));return null===(n=this._polarisReport)||void 0===n||n.sendR2(Lt.SUBSCRIBE,Dt.END,i.map((e=>e.getTrackId()))),this._updateSubListHandle(t,!1)}))}unsubscribe(e){return t(this,void 0,void 0,(function*(){return a((()=>this.__unsubscribe(e)))}))}__destroy(e){var r;return t(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),e&&(yield this._context.quitLivingRoomAsAudience(this._roomId)),yield this._service.broadcastExit(this._getReqHeaders()),this._pc.destroy(),this._polarisReport=null,this._context.onrtcdatachange=()=>{})}))}getRemoteTrack(e){return this._remoteTracks[e]}__getPC(){return this._pc}getLocalTrack(e){return{}}__onReconnected(){return t(this,void 0,void 0,(function*(){const{code:t}=yield this._context.joinLivingRoomAsAudience(this._roomId,e.RTCMode.LIVE);t!==e.ErrorCode.SUCCESS&&r.error("join living room error when on reconnected")}))}registerRoomEventListener(e){this._appListener=e}onAudioLevelChange(e,t){var r;null===(r=this._audioLevelReport)||void 0===r||r.clearAudioLevelReportTimer(),this._audioLevelReport=new Mt(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}registerReportListener(e){var t;null===(t=this._pc)||void 0===t||t.registerReportListener(e)}getRoomId(){return this._roomId}getCrtUserId(){return this._context.getCurrentId()}getSessionId(){return this._sessionId}getRemoteUserIds(){return this._roomAnchorList}getRemoteTracksByUserId(e){const t=[];for(const r in this._remoteTracks){const i=this._remoteTracks[r];i.getUserId()===e&&t.push(i)}return t}getRemoteTracks(){const e=[],t=[];for(const e in this._remoteTracks){if(2===t.length)break;const r=this._remoteTracks[e];r.isMCUTrack()&&t.push(r)}return this._roomAnchorList.forEach((t=>{e.push(...this.getRemoteTracksByUserId(t))})),[...t,...e]}getRemoteRTCTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()||e.push(r)}return e}getRemoteMCUTracks(){const e=[];for(const t in this._remoteTracks){const r=this._remoteTracks[t];r.isMCUTrack()&&e.push(r)}return e}getCDNInfo(){return this._CDNUris.w?{resolution:`W${this._CDNUris.w}_H${this._CDNUris.h}`,fps:`FPS_${this._CDNUris.fps}`,CDNEnable:this._CDNUris.enableInnerCDN}:{CDNEnable:!1}}}const rr=(e,t)=>{const r=[];return r[0]=(null==t?void 0:t.withoutAudio)?void 0:e.getAudioTracks()[0],r[1]=(null==t?void 0:t.withoutVideo)?void 0:e.getVideoTracks()[0],r};class ir{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,It.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new qt(this._runtime,this._context,this._options.mediaServer,this._options.timeout),this._context.onconnectionstatechange=this._onIMStatusChange.bind(this),this._context.ondisconnect=this._onIMDisconnect.bind(this),this._context.ondestroy=this._onIMUninit.bind(this),this._context.onmessage=this._handleMessage.bind(this)}_handleMessage(t){var r;return t.conversationType===e.ConversationType.RTC_ROOM&&(null===(r=this._crtRoom)||void 0===r||r.__parseInnerMessage(t),!0)}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t){return a((()=>this._joinRTCRoom(e,t)))}_joinRTCRoom(i,s){return t(this,void 0,void 0,(function*(){if(ut(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.debug(`joinRoom -> roomId: ${i}; joinType: ${s||e.RTCJoinType.KICK}`);const{code:t,data:o}=yield this._context.joinRTCRoom(i,e.RTCMode.RTC,void 0,s);if(t!==e.ErrorCode.SUCCESS){r.error(`joinRoom failed -> code: ${t}`);return{code:t===n.JOIN_REFUSED?exports.RCRTCCode.SIGNAL_JOIN_RTC_ROOM_REFUSED:t}}r.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(o)}`);const a=new Yt(this._context,this._runtime,i,o,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=a,{room:a,code:exports.RCRTCCode.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}joinLivingRoom(e,t){return a((()=>this._joinLivingRoom(e,t)))}_joinLivingRoom(i,n){return t(this,void 0,void 0,(function*(){if(ut(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==e.ConnectionStatus.CONNECTED)return{code:exports.RCRTCCode.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};r.debug(`joinRoom, roomId: ${i}`);const{code:t,data:s}=yield this._context.joinRTCRoom(i,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error(`joinRoom failed -> code: ${t}`),{code:t};r.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${i}, data: ${JSON.stringify(s)}`);const o=new Wt(this._context,this._runtime,i,s,this._service,this._options,this._releaseCrtRoomObj.bind(this),n,!1);this._crtRoom=o;const a={room:o,code:exports.RCRTCCode.SUCCESS,userIds:o.getRemoteUserIds(),tracks:o.getRemoteTracks()};return o.__getCDNPushMode()===Jt.MANUAL&&Object.assign(a,{CDNEnable:o.__getCDNEnable()}),a}))}getAudienceClient(){return this._audience||(this._audience=new Zt(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(t){r.debug(`signal server connection state change: ${t}`),t===e.ConnectionStatus.CONNECTED&&this._crtRoom&&this._crtRoom.__onReconnected()}_onIMDisconnect(){r.debug("TODO -> on IM disconnect")}_onIMUninit(){r.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return a((()=>this._leaveRoom(e)))}_leaveRoom(e){return t(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),r.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,i="getUserMedia"){return t(this,void 0,void 0,(function*(){try{const t=yield navigator.mediaDevices[i](e);return{code:exports.RCRTCCode.SUCCESS,stream:t}}catch(e){if("Permission denied"===e.message)return{code:exports.RCRTCCode.PERMISSION_DENIED};r.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===i?exports.RCRTCCode.GET_USER_MEDIA_FAILED:exports.RCRTCCode.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",r){return t(this,void 0,void 0,(function*(){if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==r?void 0:r.micphoneId,sampleRate:null==r?void 0:r.sampleRate}});if(n!==exports.RCRTCCode.SUCCESS)return{code:n};const s=i.getAudioTracks()[0];return{code:n,track:new Ue(e,t,s)}}))}createCameraVideoTrack(e="RongCloudRTC",r){return t(this,void 0,void 0,(function*(){if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};const i=it(null==r?void 0:r.resolution)?r.resolution:exports.RCResolution.W640_H480,{width:n,height:s}=rt(i),{stream:o,code:a}=yield this._getMediaStream({video:{deviceId:null==r?void 0:r.cameraId,frameRate:st((null==r?void 0:r.frameRate)||exports.RCFrameRate.FPS_15),width:n,height:s,facingMode:null==r?void 0:r.faceMode}});if(a!==exports.RCRTCCode.SUCCESS)return{code:a};const c=o.getVideoTracks()[0];return{code:a,track:new $e(e,t,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",r){var i,n,s,o,a,c;return t(this,void 0,void 0,(function*(){const t=[];if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};const d=this._context.getCurrentId();if(!d)return{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const u=it(null===(i=null==r?void 0:r.video)||void 0===i?void 0:i.resolution)?r.video.resolution:exports.RCResolution.W640_H480,{width:l,height:p}=rt(u),{stream:h,code:m}=yield this._getMediaStream({video:{deviceId:null===(n=null==r?void 0:r.video)||void 0===n?void 0:n.cameraId,frameRate:st((null===(s=null==r?void 0:r.video)||void 0===s?void 0:s.frameRate)||exports.RCFrameRate.FPS_15),width:l,height:p,facingMode:null===(o=null==r?void 0:r.video)||void 0===o?void 0:o.faceMode},audio:{deviceId:null===(a=null==r?void 0:r.audio)||void 0===a?void 0:a.micphoneId,sampleRate:null===(c=null==r?void 0:r.audio)||void 0===c?void 0:c.sampleRate}});return m!==exports.RCRTCCode.SUCCESS||h.getTracks().forEach((r=>{"video"===r.kind?t.push(new $e(e,d,r)):t.unshift(new Ue(e,d,r))})),{code:m,tracks:t}}))}createScreenVideoTrack(e="screenshare",r){return t(this,void 0,void 0,(function*(){if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS};const t=this._context.getCurrentId();if(!t)return{code:exports.RCRTCCode.INVALID_USER_ID};if(!ct())return{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==r?void 0:r.chromeMediaSourceId))return{code:exports.RCRTCCode.PARAMS_ERROR};const n=it(null==r?void 0:r.resolution)?r.resolution:exports.RCResolution.W1280_H720,{width:s,height:o}=rt(n),a=i?{mandatory:{chromeMediaSourceId:r.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:s,maxWidth:s,minHeight:o,maxHeight:o}}:{frameRate:st((null==r?void 0:r.frameRate)||exports.RCFrameRate.FPS_15),width:s,height:o},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==exports.RCRTCCode.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new je(e,t,u)}}))}createLocalAudioTrack(e,r){return t(this,void 0,void 0,(function*(){if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS};if(!r||"[object MediaStreamTrack]"!==r.toString()||"audio"!==r.kind)return{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();return t?{code:exports.RCRTCCode.SUCCESS,track:new De(e,t,r)}:{code:exports.RCRTCCode.INVALID_USER_ID}}))}createLocalVideoTrack(e,r){return t(this,void 0,void 0,(function*(){if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS};if(!r||"[object MediaStreamTrack]"!==r.toString()||"video"!==r.kind)return{code:exports.RCRTCCode.CREATE_CUSTOM_TRACK_FAILED};const t=this._context.getCurrentId();return t?{code:exports.RCRTCCode.SUCCESS,track:new Ne(e,t,r)}:{code:exports.RCRTCCode.INVALID_USER_ID}}))}createLocalFileTracks(i,n,s){return t(this,void 0,void 0,(function*(){if(!Je(i))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:[]};if(!at())return{code:exports.RCRTCCode.BROWSER_NOT_SUPPORT,tracks:[]};const t=n instanceof File?URL.createObjectURL(n):n;if(!e.isHttpUrl(t)&&!/^blob:/.test(t))return r.warn(`createLocalFileTracks failed: params error -> url: ${t}`),{code:exports.RCRTCCode.PARAMS_ERROR,tracks:[]};const o=this._context.getCurrentId();return o?new Promise((e=>{const n=document.createElement("video");(null==s?void 0:s.withoutAudio)&&(n.muted=!0),n.onloadedmetadata=()=>{const a=[];let c;try{const e=n.mozCaptureStream?"mozCaptureStream":"captureStream";c=n[e]()}catch(i){r.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${t}`),r.error(i),e({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:a})}const[d,u]=rr(c,s);d&&a.push(new we(i,o,d,n)),u&&a.push(new Me(i,o,u,n)),0===a.length&&(n.pause(),n.src=""),n.onerror=null,e({code:exports.RCRTCCode.SUCCESS,tracks:a})},n.onerror=()=>{r.error(`create RCLocalFileTrack failed -> url: ${t}`),e({code:exports.RCRTCCode.CREATE_FILE_TRACK_FAILED,tracks:[]})},n.src=t,n.loop=!0,n.play()})):{code:exports.RCRTCCode.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,r,i){return t(this,void 0,void 0,(function*(){const t=[];if(!Je(e))return{code:exports.RCRTCCode.INVALID_TAGS,tracks:t};if(!(r instanceof MediaStream))return{code:exports.RCRTCCode.PARAMS_ERROR,tracks:t};const n=this._context.getCurrentId();if(!n)return{code:exports.RCRTCCode.INVALID_USER_ID,tracks:t};const[s,o]=rr(r,i);return s&&t.push(new De(e,n,s)),o&&t.push(new Ne(e,n,o)),{code:exports.RCRTCCode.SUCCESS,tracks:t}}))}joinLivingRoomAsAudience(i,n){return t(this,void 0,void 0,(function*(){if(ut(this._context.getNaviInfo()))return{code:exports.RCRTCCode.PACKAGE_ENVIRONMENT_ERROR};if(!e.validate("roomId",i,e.notEmptyString,!0)||!e.validate("livingType",n,(e=>e===exports.RCLivingType.AUDIO||e===exports.RCLivingType.VIDEO)))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:exports.RCRTCCode.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:t,data:s}=yield this._context.joinLivingRoomAsAudience(i,e.RTCMode.LIVE,n);if(t!==e.ErrorCode.SUCCESS)return r.error("audienceJoinLivingRoomError:",t),{code:exports.RCRTCCode.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};r.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(s)}`);const o=new tr(this._context,this._runtime,this._options,i,s,n);return this._crtAudienceLivingRoom=o,{room:o,code:exports.RCRTCCode.SUCCESS,userIds:o.getRemoteUserIds(),RTCTracks:o.getRemoteRTCTracks(),MCUTracks:o.getRemoteMCUTracks(),CDNUris:o.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return t(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:exports.RCRTCCode.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:exports.RCRTCCode.SUCCESS}):{code:exports.RCRTCCode.SUCCESS}}))}upgradeToAnchorRoom(i){return t(this,void 0,void 0,(function*(){if(!e.validate("room._roomId",i._roomId,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(i._roomId,e.RTCIdentityChangeType.ViewerToAnchor,i._livingType);if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const s=new Wt(this._context,this._runtime,i._roomId,n,this._service,this._options,this._releaseCrtRoomObj.bind(this),i._livingType,!0);return this._crtRoom=s,this._crtAudienceLivingRoom=null,{room:s,code:exports.RCRTCCode.SUCCESS}}))}downgradeToAudienceRoom(i){return t(this,void 0,void 0,(function*(){if(!e.validate("room._roomId",i._roomId,e.notEmptyString,!0))return{code:exports.RCRTCCode.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:exports.RCRTCCode.REPERT_JOIN_ROOM};const{code:t,data:n}=yield this._context.rtcIdentityChange(i._roomId,e.RTCIdentityChangeType.AnchorToViewer,i.getLivingType());if(t!==e.ErrorCode.SUCCESS)return r.error("change room identity error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};r.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(n)}`);const s=new tr(this._context,this._runtime,this._options,i._roomId,n,i.getLivingType());return this._crtAudienceLivingRoom=s,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:s,code:exports.RCRTCCode.SUCCESS,userIds:s.getRemoteUserIds(),RTCTracks:s.getRemoteRTCTracks(),MCUTracks:s.getRemoteMCUTracks(),CDNUris:s.getCDNInfo()}}))}getJoinedRoomInfo(){return t(this,void 0,void 0,(function*(){const{code:t,data:i}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return t!==e.ErrorCode.SUCCESS?(r.error("getJoinedUserInfo error",t),{code:exports.RCRTCCode.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:exports.RCRTCCode.SUCCESS,data:i}}))}}var nr;exports.RCKickReason=void 0,(nr=exports.RCKickReason||(exports.RCKickReason={}))[nr.SERVER_KICK=1]="SERVER_KICK",nr[nr.OTHER_KICK=2]="OTHER_KICK";const sr={tag:"RCRTC",verify:t=>"browser"!==t.tag?(r.error(`RCRTC Plugin is not support the runtime '${t.tag}'`),!1):We?(e.VersionManage.add("plugin-rtc","5.2.4"),!!e.VersionManage.validEngine(">=4.5.1")||(r.error(`The current engine version '${e.VersionManage.getInfo().engine}' error, plugin-rtc required engine version at least '>=4.5.1'.`),!1)):(r.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(t,i,n={})=>(r.setLogLevel(n.logLevel),r.setLogStdout(n.logStdout),r.warn("RCRTC Version: 5.2.4, Commit: d2c309074e678b96ebd403c0967994360e8b389c"),r.warn(`browserInfo.browser -> ${ot.browser}`),r.warn(`browserInfo.supportsUnifiedPlan -> ${ot.supportsUnifiedPlan}`),r.warn(`browserInfo.version -> ${ot.version}`),e.assert("options.mediaServer",n.mediaServer,(t=>!(!e.isHttpUrl(t)||"https:"===location.protocol&&!/^https/.test(t)))),e.assert("options.timeout",n.timeout,(t=>e.isNumber(t)&&t>=5e3&&t<=3e4)),e.assert("options.pingGap",n.pingGap,(t=>e.isNumber(t)&&t>=3e3&&t<=1e4)),new ir(t,i,n))},or={transResolution:rt,transFrameRate:st,parseTrackId:Qe,ifSupportLocalFileTrack:at,ifSupportScreenShare:ct};Object.defineProperty(exports,"RTCJoinType",{enumerable:!0,get:function(){return e.RTCJoinType}}),exports.RCAbstractRoom=Ut,exports.RCAudienceClient=Zt,exports.RCAudienceLivingRoom=tr,exports.RCCameraVideoTrack=$e,exports.RCLivingRoom=Wt,exports.RCLocalAudioTrack=De,exports.RCLocalFileAudioTrack=we,exports.RCLocalFileTrack=Ae,exports.RCLocalFileVideoTrack=Me,exports.RCLocalTrack=Le,exports.RCLocalVideoTrack=Ne,exports.RCMCUConfigBuilder=Ft,exports.RCMicphoneAudioTrack=Ue,exports.RCRTCClient=ir,exports.RCRTCRoom=Yt,exports.RCRemoteAudioTrack=Be,exports.RCRemoteTrack=Ve,exports.RCRemoteVideoTrack=Fe,exports.RCScreenVideoTrack=je,exports.RCTag={DEFAULT:"RongCloudRTC"},exports.RCTrack=Oe,exports.device=Pe,exports.helper=or,exports.installer=sr;
|