@rongcloud/plugin-rtc 5.3.4 → 5.3.5
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 +13 -8
- package/dist/index.esm.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.umd.js +1 -1
- package/package.json +2 -2
package/dist/index.esm.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 C(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 T=new e("RCRTC");var I,E;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.PERMISSION_DENIED=53012]="PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM"}(I||(I={})),function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(E||(E={}));class y{constructor(){this.queue=[],this.locked=!1}checkToStart(){return C(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 k=new y,b=e=>k.push(e);let P=!0,O=!0;function L(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function N(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 D(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(P=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function A(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(O=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function M(){if("object"==typeof window){if(P)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function x(e,t){O&&console.warn(e+" is deprecated, please use "+t+" instead.")}function U(e){return"[object Object]"===Object.prototype.toString.call(e)}function w(e){return U(e)?Object.keys(e).reduce((function(t,r){const i=U(e[r]),n=i?w(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function $(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?$(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{$(e,e.get(t),r)}))})))}function j(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&&$(e,r,n)}))})),n}const V=M;function B(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),V("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return V("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 H(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function K(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 N(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function F(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 G(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 J(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=>j(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}),N(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>j(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 W(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 Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(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 q(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 z(e,t){N(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Q=Object.freeze({__proto__:null,shimMediaStream:H,shimOnTrack:K,shimGetSendersWithDtmf:F,shimGetStats:G,shimSenderReceiverGetStats:J,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:Y,shimPeerConnection:q,fixNegotiationNeeded:z,shimGetUserMedia:B,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 X,Z,ee=(X=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},X(Z={exports:{}},Z.exports),Z.exports);function te(e,t,r,i,n){var s=ee.writeRtpDescription(e.kind,t);if(s+=ee.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=ee.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:"+ee.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+ee.localCName+"\r\n"),s}function re(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 ie(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 ne(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 se(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 oe=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 se("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=ee.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 se("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw se("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 se("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 se("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=ee.writeCandidate(o);s.candidate=Object.assign(s.candidate,ee.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=ee.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=ee.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=re(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:ee.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(se("TypeError",'Unsupported type "'+e.type+'"'));if(!ie("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(se("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=ee.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=ee.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=ee.splitSections(i._remoteDescription.sdp),r=t.shift();var n=ee.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(!(ee.isRejected(e)&&0===ee.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var l=ee.getIceParameters(e,r),h=ee.getDtlsParameters(e,r);n&&(h.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(h));var p=re(d,u);i._transceive(s,p.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(se("TypeError",'Unsupported type "'+n.type+'"'));if(!ie("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(se("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=ee.splitSections(n.sdp),d=c.shift(),u=ee.matchPrefix(d,"a=ice-lite").length>0,l=ee.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=ee.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var h=ee.splitLines(i),p=ee.getKind(i),_=ee.isRejected(i)&&0===ee.matchPrefix(i,"a=bundle-only").length,m=h[0].substr(2).split(" ")[2],f=ee.getDirection(i,d),v=ee.parseMsid(i),R=ee.getMid(i)||ee.generateIdentifier();if(_||"application"===p&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))s.transceivers[c]={mid:R,kind:p,protocol:m,rejected:!0};else{var g,S,C,T,I,E,y,k,b;!_&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(p,!0));var P,O,L=ee.parseRtpParameters(i);_||(P=ee.getIceParameters(i,d),(O=ee.getDtlsParameters(i,d)).role="client"),y=ee.parseRtpEncodingParameters(i);var N=ee.parseRtcpParameters(i),D=ee.matchPrefix(i,"a=end-of-candidates",d).length>0,A=ee.matchPrefix(i,"a=candidate:").map((function(e){return ee.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!_&&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||_){if("answer"===n.type&&!_){S=(g=s.transceivers[c]).iceGatherer,C=g.iceTransport,T=g.dtlsTransport,I=g.rtpReceiver,E=g.sendEncodingParameters,k=g.localCapabilities,s.transceivers[c].recvEncodingParameters=y,s.transceivers[c].remoteCapabilities=L,s.transceivers[c].rtcpParameters=N,A.length&&"new"===C.state&&(!u&&!D||l&&0!==c?A.forEach((function(e){ne(g.iceTransport,e)})):C.setRemoteCandidates(A)),l&&0!==c||("new"===C.state&&C.start(S,P,"controlling"),"new"===T.state&&T.start(O)),!re(g.localCapabilities,g.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&g.sendEncodingParameters[0].rtx&&delete g.sendEncodingParameters[0].rtx,s._transceive(g,"sendrecv"===f||"recvonly"===f,"sendrecv"===f||"sendonly"===f),!I||"sendrecv"!==f&&"sendonly"!==f?delete g.rtpReceiver:(b=I.track,v?(o[v.stream]||(o[v.stream]=new e.MediaStream),r(b,o[v.stream]),a.push([b,I,o[v.stream]])):(o.default||(o.default=new e.MediaStream),r(b,o.default),a.push([b,I,o.default])))}}else{(g=s.transceivers[c]||s._createTransceiver(p)).mid=R,g.iceGatherer||(g.iceGatherer=s._createIceGatherer(c,l)),A.length&&"new"===g.iceTransport.state&&(!D||l&&0!==c?A.forEach((function(e){ne(g.iceTransport,e)})):g.iceTransport.setRemoteCandidates(A)),k=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),E=g.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,x=!1;if("sendrecv"===f||"sendonly"===f){if(x=!g.rtpReceiver,I=g.rtpReceiver||new e.RTCRtpReceiver(g.dtlsTransport,p),x)b=I.track,v&&"-"===v.stream||(v?(o[v.stream]||(o[v.stream]=new e.MediaStream,Object.defineProperty(o[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(b,"id",{get:function(){return v.track}}),M=o[v.stream]):(o.default||(o.default=new e.MediaStream),M=o.default)),M&&(r(b,M),g.associatedRemoteMediaStreams.push(M)),a.push([b,I,M])}else g.rtpReceiver&&g.rtpReceiver.track&&(g.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===g.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),g.associatedRemoteMediaStreams=[]);g.localCapabilities=k,g.remoteCapabilities=L,g.rtpReceiver=I,g.rtcpParameters=N,g.sendEncodingParameters=E,g.recvEncodingParameters=y,s._transceive(s.transceivers[c],!1,x)}}})),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(se("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=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||ee.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+=te(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="+ee.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(se("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(se("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=ee.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=ee.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=re(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+=te(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(se("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(se("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?ee.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)&&!ne(a.iceTransport,c))return n(se("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=ee.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=ee.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=ee.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=ee.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 se("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 ae(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 ce(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 de(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=oe(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&&x("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 ue(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var le=Object.freeze({__proto__:null,shimPeerConnection:de,shimReplaceTrack:ue,shimGetUserMedia:ae,shimGetDisplayMedia:ce});function he(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){x("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 pe(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 _e(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 me(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 fe(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}),N(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ve(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){x("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Re(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ge(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 Se(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 Ce(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 Te(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:pe,shimPeerConnection:_e,shimSenderGetStats:me,shimReceiverGetStats:fe,shimRemoveStream:ve,shimRTCDataChannel:Re,shimAddTransceiver:ge,shimGetParameters:Se,shimCreateOffer:Ce,shimCreateAnswer:Te,shimGetUserMedia:he,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 Ee(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 ye(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 ke(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 be(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(Pe(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Pe(e){return e&&void 0!==e.video?Object.assign({},e,{video:w(e.video)}):e}function Oe(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")?(x("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 Le(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 Ne(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 De(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ae=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ee,shimRemoteStreamsAPI:ye,shimCallbacksAPI:ke,shimGetUserMedia:be,shimConstraints:Pe,shimRTCIceServerUrls:Oe,shimTrackEventTransceiver:Le,shimCreateOfferLegacy:Ne,shimAudioContext:De});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=ee.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,N(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function xe(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=ee.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ee.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=ee.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 Ue(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},N(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function we(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 $e(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 je(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 Ve=Object.freeze({__proto__:null,shimRTCIceCandidate:Me,shimMaxMessageSize:xe,shimSendThrowTypeError:Ue,shimConnectionState:we,removeExtmapAllowMixed:$e,shimAddIceCandidateNullOrEmpty:je});const Be=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=L(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=L(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=L(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=L(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Ve,extractVersion:L,disableLog:D,disableWarnings:A};switch(i.browser){case"chrome":if(!Q||!q||!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=Q,je(e,i),B(e,i),H(e),q(e,i),K(e),Y(e,i),F(e),G(e),J(e),z(e,i),Me(e),we(e),xe(e,i),Ue(e),$e(e,i);break;case"firefox":if(!Ie||!_e||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ie,je(e,i),he(e,i),_e(e,i),pe(e),ve(e),me(e),fe(e),Re(e),ge(e),Se(e),Ce(e),Te(e),Me(e),we(e),xe(e,i),Ue(e);break;case"edge":if(!le||!de||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=le,ae(e),ce(e),de(e,i),ue(e),xe(e,i),Ue(e);break;case"safari":if(!Ae||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Ae,je(e,i),Oe(e),Ne(e),ke(e),Ee(e),ye(e),Le(e),be(e),De(e),Me(e),xe(e,i),Ue(e),$e(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var He,Ke,Fe;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(He||(He={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(Ke||(Ke={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(Fe||(Fe={}));const Ge={[Ke.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[Ke.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[Ke.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[Ke.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[Ke.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in Ge){const t=Ge[e],s=Math.abs(t.width*t.height-r);s<i&&(n=t,i=s)}return n},We={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in We){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=We[i])}return r},qe={getCameras:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class ze extends t{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(){T.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){T.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return C(this,void 0,void 0,(function*(){if(!this._msTrack)return T.warn(`the track is not ready to play -> id: ${this._id}`),{code:I.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&T.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==t?void 0:t.volume){if(!r(null==t?void 0:t.volume))return T.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),{code:I.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,T.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==t?void 0:t.volume)>100&&(t.volume=100,T.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==t?void 0:t.audioDeviceId){if(!(yield qe.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return T.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),{code:I.PARAMS_ERROR}}const i=this.isVideoTrack();if(i&&(!e||!(e instanceof HTMLVideoElement)))return T.error(`the video track need an <video> to play -> id: ${this._id}`),{code:I.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=i?e: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;T.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;T.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;T.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;T.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;T.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;T.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 r=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));T.info(`HTMLMediaElement onvolumechange -> volume: ${r}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,i&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),i||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100);try{(null==t?void 0:t.audioDeviceId)&&!i?yield this._element.setSinkId(t.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(T.error(`setSinkId failed -> ${e.message}`),{code:I.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(T.error(e),{code:I.TRACK_PLAY_ERROR})}return{code:I.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class Qe extends ze{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(Qe.EVENT_LOCAL_TRACK_END,this),this.removeAll(Qe.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(Qe.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;T.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(Qe.__INNER_EVENT_DESTROY__,this)}setBitrate(e=0,t=0,i=0){!r(e)||!r(t)||!r(i)||e<=0||t<=0||e<t?T.error("setBitrate params error ->"):this._bitrateInfo={max:e,min:t,start:i}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?mt(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}}}Qe.EVENT_LOCAL_TRACK_END="local-track-end",Qe.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Qe.__INNER_EVENT_DESTROY__="inner-destroy";class Xe extends Qe{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,r){T.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Ze extends Qe{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 et extends Qe{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,et.__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(),et.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}et._mapping=new Map;class tt extends et{constructor(e,t,r,i){super(e,t,"video",r,i)}}class rt extends et{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:I.SUCCESS})}}class it extends Xe{}class nt extends Ze{}class st extends Ze{}class ot extends ze{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 ot{constructor(e,t,r){super(e,t,"audio",r)}}class ct extends ot{constructor(e,t,r){super(e,t,"video",r)}}const dt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),ut=e=>JSON.stringify(e),lt=e=>/^[a-zA-Z\d-=]+$/g.test(e),ht="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),pt=e=>{if(void 0===e)return 0;if(r(e))return e;const t=e;return t.exact||t.ideal||t.max||0},_t=e=>{const t=e.getConstraints();return{width:pt(t.width),height:pt(t.height),frameRate:pt(t.frameRate)}},mt=e=>{const{width:t,height:r,frameRate:i}=_t(e),n=Je(t,r),s=Ye(i);return{min:n.minBitrate*s,max:n.maxBitrate*s}},ft=e=>[e.msid,e.mediaType].join("_"),vt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Rt=(e,t)=>[e,t].join("_"),gt=e=>e.map((e=>Object.assign({},e))),St=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],s=[];return t.forEach((t=>{const n=ft(t);let o=e.findIndex((e=>ft(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}},Ct=()=>{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},Tt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},It=e=>!!Ke[e],Et=e=>!!He[e],yt=e=>parseInt(e.replace("FPS_","")),kt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=Be.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function bt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Pt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Ot=e=>"[object Null]"===Object.prototype.toString.call(e),Lt=e=>1===e.type,Nt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const n=[],s=e.users[i];if(s.extra){const e=JSON.parse(s.extra).roomId;if(t!==e)return}if(s.uris)try{n.push(...JSON.parse(s.uris))}catch(e){T.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}r[i]=n})),r};var Dt,At;!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",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline"}(Dt||(Dt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(At||(At={}));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 C(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var e,t,r;return C(this,void 0,void 0,(function*(){const n=yield new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{T.error(`rtcping receive unknown error -> ${t}`),e(i.UNKNOWN)})),setTimeout(e,1e4,i.TIMEOUT)})),s=Date.now();if(n===i.SUCCESS)return this._latestTimestamp=s,void(null===(e=this.onPingResult)||void 0===e||e.call(this,At.SUCCESS));null===(t=this.onPingResult)||void 0===t||t.call(this,At.FAIL),T.warn(`rtcping failed -> code: ${n}`),(40003===n||s-this._latestTimestamp>6e4)&&(this.stop(),null===(r=this.onFailed)||void 0===r||r.call(this,40003===n))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var xt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(xt||(xt={}));const Ut=(e,t)=>Math.round(8*t/e),wt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},$t=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},jt=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return wt(e/t,3);const n=t-i;if(0===n)return 0;const s=e-r;return s<0||n<0?0:wt(s/n,3)},Vt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!Ot(t)||!Ot(r)||0!==i};class Bt{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 Ut(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 Ut(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=jt(t,r,n,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?s:r}else i=jt(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=jt(t,r+t,n,s+n)}else i=jt(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===Fe.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 h=null==o?void 0:o.split("\r\nm="),p=null==h?void 0:h.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==p?void 0:p.match(a);return l=_?_[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 Ht extends Bt{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:h,bytesSent:p,trackId:_,encoderImplementation:m,pliCount:f,nackCount:v,firCount:R}=o;if(!_)return;let{framesPerSecond:g,frameWidth:S,frameHeight:C}=o;"video"!==c||S||C||g||(S=e[_].frameWidth,C=e[_].frameHeight,g=u?e[u].framesPerSecond:null);const T=e[l];let I=null,E=null,y=0;T&&(I=T.jitter,E=T.roundTripTime,y=T.packetsLost),n+=y;const k=this.getResourceIdByParseSdp(o),b=u?e[u].audioLevel:e[_].audioLevel;let P=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),T?P=this.updateSenderPacketsLost(k,y,h):this._latestPacketsSent[k].crtPacketsSent=h;let O=this.updateBytesSent(k,p,r);O<0&&(O=0),s+=O,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:P,remoteResource:!1,audioLevel:b||0===b?$t(b):null,frameWidth:S,frameHeight:C,frameRate:g,bitrate:O,jitter:I?Math.round(1e3*I):I,rtt:E,encoderImplementation:m,pliCount:f,nackCount:v,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&&!Vt(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:h,kind:p,codecImplementationName:_,nackCount:m,pliCount:f}=s;if(!a)return;let{frameWidth:v,frameHeight:R,audioLevel:g}=s;"video"===p?v||R||(v=e[a].frameWidth,R=e[a].frameHeight):g||(g=e[a].audioLevel),n+=c;const S=this.getResourceIdByParseSdp(s),C=this.updateReceiverPacketsLost(S,c,d);let T=this.updateBytesRecv(S,l,r);T<0&&(T=0),o+=T,t.receivers.push({trackId:S,kind:p,packetsLostRate:C,remoteResource:!0,audioLevel:g||0===g?$t(g):null,frameWidth:v,frameHeight:R,frameRate:h,bitrate:T,jitter:u?Math.round(1e3*u):0,codecImplementationName:_,nackCount:m,pliCount:f,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,h=e[u],{ip:p,port:_,networkType:m}=h,f=e[l],{ip:v,port:R,protocol:g}=f;t.iceCandidatePair={IP:p,port:_,networkType:m,remoteIP:v,remotePort:R,protocol:g,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?$t(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?$t(s):null})})),t}}class Kt extends Bt{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:h,pliCount:p,remoteId:_}=a,{jitter:m,roundTripTime:f,packetsLost:v}=_?e[_]:{jitter:null,roundTripTime:null,packetsLost:0},R=this.getResourceIdByParseSdp(a);i+=v;let g=null;!this._latestPacketsSent[R]&&(this._latestPacketsSent[R]={}),_?g=this.updateSenderPacketsLost(R,v,d):this._latestPacketsSent[R].crtPacketsSent=d;let S=0;"video"===o?u&&(S=Math.floor(u/1e3)):S=this.updateBytesSent(R,c,t),S<0&&(S=0),n+=S,r.senders.push({trackId:R,kind:o,packetsLostRate:g,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:S,jitter:m?Math.round(1e3*m):null,rtt:f,encoderImplementation:null,pliCount:p,nackCount:h,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&&Vt(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:h,nackCount:p,pliCount:_}=a,m=this.getResourceIdByParseSdp(a);i+=n;const f=this.updateReceiverPacketsLost(m,n,c);let v=0;"video"===l?h&&(v=Math.floor(h/1e3)):v=this.updateBytesRecv(m,o,t),v<0&&(v=0),s+=v,r.receivers.push({trackId:m,kind:l,packetsLostRate:f,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:v,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:p,pliCount:_,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:h}=d;r.iceCandidatePair={IP:o,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:h,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 Ft extends Bt{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:h,encoderImplementation:p,pliCount:_,nackCount:m,firCount:f}=n;if(!h)return;const{audioLevel:v,frameHeight:R,frameWidth:g}=e[h];let S=this.updateBytesSent(o,l,r);S<0&&(S=0),s+=S,t.senders.push({trackId:o,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:v||0===v?$t(v):null,frameWidth:g,frameHeight:R,frameRate:null,bitrate:S,jitter:null,rtt:null,encoderImplementation:p,pliCount:_,nackCount:m,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:h,nackCount:p,pliCount:_}=s,m=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:f,frameWidth:v,audioLevel:R}=e[a];n+=c;const g=this.updateReceiverPacketsLost(m,c,d);let S=this.updateBytesRecv(m,l,r);S<0&&(S=0),o+=S,t.receivers.push({trackId:m,kind:h,packetsLostRate:g,remoteResource:!0,audioLevel:R||0===R?$t(R):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:S,jitter:u,codecImplementationName:null,nackCount:p,pliCount:_,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,h=e[u],{address:p,port:_}=h,m=e[l],{address:f,port:v,protocol:R}=m;t.iceCandidatePair={IP:p||null,port:_,networkType:null,remoteIP:f,remotePort:v,protocol:R,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?$t(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?$t(o):null})})),t}}class Gt{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:r,supportsUnifiedPlan:i}=kt;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 Gt._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}=_t(r);e.push({trackId:r.id,simulcast:i?xt.TINY:xt.NORMAL,resolution:`${n}x${s}`})}return e}setRemoteAnswer(e){return C(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 T.error(e),I.SET_REMOTE_DESCRIPTION_FAILED}return I.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(kt.browser)?new Ht(e,t):/Firefox/i.test(kt.browser)?new Kt(e,t):/Safari/i.test(kt.browser)?new Ft(e,t):null}}class Jt extends Gt{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 C(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 Wt extends Gt{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){T.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}=vt(e);this._recvTransceiver[e]=t;const i=r===Fe.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 C(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)&&(T.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class Yt extends t{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=Gt.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new Jt(i):new Wt(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(){T.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;T.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||(T.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){T.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Yt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,r){return C(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,r)}))}createOffer(e){return C(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return T.debug(`offer -> ${JSON.stringify(t.sdp)}`),t}))}setRemoteAnswer(e){return C(this,void 0,void 0,(function*(){return T.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(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Qe.__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(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Qe.__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(Qe.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(Qe.__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,t;return C(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return C(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t,r;return C(this,void 0,void 0,(function*(){const i=yield this._getStatsData();if(!i)return;(i.senders.length||i.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(i));const n=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,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 qt,zt,Qt,Xt,Zt;Yt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(qt||(qt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(zt||(zt={}));class er{constructor(e,t,r,i,n=zt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(e){this._context.getConnectionStatus()===n.CONNECTED&&this._context.setRTCState(this._roomId,e)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Ct(),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())===Fe.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===Fe.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,h=this._context.getCurrentId();let p=`R3\t${n}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`,_=`R4\t${s}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`;const m=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:h,pliCount:p,rtt:_,googFirsSent:m,encoderImplementation:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||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:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsSent:m,samplingRate:n,googRenderDelayMs:u,encoderImplementation:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(R))||void 0===t?void 0:t.isLocalMuted())?qt.DISABLE:qt.ENABLE}})),f=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:h,pliCount:p,rtt:_,googFirsReceived:m,codecImplementationName:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||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:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsReceived:m,samplingRate:n,googRenderDelayMs:u,codecImplementationName:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(R))||void 0===t?void 0:t.isLocalMuted())?qt.DISABLE:qt.ENABLE}}));p+=m.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(p+`\r${this._userRole}`),_+=f.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(_+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.3.4\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${kt.browser}\t${kt.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"}(Qt||(Qt={})),function(e){e.BEGIN="begin",e.END="end"}(Xt||(Xt={}));class tr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return C(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?T.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)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(Zt||(Zt={}));const rr=e=>e instanceof ze?e.getTrackId():e.track.getTrackId();class ir{constructor(e,t,r,i,n,s,o,a,c,d){this._context=e,this._runtime=t,this._roomId=r,this._roomMode=n,this._service=s,this._initOptions=o,this._ntfClearRoomItem=a,this._isMainRoom=d,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new y,this._appListener=null,this._onRecvPKMsg=null,this._token=i.token,this._sessionId=i.sessionId,this._roomResources=c?{}:Nt(i,this._roomId),this._initRemoteTracks();const u=this._context.getCurrentId(),l=this._roomResources[u]=this._roomResources[u]||[];T.debug(`room data -> ${JSON.stringify(this._roomResources)}`),l.length>0&&b((()=>this._unpublishPrev(l))),c&&this._afterChangedRole(i),this._pinger=new Mt(r,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 er(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new Yt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(Qe.__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=ft(e),{tag:r,userId:i,mediaType:n}=vt(t),s=n===Fe.AUDIO_ONLY?new at(r,i):new ct(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,i){T.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),s("max",e,(e=>r(e)&&e>Math.max(t||1,200)),!0),s("min",t,(t=>r(t)&&t>=1&&(!r(e)||t<e)),!0),s("start",i,(i=>r(i)&&i>t&&i<=e)),this._pc.setBitrate(e,t,i)}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):T.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_onUserUnpublish(e){return C(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(e){return C(this,void 0,void 0,(function*(){const t=e.slice();e.length=0,T.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const r=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.UNPUBLISH,t),ut([]),Dt.TOTAL_CONTENT_RESOURCE,ut([]));r!==i.SUCCESS?T.error(`unpublish prev uris failed -> code: ${r}`):T.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==o.RTC_ROOM)return!1;if(t!==this._roomId)return!0;T.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Dt.KICK:this._kickoff(!0,i);break;case Dt.STATE:this.msgTaskQueue.push((()=>this._stateHandle(i)));break;case Dt.MODIFY:case Dt.PUBLISH:case Dt.UNPUBLISH:case Dt.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(i,e.messageType,e.senderUserId)));break;case Dt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Dt.USER_NOTIFY:T.warn(`TODO: ${Dt.USER_NOTIFY}`);break;case Dt.PK_INVITE:case Dt.PK_CANCEL_INVITE:case Dt.PK_INVITE_TIMEOUT:case Dt.PK_INVITE_ANSWER:case Dt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Dt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){let r;T.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(r=e.type)})),this._callAppListener("onKickOff",e,r)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void T.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:i,ignore:n}=e;if(n||!i)return;const s=[],o=[],a=[];let c;const d=this._roomResources[r]||(this._roomResources[r]=[]);switch(t){case Dt.MODIFY:a.push(...i);break;case Dt.PUBLISH:s.push(...i);break;case Dt.UNPUBLISH:o.push(...i);break;case Dt.TOTAL_CONTENT_RESOURCE:c=St(d,i),s.push(...c.publishedList),o.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const e=d.map(ft),t=[],r=[];if(s.forEach((i=>{const n=ft(i),s=e.indexOf(n),{userId:o,tag:a,mediaType:c}=vt(n);s>-1?d[s]=i:d.push(i);let u=this._remoteTracks[n];u?u.isSubscribed()&&t.push(u):(u=c===Fe.AUDIO_ONLY?new at(a,o):new ct(a,o),this._remoteTracks[n]=u,r.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));T.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield b((()=>this.__subscribe(t,!0)));r!==I.SUCCESS&&T.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(r)}if(o.length>0){const e=o.map(ft);for(let t=d.length-1;t>=0;t-=1){const r=d[t];e.includes(ft(r))&&d.splice(t,1)}const t=o.map((e=>{const t=ft(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(a.length>0){const e=d.map(ft);for(let t=0;t<a.length;t+=1){const r=a[t],i=ft(r),n=e.indexOf(i);d[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 t;return C(this,void 0,void 0,(function*(){const{users:r}=e;if(0===r.length)return;for(let e=0;e<r.length;e++){const t=r[e];if(t.extra&&t.extra.roomId!==this._roomId)return;if(1==+t.state&&!this.getRemoteUserIds().includes(t.userId))return}const i=[],n=[],s=[],o=[];r.forEach((e=>{0==+e.state?(T.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?s.push(e.userId):i.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(T.debug(`user left -> ${e.userId}`),e.switchRoleType?o.push(e.userId):n.push(e.userId))}));const a=[...i,...s],c=[...n,...o];if(c.length){const e=[],t=[];c.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===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,Zt.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,Zt.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(n.length&&this._callAppListener("onUserLeave",n));a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}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(e,t){return C(this,void 0,void 0,(function*(){const{code:r}=yield this._context.sendMessage(o.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return r!==i.SUCCESS?(T.error(`send message failed -> code: ${r}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}setRoomAttribute(e,t,r,n=!1){return C(this,void 0,void 0,(function*(){const s=yield this._context.setRTCData(this._roomId,e,t,n,a.ROOM,r);return s!==i.SUCCESS?(T.error(`SetRoomAttributeValue Failed: ${s}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}deleteRoomAttributes(e,t,r=!1){return C(this,void 0,void 0,(function*(){const n=yield this._context.removeRTCData(this._roomId,e,r,a.ROOM,t);return n!==i.SUCCESS?(T.error(`DeleteRoomAttribute Failed: ${n}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}getRoomAttributes(e=[],t=!1){return C(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,e,t,a.ROOM);return r!==i.SUCCESS?(T.error(`GetRoomAttributes Failed: ${r}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,a.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,a.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,a.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var t;return C(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._isMainRoom&&this._quitAllPKRoom(),this._pc.removeAllLocalTrack(),this._pinger.stop(),yield this._service.exit(this._getRTCReqestHeaders()),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof Ze&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return C(this,void 0,void 0,(function*(){const t=e.getTrackId(),r=this._context.getCurrentId(),n=[{resourceId:t,enabled:!e.isLocalMuted()}],s=this._roomResources[r]||[],o=[];for(let e=0;e<s.length;e+=1){const t=s[e],r=ft(t),i=n.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=n[i];t.state=e?1:0,o.push(t);break}}const a=yield b((()=>this._context.setRTCTotalRes(this._roomId,dt(Dt.MODIFY,o),ut(s),Dt.TOTAL_CONTENT_RESOURCE)));a!==i.SUCCESS&&T.error("notice `track.enabled` change failed -> code: "+a)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof Qe?e:e.track;T.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__publish(e)))}))}__publish(e){return C(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof mr)return T.error("the `publish` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return T.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Qe||e.track instanceof Qe))),!0))return T.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof Qe?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(e)>10)return T.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:I.PUBLISH_TRACK_LIMIT_EXCEEDED};T.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`),e.forEach((e=>{const{track:t,pubTiny:r}=e instanceof Qe?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||He.FPS_15,n=r.resolution||Ke.W176_H144,{width:s,height:o}=Tt(n),a=yt(i);e.applyConstraints({width:s,height:o,frameRate:a})}catch(r){return null==e||e.stop(),void T.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}this._pc.addLocalTrack(new Ze(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const r=yield this._createExchangeParams(this._subscribedList,!1),n=this._getPushOtherRoomsParams();n&&(r.pushOtherRooms=n);const s=yield this._exchangeHandle(r);if(s.code!==I.SUCCESS)return T.error(`publish failed -> roomId: ${this._roomId}, code: ${s.code}`),this._removePubFailedTracks(e),{code:s.code};const{publishList:o,sdp:a,resultCode:l,message:h,urls:p,mcuPublishList:_}=s.data;if(l!==I.SUCCESS)return T.error(`publish failed -> roomId: ${this._roomId}, code: ${l}, msg: ${h}`),this._removePubFailedTracks(e),{code:l};const m=yield this._pc.setRemoteAnswer(a.sdp);if(m!==I.SUCCESS)return{code:m};const f=this._roomResources[t],v=o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ft(e))},e))),{publishedList:R}=St(f,v),g=(null==_?void 0:_.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],S=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.PUBLISH,R),ut(v),Dt.TOTAL_CONTENT_RESOURCE,ut(g));if(S!==i.SUCCESS)return T.error(`send publish streams notification failed: ${S}`),{code:I.SIGNAL_ERROR};this._roomResources[t]=v;const C=R.map((e=>ft(e)));return this._polarisReport&&this._polarisReport.sendR2(Qt.PUBLISH,Xt.BEGIN,C),e.forEach((e=>{const{track:t}=e instanceof Qe?{track:e}:e;t.__innerSetPublished(!0)})),T.debug(`publish success: ${C.join(",")}`),this._roomMode===u.LIVE?{code:I.SUCCESS,liveUrl:null==p?void 0:p.liveUrl}:{code:I.SUCCESS}}))}_getPushOtherRoomsParams(){if(this instanceof mr){const{code:e,roomPKHandler:t}=this.getRoomPKHandler(),r=[];if(e===I.SUCCESS&&t){const e=t.getJoinedPKRooms();for(const i in e){const n=e[i].getSessionId(),s=t.getPKInfo(i);if(!s)return;const{inviterUserAutoMix:o,inviteeUserAutoMix:a,inviterUserId:c}=s,d=this._context.getCurrentId()===c;r.push({roomId:i,sessionId:n,autoMix:d?!!o:!!a})}}return r}}_reTryExchange(){return C(this,void 0,void 0,(function*(){b((()=>C(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==I.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,t){return C(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(t),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=vt(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?xt.TINY:xt.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 C(this,void 0,void 0,(function*(){return b((()=>this.__unpublish(e)))}))}__unpublish(e){var t;return C(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof mr)return T.error("the `unpublish` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return T.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:I.SUCCESS};const r=this._context.getCurrentId();if(!c("tracks",e,(()=>e.every((e=>e.getUserId()===r&&e instanceof Qe))),!0))return T.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`),{code:I.PARAMS_ERROR};const n=e.map((e=>e.getTrackId())),s=n.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===s.length)return{code:I.SUCCESS};const o=this._roomResources[r].filter((e=>!s.includes(e)));n.forEach((e=>this._pc.removeLocalTrackById(e))),null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.PUBLISH,Xt.END,n),this._pc.clearReTryExchangeTimer();const a=yield this._createExchangeParams(this._subscribedList,!1),d=this._getPushOtherRoomsParams();d&&(a.pushOtherRooms=d);const u=yield this._exchangeHandle(a);if(u.code!==I.SUCCESS)return T.error(`exchange failed -> code: ${u.code}`),{code:u.code};const{publishList:l,sdp:h,resultCode:p,message:_,mcuPublishList:m}=u.data;p!==I.SUCCESS&&T.error(`unpublish streams failed -> code: ${p}, msg: ${_}`);const f=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],v=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.UNPUBLISH,s),ut(o),Dt.TOTAL_CONTENT_RESOURCE,ut(f));if(v!==i.SUCCESS)return T.error("send unpublish notification failed:",v),{code:I.SIGNAL_ERROR};T.debug(`unpublish success -> tracks: ${n.join(",")}`);const R=yield this._pc.setRemoteAnswer(h.sdp);if(R!==I.SUCCESS)return{code:R};const g=l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ft(e))},e)));return this._roomResources[r]=g,{code:I.SUCCESS}}))}_getResourceById(e){const{userId:t}=vt(e);return this._roomResources[t].find((t=>ft(t)===e))}_isValidResourceId(e){var t;const{userId:r}=vt(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>ft(t)===e)))}subscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__subscribe(e,!1)))}))}__subscribe(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return T.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return T.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`subscribe -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`);const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof ot?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(Qt.SUBSCRIBE,Xt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:I.SUCCESS}}))}unsubscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe(e)))}))}__unsubscribe(e){var t;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return T.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:I.SUCCESS};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot))),!0))return T.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`);const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.SUBSCRIBE,Xt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return T.warn(e),I.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 C(this,void 0,void 0,(function*(){return b((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(e,t=!1){return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return T.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${t}, tracks: ${e.map(rr)}`);let r=e.map((e=>e instanceof ot?{track:e}:Object.assign({},e)));const i={};r=r.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!i[t]&&(i[t]=!0):(T.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(r.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:I.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const s=yield this._createExchangeParams(r,!1),o=this._getPushOtherRoomsParams();o&&(s.pushOtherRooms=o);const a=yield this._exchangeHandle(s),u=r.map((e=>e.track.getTrackId()));if(a.code!==I.SUCCESS)return{code:a.code};const{sdp:l,resultCode:h,message:p,subscribedList:_}=a.data;if(h!==I.SUCCESS)return T.error(`change subscribe list failed: ${h}`),{code:h};T.debug(`subscribe success: ${u.join(",")}`);const m=yield this._pc.setRemoteAnswer(l.sdp);if(m!==I.SUCCESS)return{code:m};const f=null==_?void 0:_.map((e=>`${e.msid}_${e.mediaType}`)),v=r.filter((e=>null==f?void 0:f.includes(e.track.getTrackId()))),R=r.filter((e=>!(null==f?void 0:f.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=v.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...v),R.length?{code:I.SUCCESS,failedList:R}:{code:I.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 tr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return C(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return T.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:r}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,e);if(t!==i.SUCCESS)return void T.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);T.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(r)}`);const n=[],s={},o={},a={},c=Nt(r,this._roomId),d=Object.keys(c),u=Object.keys(this._roomResources);for(let e=d.length-1;e>=0;e-=1){const t=d[e],r=u.indexOf(t);if(-1===r){n.push(t),s[t]=gt(c[t]);continue}const i=this._roomResources[t],l=c[t],{publishedList:h,modifiedList:p,unpublishedList:_}=St(i,l,!0);s[t]=gt(h),o[t]=gt(_),a[t]=gt(p),u.splice(r,1)}u.length&&u.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,c),u.length&&this._callAppListener("onUserLeave",u),n.length&&this._callAppListener("onUserJoin",n);for(const e in o){const t=o[e];if(t.length){const e=t.map((e=>this._remoteTracks[ft(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=ft(e),{userId:r,tag:i,mediaType:n}=vt(t),s=this._remoteTracks[t]=n===Fe.AUDIO_ONLY?new at(i,r):new ct(i,r);return s.__innerSetRemoteMuted(0===e.state),s}));this._onTrackPublish(r)})),Object.keys(a).forEach((e=>{a[e].forEach((e=>{const t=ft(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:r}}))}_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={})}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}}var nr,sr,or;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(nr||(nr={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(sr||(sr={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(or||(or={}));const ar=()=>({version:1,mode:sr.SUSPENSION});class cr{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=ar()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return T.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:r,userId:i}=vt(e);return t!==Fe.VIDEO_ONLY?(T.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=Rt(i,r),this)}setMixLayoutMode(e){return[sr.CUSTOMIZE,sr.SUSPENSION,sr.ADAPTATION].includes(e)?(this._values.mode=e,this):(T.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:nr.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 T.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Tt(e);return this._addOutputValue("video",{width:t,height:r},"normal"),this}setOutputVideoFPS(e){if(!Et(e))return T.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=yt(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(e){return!r(e)||e<=0?T.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"normal"),this}setOutputTinyVideoResolution(e){if(!It(e))return T.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Tt(e);return this._addOutputValue("video",{width:t,height:r},"tiny"),this}setOutputTinyVideoFPS(e){if(!Et(e))return T.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=yt(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(e){return!r(e)||e<=0?T.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"tiny"),this}setOutputVideoRenderMode(e){return[or.CROP,or.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):T.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(e){return r(e)&&e>0?this._addOutputValue("audio",e):T.error(`bitrate is invalid: ${e}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):T.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(e,t,i,n,s){var o,a,c;if(!l(e))return T.error(`uri is invalid: ${e}`),this;if([t,i,n,s].some((e=>!r(e)||e<0||e>1)))return T.error(`some attrs of (x, y, w, h) is invalid: ${t}, ${i}, ${n}, ${s}`),this;const d=(null===(c=null===(a=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===a?void 0:a.backgroundPicture)||void 0===c?void 0:c.picture)||[];return d.push({uri:e,w:n,h:s,x:t,y:i}),this._addOutputValue("video",{picture:d},"backgroundPicture"),this}removeOutputBackgroundPicture(e){var t,r,i;if(!l(e))return T.error(`uri is invalid: ${e}`),this;let n=null===(i=null===(r=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===r?void 0:r.backgroundPicture)||void 0===i?void 0:i.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[nr.CROP,nr.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):T.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return T.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];let s=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(s=!0,n.push({pushurl:e}))})),n.length>5?(T.error("publish stream url no more than 5"),this):(s&&this._addOutputValue("cdn",n),this)}removePublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return T.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(e,t,i,n,s){if(!this._isValidTrackId(e))return T.error(`trackId is invalid: ${e}`),this;if(!r(t)||!r(i))return T.error(`some attrs of (x, y) is invalid: ${t}, ${i}`),this;if([n,s].some((e=>!r(e)||e<0)))return T.error(`some attrs of (width, height) is invalid: ${n}, ${s}`),this;const{userId:o,tag:a,mediaType:c}=vt(e);if(c!==Fe.VIDEO_ONLY)return T.error(`kind of resource is not 'video': ${e}`),this;const d=Rt(o,a);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:o,stream_id:d,x:t,y:i,width:n,height:s}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return T.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:r,mediaType:i}=vt(e);if(i!==Fe.VIDEO_ONLY)return T.error(`kind of resource is not 'video': ${e}`),this;const n=Rt(t,r),s=this._values.input||(this._values.input={video:[]});return s.video=s.video.filter((e=>e.stream_id===n)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,t,r,i;return C(this,void 0,void 0,(function*(){const n=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._onFlush(n);return s===I.SUCCESS&&((null===(t=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===t?void 0:t.width)||(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.fps))&&this._sendCDNInfoSignal(),this._values=ar(),{code:s}}))}}var dr,ur,lr,hr;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(dr||(dr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(ur||(ur={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(lr||(lr={})),function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(hr||(hr={}));const pr=()=>"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)}));class _r{constructor(e,t,r,i,n,s,o,a,c){this._PKInfo=e,this._context=t,this._runtime=r,this._service=i,this._initOptions=n,this._mainLivingRoom=s,this._registerPKMsgListener=o,this._onJoinedPKRoom=a,this._onLeavePKRoom=c,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:n}=t,s={inviterRoomId:r,inviterUserId:i,extra:n};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},n={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",n)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:n,inviterRoomId:s,inviteeUserId:o,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:u}=r,l={agree:1===t,inviterRoomId:s,inviterUserId:n,inviteeRoomId:d,inviteeUserId:o,extra:u};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:s,inviterUserId:n,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",l)}_onPKEnd(e){return C(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,n=r===this._mainRoomId?t:r,s={endRoomId:n,endUserId:i};this._joinedPKRooms[n]&&(yield this.leaveOtherRoom(this._joinedPKRooms[n])),delete this._PKInfo[n],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Dt.PK_INVITE:this._onInvite(r);break;case Dt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Dt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Dt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Dt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){this._appListener=e}requestJoinOtherRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:I.PARAMS_ERROR};T.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(r||{})}`);const n=pr(),s=!p(null==r?void 0:r.autoMix)||(null==r?void 0:r.autoMix),o={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==r?void 0:r.extra)||""},a={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(o),inviteSessionId:n};T.info(`requestRoomPK -> params: ${JSON.stringify(a)}`);const d=yield this._context.requestRoomPK(a);return d!==i.SUCCESS?(T.error(`requestRoomPK failed: ${d}`),{code:d}):(T.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e},{code:I.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:I.PARAMS_ERROR};if(!this._PKInfo[e])return T.error(`未发起过与 ${e} 房间内 ${t} 连麦的请求`),{code:I.PARAMS_ERROR};T.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${r}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:r||""},s={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};T.info(`canceRequestJoinPK -> params: ${JSON.stringify(s)}`);const o=yield this._context.cancelRoomPK(s);return o!==i.SUCCESS?(T.error(`canceRequestJoinPK failed: ${o}`),{code:o}):(T.info("canceRequestJoinPK success"),delete this._PKInfo[e],{code:I.SUCCESS})}))}responseJoinOtherRoom(e,t,r,n){return C(this,void 0,void 0,(function*(){if(!c("inviterRoomId",e,h,!0)||!c("inviterUserId",t,h,!0))return{code:I.PARAMS_ERROR};if(!this._PKInfo[e])return T.error(`${e} 房间内的 ${t} 未发起过连麦请求`),{code:I.PARAMS_ERROR};T.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${r}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:s,inviterUserAutoMix:o}=this._PKInfo[e],a=!p(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),d={inviteSessionId:s,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:o,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:a},u=Object.assign(d,{inviterUserAutoMix:o}),l=r?Object.assign(d,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(u)}):d;!_(null==n?void 0:n.extra)&&Object.assign(l,{extra:n.extra});const m={agree:r,roomId:this._mainRoomId,inviteSessionId:s,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(l),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(d)};T.info(`responseRoomPK -> params: ${JSON.stringify(m)}`);const f=yield this._context.responseRoomPK(m);return f!==i.SUCCESS?(T.error(`responseRoomPK failed: ${f}`),{code:f}):(T.info("responseRoomPK success"),this._PKInfo[e].inviteeUserAutoMix=a,{code:I.SUCCESS})}))}_quitRoomPK(e){return C(this,void 0,void 0,(function*(){const{inviterRoomId:t,inviteeRoomId:r,inviterUserId:n}=this._PKInfo[e],s={inviteeRoomId:r,inviterRoomId:t,userId:this._context.getCurrentId()},o={roomId:this._mainRoomId,endRoomId:e,sessionId:this._PKInfo[e].inviteSessionId,content:JSON.stringify(s),keys:[`${t}|${n}`]};T.info(`quitRoomPK -> params: ${JSON.stringify(o)}`);const a=yield this._context.endRoomPK(o);return a!==i.SUCCESS?(T.error(`quitRoomPK failed: ${a}`),{code:I.SIGNAL_ERROR}):(T.info("quitRoomPK success"),delete this._PKInfo[e],{code:I.SUCCESS})}))}_relaseCrtRoom(){}joinOtherRoom(e){return C(this,void 0,void 0,(function*(){if(!c("roomId",e,h,!0))return{code:I.PARAMS_ERROR};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(T.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return{code:I.REPERT_JOIN_ROOM};const t=hr.VIDEO,r={extra:`{"roomId": "${this._mainRoomId}"}`},{code:s,data:o}=yield this._context.joinRTCRoom(e,u.LIVE,t,void 0,r);if(s!==i.SUCCESS)return T.error(`JoinPKRoom failed -> code: ${s}`),{code:s};T.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(o)}`);const a=new mr(this._context,this._runtime,e,o,this._service,this._initOptions,this._relaseCrtRoom.bind(this),t,!1,!1);return this._joinedPKRooms[e]=a,this._onJoinedPKRoom(e,a),{room:a,code:I.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}leaveOtherRoom(e,t){return C(this,void 0,void 0,(function*(){return b((()=>C(this,void 0,void 0,(function*(){const r=e.getRoomId();return T.info(`leavePKRoom -> userId: ${this._context.getCurrentId()} , roomId: ${r}`),yield e.__destroy(!0),delete this._joinedPKRooms[r],this._onLeavePKRoom(r),this._PKInfo[r]?(t&&this._quitRoomPK(r),{code:I.SUCCESS}):{code:I.SUCCESS}}))))}))}getPKInfo(e){return this._PKInfo[e]}getAllPKInfo(){return this._PKInfo}getJoinedPKRooms(){return this._joinedPKRooms}}class mr extends ir{constructor(e,t,r,i,n,s,o,a,c=!1,d){var l;if(super(e,t,r,i,u.LIVE,n,s,o,c,d),this._livingType=a,this._isMainRoom=d,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new cr(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this)),this._isMainRoom){const r=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:n,inviteeRoomId:s}=i;r[e===n?s:n]=JSON.parse(t.value)})),r})(this._roomId,i.roomInfo);this._roomPKHandler=new _r(r,e,t,n,s,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._onLeavePKRoom.bind(this))}const h=null===(l=i.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===l?void 0:l.value;h&&(this._CDNUris=JSON.parse(h)[0])}_isValidResourceId(e){var t;const{userId:r}=vt(e),i=!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>ft(t)===e)));let n=!1;const{code:s,roomPKHandler:o}=this.getRoomPKHandler();if(s!==I.SUCCESS||!o)return i;const a=o.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),n=c.some((t=>e===t.getTrackId())),i||n}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._isMainRoom?this._mcuConfigBuilder:(T.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_onMCUConfigFlush(e){return C(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:r,res:i}=yield this._service.setMcuConfig(t,e);return r!==I.SUCCESS?(T.error(`set MCU config failed: ${r}`),{code:r}):(T.info("set MCU config success"),i.pull_url&&(this._CDNUris=JSON.parse(i.pull_url)),{code:r,res:i})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var t,r;return C(this,void 0,void 0,(function*(){const i=yield e.__onReconnected.call(this,this._livingType);if(!i||!i.data)return;const n=i.data.roomInfo,s=null===(t=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===t?void 0:t.value;if(!s)return;const o=JSON.parse(s);(null===(r=this._CDNUris)||void 0===r?void 0:r.enableInnerCDN)!==o.enableInnerCDN&&this._callAppListener("onCDNEnableChange",o.enableInnerCDN),this._CDNUris=o}))}enableInnerCDN(e){return C(this,void 0,void 0,(function*(){if(!this._isMainRoom)return T.error("the `enableInnerCDN` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!p(e))return T.error("`enable` is invalid"),{code:I.PARAMS_ERROR};this._CDNEnable=e;const t={version:2,output:{inCDNModel:e?dr.OPEN:dr.STOP}},{code:r}=yield this._onMCUConfigFlush(t);if(r!==I.SUCCESS)return T.error(`enableInnerCDN failed -> code: ${r}`),{code:I.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==ur.SPREAD)return T.info("enableInnerCDN succeed"),{code:I.SUCCESS};const{code:i}=yield b((()=>C(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return i===I.SUCCESS?(T.info("enableInnerCDN succeed"),{code:I.SUCCESS}):(T.error(`enableInnerCDN failed -> code: ${i}`),{code:i})}))}_sendCDNInfoSignal(){return C(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===I.SUCCESS))?{code:I.SUCCESS}:{code:I.SIGNAL_ERROR}}))}_spreadCDNInfo(e){return C(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,Dt.TOTAL_CONTENT_RESOURCE,JSON.stringify([e]));return t!==i.SUCCESS?(T.error(`spreadCDNInfo failed -> code: ${t}`),{code:I.SIGNAL_ERROR}):(T.info("spreadCDNInfo succeed"),{code:I.SUCCESS})}))}_setRoomCDNInfo(e){return C(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([e]),!0,a.ROOM);return t!==i.SUCCESS?(T.error(`setRoomCDNInfo failed -> code: ${t}`),{code:I.SIGNAL_ERROR}):(T.info("setRoomCDNInfo succeed"),{code:I.SUCCESS})}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var n;return C(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r),e.cdn_uris&&((null===(n=this._CDNUris)||void 0===n?void 0:n.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var t,r,i;return C(this,void 0,void 0,(function*(){const n=yield this._service.exchange(this._getRTCReqestHeaders(),e),s=null===(r=null===(t=n.data)||void 0===t?void 0:t.urls)||void 0===r?void 0:r.pull_url;return n.code===I.SUCCESS&&s?(this._CDNUris=JSON.parse(s),(null===(i=this._CDNUris)||void 0===i?void 0:i.broadcast)===ur.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),n):n}))}_afterChangedRole(e){const t=Nt(e,this._roomId),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]},Dt.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)===lr.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}_onJoinedPKRoom(e,t){const{code:r,roomPKHandler:i}=this.getRoomPKHandler();if(r===I.SUCCESS&&i){if(!i.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}_onLeavePKRoom(e){const{code:t,roomPKHandler:r}=this.getRoomPKHandler();if(t===I.SUCCESS&&r){if(!r.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}_exchangeWithPushOtherRoom(){return C(this,void 0,void 0,(function*(){if(!this.getLocalTracks().length)return;const e=yield this._createExchangeParams(this._subscribedList,!1),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`exchange with pushOtherRoom failed: ${n}`),{code:n};const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==I.SUCCESS?{code:s}:void 0}))}getRoomPKHandler(){return this._isMainRoom?{code:I.SUCCESS,roomPKHandler:this._roomPKHandler}:(T.error("the `getRoomPKHandler` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e){const r=e[t];this._roomPKHandler.leaveOtherRoom(r)}}isMainRoom(){return this._isMainRoom}}class fr extends ir{constructor(e,t,r,i,n,s,o){super(e,t,r,i,u.RTC,n,s,o,!1)}}const vr=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${kt.browser}|${kt.version}`,ClientVersion:"5.3.4","Client-Session-Id":pr(),"Request-Id":Date.now().toString()});class Rr{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 r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return T.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const n=i[0],s=[];return n.mediaServer&&s.push(n.mediaServer.replace(/^(https?:\/\/)?/,"https://")),n.backupMediaServer&&n.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(e,t,r){return C(this,void 0,void 0,(function*(){const i=this.getNaviMS();if(0===i.length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(r.rtcFinger=this._rtcFinger);for(let n=0;n<i.length;n+=1){const s=`${i[n]}${e}`,o=vr();T.debug(`request -> Request-Id: ${o["Request-Id"]}, url: ${s}`);const{status:a,data:c}=yield this._runtime.httpReq({url:s,body:JSON.stringify(r),headers:Object.assign(Object.assign({},o),t),method:m.POST,timeout:this._timeout});if(200===a){const e=JSON.parse(c);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),T.debug(`request success -> Request-Id: ${o["Request-Id"]}`),{code:I.SUCCESS,data:e}}T.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${s}`),this._failedMs.push(...this._msInNavi.splice(n,1))}return{code:I.REQUEST_FAILED}}))}exchange(e,t){var r;return C(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===I.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===I.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return C(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 C(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return C(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:I.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,i=vr();T.debug(`request -> Request-Id: ${i["Request-Id"]}, url: ${r}`);const{status:n,data:s}=yield this._runtime.httpReq({url:r,headers:Object.assign(Object.assign({},i),e),body:JSON.stringify(t),method:m.POST});if(200===n){T.debug(`request success -> Request-Id: ${i["Request-Id"]}`);const e=JSON.parse(s);return{code:e.resultCode,res:e}}return{code:I.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return C(this,void 0,void 0,(function*(){const r=vr(),{status:i,data:n}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},r),e),method:m.GET});if(200===i){const e=JSON.parse(n);return{code:e.resultCode,res:e}}return T.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${i}, url: ${t}`),{code:I.REQUEST_FAILED}}))}}class gr{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 Rr(t,e,r.mediaServer)}_getReqHeaders(e){return C(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:n}=yield this._context.getRTCToken(r,u.LIVE,e);if(t!==i.SUCCESS)return T.error(`getRTCToken failed: ${t}`),{code:I.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:I.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:u.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 C(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===I.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return C(this,void 0,void 0,(function*(){return b((()=>this.__subscribe(e,t,r,i)))}))}__subscribe(e,t,r,i=!1){var n;return C(this,void 0,void 0,(function*(){const s=[];if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR,tracks:s};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!f(e))return T.error(`liveUrl is invalid: ${e}`),{code:I.PARAMS_ERROR,tracks:s};if(![hr.AUDIO,hr.VIDEO].includes(t))return T.error(`livingType is invalid: ${t}`),{code:I.PARAMS_ERROR,tracks:s};if(![Fe.AUDIO_ONLY,Fe.VIDEO_ONLY,Fe.AUDIO_VIDEO].includes(r))return T.error(`mediaType is invalid: ${r}`),{code:I.PARAMS_ERROR,tracks:s};if(this._liveUrl&&this._liveUrl!==e)return{code:I.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:s};this._pc||(this._pc=new Yt(this._reTryExchange.bind(this)),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=e;const{code:o,headers:a}=yield this._getReqHeaders(t);if(o!==I.SUCCESS)return{code:o,tracks:s};const c=`rc_mcu_${Date.now()}`,d="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new at(d,c),new ct(d,c)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const u={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:r,simulcast:i?xt.TINY:xt.NORMAL,switchstream:!1},l=yield this._service.broadcastSubscribe(a,u);if(l.code!==I.SUCCESS)return T.error(`andience subscribe failed: ${l.code}`),{code:l.code,tracks:s};const h=l.data;if(h.resultCode!==I.SUCCESS)return T.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),{code:h.resultCode,tracks:s};T.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=r,this._subTiny=i;const{sdp:p,subscribedList:_}=h,m=[];return _.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];m.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(p.sdp),{code:I.SUCCESS,tracks:m}}))}unsubscribe(){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return C(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:I.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:r}=yield this._service.broadcastExit(t);return r!==I.SUCCESS?T.error(`broadcast unsubscribe failed: ${r}`):T.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:r}}))}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,r;const i=e.receiver.track,n="audio"===i.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY,s=this._subTracks[n];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){T.error(e)}}}var Sr,Cr;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(Sr||(Sr={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Cr||(Cr={}));const Tr=Object.assign(Object.assign({},Tt(Ke.W176_H144)),{frameRate:yt(He.FPS_15)});class Ir{constructor(e,t,r,i,n,s){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=n,this._livingType=s,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._setInitData(),this._service=new Rr(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new er(this._context,this._runtime,this._roomId,this,zt.Audience),this._polarisReport.sendR1(),this._pc=new Yt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):T.warn("cannot found RCRemoteTrack:",r.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],i=r?r.value:"",n=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],s=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),o=s.length?JSON.parse(s[0].mcu_uris||"[]"):[],a=[];o.forEach((t=>{const{mediaType:r,tag:i}=t,n=r===Fe.AUDIO_ONLY?new at(i,"",e):new ct(i,"",e);a.push(n)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,n=i.split("_")[0],s=t===Fe.AUDIO_ONLY?new at(r,n):new ct(r,n);d.push(s)}))}));const u=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:i,remoteUserIds:n||[],remoteRTCUris:c,remoteMUCUris:o,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:u||{}}})(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=ft(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 T.warn(e),I.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var r;if(t!==this._roomId)return void T.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);T.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const i=[],n=null===(r=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===r?void 0:r.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:n,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),n=JSON.parse(e.uris||"[]");return i.push(...t),void this._diffAnchorResource(n,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(i)}_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 C(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 C(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=ft(e),{userId:n,tag:s,mediaType:o}=vt(r),a=[this._roomId,s,o].join("_");if(!this._remoteTracks[a]){const r=o===Fe.AUDIO_ONLY?new at(s,"",this._roomId):new ct(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,t){return C(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:n,modifiedList:s}=St(r,e);if(i.length){const e=r.map(ft),t=[],n=[];if(i.forEach((i=>{const s=ft(i),o=e.indexOf(s),{userId:a,tag:c,mediaType:d}=vt(s);o>-1?r[o]=i:r.push(i);let u=this._remoteTracks[s];this._roomRes[s]=i,u?u.isSubscribed()&&t.push(u):(u=d===Fe.AUDIO_ONLY?new at(c,a):new ct(c,a),this._remoteTracks[s]=u,n.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));T.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield b((()=>this._subscribeHandle(t,!0)));r!==I.SUCCESS&&T.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(ft);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(ft(i))&&r.splice(t,1)}const t=n.map((e=>{const t=ft(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(ft);for(let t=0;t<s.length;t++){const i=s[t],n=ft(i),o=e.indexOf(n);r[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,t){return C(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(t,e)}))}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_reTryExchange(){return C(this,void 0,void 0,(function*(){b((()=>C(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`reTryExchange failed: ${n}`),{code:n};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,n=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),n)}const o=yield this._pc.setRemoteAnswer(i.sdp);return o!==I.SUCCESS?{code:o}:void 0}))))}))}_createSubscribeParams(e,t,r){return C(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),n={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:o}=t[e];[r,o].forEach(((t,r)=>{var o;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(o=i.sdp)||void 0===o?void 0:o.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:u,height:l,frameRate:h}=d?_t(c):Tr;n.resolutionInfo.push({trackId:c.id,simulcast:d?xt.NORMAL:xt.TINY,resolution:`${u}x${l}`});const p=Je(u,l),_=Ye(h);s.min+=p.minBitrate*_,s.max+=p.maxBitrate*_}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?xt.TINY:xt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return{code:I.PARAMS_ERROR};const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof ot?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(Qt.SUBSCRIBE,Xt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:I.SUCCESS}}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:u.LIVE,UserId:e,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return{code:I.PARAMS_ERROR};let i=e.map((e=>e instanceof ot?{track:e}:Object.assign({},e)));const n={};i=i.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const s=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.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:I.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:o}=yield this._createSubscribeParams(i,{},!1),a=yield this._exchangeHandle(o);if(s.length){const e=[];s.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(a.code!==I.SUCCESS)return{code:a.code};const{sdp:u,resultCode:l,message:h,subscribedList:p}=a.data;if(l!==I.SUCCESS)return T.error("change subscribe list failed:",h,l),{code:l};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=vt(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const _=yield this._pc.setRemoteAnswer(u.sdp);if(_!==I.SUCCESS)return{code:_};const m=null==p?void 0:p.map((e=>`${e.msid}_${e.mediaType}`)),f=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return m.includes(r)}return null==m?void 0:m.includes(e.track.getTrackId())})),v=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),R=i.filter((e=>!(null==v?void 0:v.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),R.length?{code:I.SUCCESS,failedList:R}:{code:I.SUCCESS}}))}_diffCDNUris(e){return C(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 C(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,n=this._initOptions.pullInnerCDNProtocol||Sr.FLV,s=this._initOptions.pullInnerCDNUseHttps===Cr.NOT_HTTPS?Cr.NOT_HTTPS:Cr.HTTPS;if(!this._CDNUris.url)return T.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${I.CDN_RESOURCE_IS_EMPTY}`),{code:I.CDN_RESOURCE_IS_EMPTY};const o={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${n}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:u,res:l}=yield this._service.getCDNResourceInfo(o,d);return u!==I.SUCCESS?(T.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(T.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(e,t){return C(this,void 0,void 0,(function*(){if(e&&!It(e))return T.error("`resolution` is invalid"),{code:I.PARAMS_ERROR};if(t&&!Et(t))return T.error("`fps` is invalid"),{code:I.PARAMS_ERROR};const{width:r,height:i}=e?Tt(e):{width:null,height:null},n=t?yt(t):null,s={};return r&&(s.w=r),i&&(s.h=i),n&&(s.fps=n),this._getCDNPlayUrl(s)}))}subscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(e){var t;return C(this,void 0,void 0,(function*(){if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot))),!0))return T.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.SUBSCRIBE,Xt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}unsubscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe(e)))}))}__destroy(e){var t;return C(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.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 C(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,u.LIVE);e!==i.SUCCESS&&T.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 tr(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 Er=(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 yr{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Gt.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Rr(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(e){var t;if(e.conversationType!==o.RTC_ROOM)return!1;if(this._crtRoom instanceof mr){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),!0}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===I.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}_getPKRoomIds(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===I.SUCCESS&&t){const e=t.getAllPKInfo();return Object.keys(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,r){return b((()=>this._joinRTCRoom(e,t,r)))}_joinRTCRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0))return{code:I.PARAMS_ERROR};if(!c("outerUserDatas",r,v,!1))return{code:I.PARAMS_ERROR};if(r){if(!Object.keys(r).every((e=>c(`outerUserDatas.${e}`,r[e],f,!0))))return{code:I.PARAMS_ERROR}}if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};T.debug(`joinRoom -> roomId: ${e}; joinType: ${t||R.KICK}`);const{code:s,data:o}=yield this._context.joinRTCRoom(e,u.RTC,void 0,t,void 0,r);if(s!==i.SUCCESS){T.error(`joinRoom failed -> code: ${s}`);return{code:s===E.JOIN_REFUSED?I.SIGNAL_JOIN_RTC_ROOM_REFUSED:s}}T.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(o)}`);const a=new fr(this._context,this._runtime,e,o,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=a,{room:a,code:I.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}joinLivingRoom(e,t,r,i){return b((()=>this._joinLivingRoom(e,t,r,i)))}_joinLivingRoom(e,t,r,s){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===hr.AUDIO||e===hr.VIDEO)))return{code:I.PARAMS_ERROR};if(!c("outerUserDatas",s,v,!1))return{code:I.PARAMS_ERROR};if(s){if(!Object.keys(s).every((e=>c(`outerUserDatas.${e}`,s[e],f,!0))))return{code:I.PARAMS_ERROR}}if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};T.debug(`joinRoom, roomId: ${e}`);const{code:o,data:a}=yield this._context.joinRTCRoom(e,u.LIVE,t,r,void 0,s);if(o!==i.SUCCESS)return T.error(`joinRoom failed -> code: ${o}`),{code:o};T.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(a)}`);const d=new mr(this._context,this._runtime,e,a,this._service,this._options,this._releaseCrtRoomObj.bind(this),t,!1,!0);this._crtRoom=d;const l={room:d,code:I.SUCCESS,userIds:d.getRemoteUserIds(),tracks:d.getRemoteTracks(),PKRoomIds:this._getPKRoomIds()};return d.__getCDNPushMode()===lr.MANUAL&&Object.assign(l,{CDNEnable:d.__getCDNEnable()}),l}))}getAudienceClient(){return this._audience||(this._audience=new gr(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(e){if(T.debug(`signal server connection state change: ${e}`),e===n.CONNECTED){if(this._crtRoom instanceof mr){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){T.debug("TODO -> on IM disconnect")}_onIMUninit(){T.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return b((()=>this._leaveRoom(e)))}_leaveRoom(e){return C(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),T.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:I.SUCCESS}):{code:I.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,t="getUserMedia"){return C(this,void 0,void 0,(function*(){try{const r=yield navigator.mediaDevices[t](e);return{code:I.SUCCESS,stream:r}}catch(e){if("Permission denied"===e.message)return{code:I.PERMISSION_DENIED};T.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?I.GET_USER_MEDIA_FAILED:I.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==I.SUCCESS)return{code:n};const s=i.getAudioTracks()[0];return{code:n,track:new it(e,r,s)}}))}createCameraVideoTrack(e="RongCloudRTC",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};const i=It(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:s}=Tt(i),{stream:o,code:a}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:yt((null==t?void 0:t.frameRate)||He.FPS_15),width:n,height:s,facingMode:null==t?void 0:t.faceMode}});if(a!==I.SUCCESS)return{code:a};const c=o.getVideoTracks()[0];return{code:a,track:new nt(e,r,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var r,i,n,s,o,a;return C(this,void 0,void 0,(function*(){const c=[];if(!lt(e))return{code:I.INVALID_TAGS,tracks:c};const d=this._context.getCurrentId();if(!d)return{code:I.INVALID_USER_ID,tracks:c};const u=It(null===(r=null==t?void 0:t.video)||void 0===r?void 0:r.resolution)?t.video.resolution:Ke.W640_H480,{width:l,height:h}=Tt(u),{stream:p,code:_}=yield this._getMediaStream({video:{deviceId:null===(i=null==t?void 0:t.video)||void 0===i?void 0:i.cameraId,frameRate:yt((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||He.FPS_15),width:l,height:h,facingMode:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.faceMode},audio:{deviceId:null===(o=null==t?void 0:t.audio)||void 0===o?void 0:o.micphoneId,sampleRate:null===(a=null==t?void 0:t.audio)||void 0===a?void 0:a.sampleRate}});return _!==I.SUCCESS||p.getTracks().forEach((t=>{"video"===t.kind?c.push(new nt(e,d,t)):c.unshift(new it(e,d,t))})),{code:_,tracks:c}}))}createScreenVideoTrack(e="screenshare",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};if(!Pt())return{code:I.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==t?void 0:t.chromeMediaSourceId))return{code:I.PARAMS_ERROR};const n=It(null==t?void 0:t.resolution)?t.resolution:Ke.W1280_H720,{width:s,height:o}=Tt(n),a=i?{mandatory:{chromeMediaSourceId:t.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:s,maxWidth:s,minHeight:o,maxHeight:o}}:{frameRate:yt((null==t?void 0:t.frameRate)||He.FPS_15),width:s,height:o},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==I.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new st(e,r,u)}}))}createLocalAudioTrack(e,t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return{code:I.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:I.SUCCESS,track:new Xe(e,r,t)}:{code:I.INVALID_USER_ID}}))}createLocalVideoTrack(e,t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return{code:I.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:I.SUCCESS,track:new Ze(e,r,t)}:{code:I.INVALID_USER_ID}}))}createLocalFileTracks(e,t,r){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS,tracks:[]};if(!bt())return{code:I.BROWSER_NOT_SUPPORT,tracks:[]};const i=t instanceof File?URL.createObjectURL(t):t;if(!l(i)&&!/^blob:/.test(i))return T.warn(`createLocalFileTracks failed: params error -> url: ${i}`),{code:I.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const s=document.createElement("video");(null==r?void 0:r.withoutAudio)&&(s.muted=!0),s.onloadedmetadata=()=>{const o=[];let a;try{const e=s.mozCaptureStream?"mozCaptureStream":"captureStream";a=s[e]()}catch(e){T.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${i}`),T.error(e),t({code:I.CREATE_FILE_TRACK_FAILED,tracks:o})}const[c,d]=Er(a,r);c&&o.push(new rt(e,n,c,s)),d&&o.push(new tt(e,n,d,s)),0===o.length&&(s.pause(),s.src=""),s.onerror=null,t({code:I.SUCCESS,tracks:o})},s.onerror=()=>{T.error(`create RCLocalFileTrack failed -> url: ${i}`),t({code:I.CREATE_FILE_TRACK_FAILED,tracks:[]})},s.src=i,s.loop=!0,s.play()})):{code:I.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,t,r){return C(this,void 0,void 0,(function*(){const i=[];if(!lt(e))return{code:I.INVALID_TAGS,tracks:i};if(!(t instanceof MediaStream))return{code:I.PARAMS_ERROR,tracks:i};const n=this._context.getCurrentId();if(!n)return{code:I.INVALID_USER_ID,tracks:i};const[s,o]=Er(t,r);return s&&i.push(new Xe(e,n,s)),o&&i.push(new Ze(e,n,o)),{code:I.SUCCESS,tracks:i}}))}joinLivingRoomAsAudience(e,t){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===hr.AUDIO||e===hr.VIDEO)))return{code:I.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:I.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:n}=yield this._context.joinLivingRoomAsAudience(e,u.LIVE,t);if(r!==i.SUCCESS)return T.error("audienceJoinLivingRoomError:",r),{code:I.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};T.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(n)}`);const s=new Ir(this._context,this._runtime,this._options,e,n,t);return this._crtAudienceLivingRoom=s,{room:s,code:I.SUCCESS,userIds:s.getRemoteUserIds(),RTCTracks:s.getRemoteRTCTracks(),MCUTracks:s.getRemoteMCUTracks(),CDNUris:s.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return C(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:I.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:I.SUCCESS}):{code:I.SUCCESS}}))}upgradeToAnchorRoom(e){return C(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,h,!0))return{code:I.PARAMS_ERROR};if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,g.ViewerToAnchor,e._livingType);if(t!==i.SUCCESS)return T.error("change room identity error",t),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const n=new mr(this._context,this._runtime,e._roomId,r,this._service,this._options,this._releaseCrtRoomObj.bind(this),e._livingType,!0,!0);return this._crtRoom=n,this._crtAudienceLivingRoom=null,{room:n,code:I.SUCCESS,userIds:e.getRemoteUserIds(),tracks:n.getRemoteTracks()}}))}downgradeToAudienceRoom(e){return C(this,void 0,void 0,(function*(){if(!e.isMainRoom())return T.error("the `downgradeToAudienceRoom` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!c("room._roomId",e._roomId,h,!0))return{code:I.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:I.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,g.AnchorToViewer,e.getLivingType());if(t!==i.SUCCESS)return T.error("change room identity error",t),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};T.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(r)}`);const n=new Ir(this._context,this._runtime,this._options,e._roomId,r,e.getLivingType());return this._crtAudienceLivingRoom=n,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:n,code:I.SUCCESS,userIds:n.getRemoteUserIds(),RTCTracks:n.getRemoteRTCTracks(),MCUTracks:n.getRemoteMCUTracks(),CDNUris:n.getCDNInfo()}}))}getJoinedRoomInfo(){return C(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==i.SUCCESS?(T.error("getJoinedUserInfo error",e),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:I.SUCCESS,data:t}}))}}var kr;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(kr||(kr={}));const br={tag:"RCRTC",verify:e=>"browser"!==e.tag?(T.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):ht?(S.add("plugin-rtc","5.3.4"),!!S.validEngine(">=5.1.2")||(T.error(`The current engine version '${S.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.1.2'.`),!1)):(T.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(e,t,i={})=>(T.setLogLevel(i.logLevel),T.setLogStdout(i.logStdout),T.warn("RCRTC Version: 5.3.4, Commit: a0331c6614c5526fb301c3497945278cf0ecc69d"),T.warn(`browserInfo.browser -> ${kt.browser}`),T.warn(`browserInfo.supportsUnifiedPlan -> ${kt.supportsUnifiedPlan}`),T.warn(`browserInfo.version -> ${kt.version}`),s("options.mediaServer",i.mediaServer,(e=>!(!l(e)||"https:"===location.protocol&&!/^https/.test(e)))),s("options.timeout",i.timeout,(e=>r(e)&&e>=5e3&&e<=3e4)),s("options.pingGap",i.pingGap,(e=>r(e)&&e>=3e3&&e<=1e4)),new yr(e,t,i))},Pr={DEFAULT:"RongCloudRTC"},Or={transResolution:Tt,transFrameRate:yt,parseTrackId:vt,ifSupportLocalFileTrack:bt,ifSupportScreenShare:Pt};export{nr as BackgroundPictureFillMode,sr as MixLayoutMode,or as MixVideoRenderMode,ir as RCAbstractRoom,gr as RCAudienceClient,Ir as RCAudienceLivingRoom,nt as RCCameraVideoTrack,He as RCFrameRate,Cr as RCInnerCDNPullIsHttps,Sr as RCInnerCDNPullKind,kr as RCKickReason,mr as RCLivingRoom,hr as RCLivingType,Xe as RCLocalAudioTrack,rt as RCLocalFileAudioTrack,et as RCLocalFileTrack,tt as RCLocalFileVideoTrack,Qe as RCLocalTrack,Ze as RCLocalVideoTrack,cr as RCMCUConfigBuilder,Fe as RCMediaType,it as RCMicphoneAudioTrack,yr as RCRTCClient,I as RCRTCCode,Zt as RCRTCLiveRole,At as RCRTCPingResult,fr as RCRTCRoom,at as RCRemoteAudioTrack,ot as RCRemoteTrack,ct as RCRemoteVideoTrack,Ke as RCResolution,st as RCScreenVideoTrack,Pr as RCTag,ze as RCTrack,qe as device,Or as helper,br as installer};
|
|
15
|
+
***************************************************************************** */function C(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 T=new e("RCRTC");var I,E;!function(e){e[e.SUCCESS=1e4]="SUCCESS",e[e.SIGNAL_DISCONNECTED=5e4]="SIGNAL_DISCONNECTED",e[e.PARAMS_ERROR=50001]="PARAMS_ERROR",e[e.REPERT_JOIN_ROOM=50002]="REPERT_JOIN_ROOM",e[e.NOT_IN_ROOM=50003]="NOT_IN_ROOM",e[e.SERVICE_INVALID=50004]="SERVICE_INVALID",e[e.RTC_TOKEN_INVALID=50006]="RTC_TOKEN_INVALID",e[e.SIGNAL_ERROR=53001]="SIGNAL_ERROR",e[e.CREATE_OFFER_FAILED=53003]="CREATE_OFFER_FAILED",e[e.REQUEST_FAILED=53004]="REQUEST_FAILED",e[e.MCU_SERVER_NOT_FOUND=53005]="MCU_SERVER_NOT_FOUND",e[e.BROADCAST_SUB_LIST_NOT_EMPTY=53007]="BROADCAST_SUB_LIST_NOT_EMPTY",e[e.ROOM_HAS_BEEN_DESTROYED=53008]="ROOM_HAS_BEEN_DESTROYED",e[e.NOT_OPEN_VIDEO_AUDIO_SERVER=53009]="NOT_OPEN_VIDEO_AUDIO_SERVER",e[e.GET_USER_MEDIA_FAILED=53010]="GET_USER_MEDIA_FAILED",e[e.GET_DISPLAY_MEDIA_FAILED=53011]="GET_DISPLAY_MEDIA_FAILED",e[e.PERMISSION_DENIED=53012]="PERMISSION_DENIED",e[e.CREATE_CUSTOM_TRACK_FAILED=53013]="CREATE_CUSTOM_TRACK_FAILED",e[e.INVALID_TAGS=53014]="INVALID_TAGS",e[e.INVALID_USER_ID=53015]="INVALID_USER_ID",e[e.CREATE_FILE_TRACK_FAILED=53016]="CREATE_FILE_TRACK_FAILED",e[e.INVALID_FILE_INSTANCE=53017]="INVALID_FILE_INSTANCE",e[e.SET_REMOTE_DESCRIPTION_FAILED=53018]="SET_REMOTE_DESCRIPTION_FAILED",e[e.BROWSER_NOT_SUPPORT=53019]="BROWSER_NOT_SUPPORT",e[e.TRACK_NOT_READY=53020]="TRACK_NOT_READY",e[e.VIDEO_TRACK_MISS_MEDIA_ELEMENT=53021]="VIDEO_TRACK_MISS_MEDIA_ELEMENT",e[e.TRACK_PLAY_ERROR=53022]="TRACK_PLAY_ERROR",e[e.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED=53023]="SIGNAL_AUDIENCE_JOIN_ROOM_FAILED",e[e.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED=53024]="SIGNAL_ROOM_CHANGE_IDENTITY_FAILED",e[e.PACKAGE_ENVIRONMENT_ERROR=53025]="PACKAGE_ENVIRONMENT_ERROR",e[e.PUBLISH_TRACK_LIMIT_EXCEEDED=53026]="PUBLISH_TRACK_LIMIT_EXCEEDED",e[e.CDN_RESOURCE_IS_EMPTY=53027]="CDN_RESOURCE_IS_EMPTY",e[e.SIGNAL_JOIN_RTC_ROOM_REFUSED=53028]="SIGNAL_JOIN_RTC_ROOM_REFUSED",e[e.NO_PERMISSION_TO_USE_REQUESTED_DEVICE=53029]="NO_PERMISSION_TO_USE_REQUESTED_DEVICE",e[e.THE_FUNCTION_IS_DISABLED_IN_PKROOM=53030]="THE_FUNCTION_IS_DISABLED_IN_PKROOM"}(I||(I={})),function(e){e[e.JOIN_REFUSED=40032]="JOIN_REFUSED"}(E||(E={}));class y{constructor(){this.queue=[],this.locked=!1}checkToStart(){return C(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 k=new y,b=e=>k.push(e);let P=!0,O=!0;function L(e,t,r){const i=e.match(t);return i&&i.length>=r&&parseInt(i[r],10)}function N(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 D(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(P=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function A(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(O=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function M(){if("object"==typeof window){if(P)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function x(e,t){O&&console.warn(e+" is deprecated, please use "+t+" instead.")}function U(e){return"[object Object]"===Object.prototype.toString.call(e)}function w(e){return U(e)?Object.keys(e).reduce((function(t,r){const i=U(e[r]),n=i?w(e[r]):e[r],s=i&&!Object.keys(n).length;return void 0===n||s?t:Object.assign(t,{[r]:n})}),{}):e}function $(e,t,r){t&&!r.has(t.id)&&(r.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?$(e,e.get(t[i]),r):i.endsWith("Ids")&&t[i].forEach((t=>{$(e,e.get(t),r)}))})))}function j(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&&$(e,r,n)}))})),n}const V=M;function H(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),V("chrome: "+JSON.stringify(e)),n(e)}))}e.video=i(e.video)}return V("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 B(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function K(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 N(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function F(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 G(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 J(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=>j(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}),N(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>j(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 W(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 Y(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return W(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 q(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 z(e,t){N(e,"negotiationneeded",(e=>{const r=e.target;if(!(t.version<72||r.getConfiguration&&"plan-b"===r.getConfiguration().sdpSemantics)||"stable"===r.signalingState)return e}))}var Q=Object.freeze({__proto__:null,shimMediaStream:B,shimOnTrack:K,shimGetSendersWithDtmf:F,shimGetStats:G,shimSenderReceiverGetStats:J,shimAddTrackRemoveTrackWithNative:W,shimAddTrackRemoveTrack:Y,shimPeerConnection:q,fixNegotiationNeeded:z,shimGetUserMedia:H,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 X,Z,ee=(X=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},X(Z={exports:{}},Z.exports),Z.exports);function te(e,t,r,i,n){var s=ee.writeRtpDescription(e.kind,t);if(s+=ee.writeIceParameters(e.iceGatherer.getLocalParameters()),s+=ee.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:"+ee.localCName+"\r\n",e.rtpSender&&e.sendEncodingParameters[0].rtx&&(s+="a=ssrc:"+e.sendEncodingParameters[0].rtx.ssrc+" cname:"+ee.localCName+"\r\n"),s}function re(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 ie(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 ne(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 se(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 oe=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 se("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=ee.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 se("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var i;if(this.transceivers.find((function(e){return e.track===t})))throw se("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 se("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 se("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=ee.writeCandidate(o);s.candidate=Object.assign(s.candidate,ee.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=ee.getMediaSections(i._localDescription.sdp);d[s.candidate.sdpMLineIndex]+=a?"a=end-of-candidates\r\n":"a="+s.candidate.candidate+"\r\n",i._localDescription.sdp=ee.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=re(e.localCapabilities,e.remoteCapabilities);r&&e.rtpSender&&(n.encodings=e.sendEncodingParameters,n.rtcp={cname:ee.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(se("TypeError",'Unsupported type "'+e.type+'"'));if(!ie("setLocalDescription",e.type,i.signalingState)||i._isClosed)return Promise.reject(se("InvalidStateError","Can not set local "+e.type+" in state "+i.signalingState));if("offer"===e.type)t=ee.splitSections(e.sdp),r=t.shift(),t.forEach((function(e,t){var r=ee.parseRtpParameters(e);i.transceivers[t].localCapabilities=r})),i.transceivers.forEach((function(e,t){i._gather(e.mid,t)}));else if("answer"===e.type){t=ee.splitSections(i._remoteDescription.sdp),r=t.shift();var n=ee.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(!(ee.isRejected(e)&&0===ee.matchPrefix(e,"a=bundle-only").length)&&!s.rejected){var l=ee.getIceParameters(e,r),h=ee.getDtlsParameters(e,r);n&&(h.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(h));var p=re(d,u);i._transceive(s,p.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(se("TypeError",'Unsupported type "'+n.type+'"'));if(!ie("setRemoteDescription",n.type,s.signalingState)||s._isClosed)return Promise.reject(se("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=ee.splitSections(n.sdp),d=c.shift(),u=ee.matchPrefix(d,"a=ice-lite").length>0,l=ee.matchPrefix(d,"a=group:BUNDLE ").length>0;s.usingBundle=l;var h=ee.matchPrefix(d,"a=ice-options:")[0];return s.canTrickleIceCandidates=!!h&&h.substr(14).split(" ").indexOf("trickle")>=0,c.forEach((function(i,c){var h=ee.splitLines(i),p=ee.getKind(i),_=ee.isRejected(i)&&0===ee.matchPrefix(i,"a=bundle-only").length,m=h[0].substr(2).split(" ")[2],f=ee.getDirection(i,d),v=ee.parseMsid(i),R=ee.getMid(i)||ee.generateIdentifier();if(_||"application"===p&&("DTLS/SCTP"===m||"UDP/DTLS/SCTP"===m))s.transceivers[c]={mid:R,kind:p,protocol:m,rejected:!0};else{var g,S,C,T,I,E,y,k,b;!_&&s.transceivers[c]&&s.transceivers[c].rejected&&(s.transceivers[c]=s._createTransceiver(p,!0));var P,O,L=ee.parseRtpParameters(i);_||(P=ee.getIceParameters(i,d),(O=ee.getDtlsParameters(i,d)).role="client"),y=ee.parseRtpEncodingParameters(i);var N=ee.parseRtcpParameters(i),D=ee.matchPrefix(i,"a=end-of-candidates",d).length>0,A=ee.matchPrefix(i,"a=candidate:").map((function(e){return ee.parseCandidate(e)})).filter((function(e){return 1===e.component}));if(("offer"===n.type||"answer"===n.type)&&!_&&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||_){if("answer"===n.type&&!_){S=(g=s.transceivers[c]).iceGatherer,C=g.iceTransport,T=g.dtlsTransport,I=g.rtpReceiver,E=g.sendEncodingParameters,k=g.localCapabilities,s.transceivers[c].recvEncodingParameters=y,s.transceivers[c].remoteCapabilities=L,s.transceivers[c].rtcpParameters=N,A.length&&"new"===C.state&&(!u&&!D||l&&0!==c?A.forEach((function(e){ne(g.iceTransport,e)})):C.setRemoteCandidates(A)),l&&0!==c||("new"===C.state&&C.start(S,P,"controlling"),"new"===T.state&&T.start(O)),!re(g.localCapabilities,g.remoteCapabilities).codecs.filter((function(e){return"rtx"===e.name.toLowerCase()})).length&&g.sendEncodingParameters[0].rtx&&delete g.sendEncodingParameters[0].rtx,s._transceive(g,"sendrecv"===f||"recvonly"===f,"sendrecv"===f||"sendonly"===f),!I||"sendrecv"!==f&&"sendonly"!==f?delete g.rtpReceiver:(b=I.track,v?(o[v.stream]||(o[v.stream]=new e.MediaStream),r(b,o[v.stream]),a.push([b,I,o[v.stream]])):(o.default||(o.default=new e.MediaStream),r(b,o.default),a.push([b,I,o.default])))}}else{(g=s.transceivers[c]||s._createTransceiver(p)).mid=R,g.iceGatherer||(g.iceGatherer=s._createIceGatherer(c,l)),A.length&&"new"===g.iceTransport.state&&(!D||l&&0!==c?A.forEach((function(e){ne(g.iceTransport,e)})):g.iceTransport.setRemoteCandidates(A)),k=e.RTCRtpReceiver.getCapabilities(p),t<15019&&(k.codecs=k.codecs.filter((function(e){return"rtx"!==e.name}))),E=g.sendEncodingParameters||[{ssrc:1001*(2*c+2)}];var M,x=!1;if("sendrecv"===f||"sendonly"===f){if(x=!g.rtpReceiver,I=g.rtpReceiver||new e.RTCRtpReceiver(g.dtlsTransport,p),x)b=I.track,v&&"-"===v.stream||(v?(o[v.stream]||(o[v.stream]=new e.MediaStream,Object.defineProperty(o[v.stream],"id",{get:function(){return v.stream}})),Object.defineProperty(b,"id",{get:function(){return v.track}}),M=o[v.stream]):(o.default||(o.default=new e.MediaStream),M=o.default)),M&&(r(b,M),g.associatedRemoteMediaStreams.push(M)),a.push([b,I,M])}else g.rtpReceiver&&g.rtpReceiver.track&&(g.associatedRemoteMediaStreams.forEach((function(t){var r=t.getTracks().find((function(e){return e.id===g.rtpReceiver.track.id}));r&&function(t,r){r.removeTrack(t),r.dispatchEvent(new e.MediaStreamTrackEvent("removetrack",{track:t}))}(r,t)})),g.associatedRemoteMediaStreams=[]);g.localCapabilities=k,g.remoteCapabilities=L,g.rtpReceiver=I,g.rtcpParameters=N,g.sendEncodingParameters=E,g.recvEncodingParameters=y,s._transceive(s.transceivers[c],!1,x)}}})),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(se("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=ee.writeSessionBoilerplate(r._sdpSessionId,r._sdpSessionVersion++);r.transceivers.forEach((function(i,n){var s=i.track,o=i.kind,a=i.mid||ee.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+=te(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="+ee.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(se("InvalidStateError","Can not call createAnswer after close"));if("have-remote-offer"!==r.signalingState&&"have-local-pranswer"!==r.signalingState)return Promise.reject(se("InvalidStateError","Can not call createAnswer in signalingState "+r.signalingState));var i=ee.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=ee.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=re(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+=te(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(se("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(se("OperationError","Can not add ICE candidate"));if(a.rejected)return i();var c=Object.keys(e.candidate).length>0?ee.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)&&!ne(a.iceTransport,c))return n(se("OperationError","Can not add ICE candidate"));var d=e.candidate.trim();0===d.indexOf("a=")&&(d=d.substr(2)),(t=ee.getMediaSections(r._remoteDescription.sdp))[s]+="a="+(c.type?d:"end-of-candidates")+"\r\n",r._remoteDescription.sdp=ee.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=ee.getMediaSections(r._remoteDescription.sdp))[u]+="a=end-of-candidates\r\n",r._remoteDescription.sdp=ee.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 se("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 ae(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 ce(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 de(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=oe(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&&x("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 ue(e){e.RTCRtpSender&&!("replaceTrack"in e.RTCRtpSender.prototype)&&(e.RTCRtpSender.prototype.replaceTrack=e.RTCRtpSender.prototype.setTrack)}var le=Object.freeze({__proto__:null,shimPeerConnection:de,shimReplaceTrack:ue,shimGetUserMedia:ae,shimGetDisplayMedia:ce});function he(e,t){const r=e&&e.navigator,i=e&&e.MediaStreamTrack;if(r.getUserMedia=function(e,t,i){x("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 pe(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 _e(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 me(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 fe(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}),N(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ve(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){x("removeStream","removeTrack"),this.getSenders().forEach((t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)}))})}function Re(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function ge(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 Se(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 Ce(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 Te(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:pe,shimPeerConnection:_e,shimSenderGetStats:me,shimReceiverGetStats:fe,shimRemoveStream:ve,shimRTCDataChannel:Re,shimAddTransceiver:ge,shimGetParameters:Se,shimCreateOffer:Ce,shimCreateAnswer:Te,shimGetUserMedia:he,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 Ee(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 ye(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 ke(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 be(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(Pe(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,r,i){t.mediaDevices.getUserMedia(e).then(r,i)}.bind(t))}function Pe(e){return e&&void 0!==e.video?Object.assign({},e,{video:w(e.video)}):e}function Oe(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")?(x("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 Le(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 Ne(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 De(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var Ae=Object.freeze({__proto__:null,shimLocalStreamsAPI:Ee,shimRemoteStreamsAPI:ye,shimCallbacksAPI:ke,shimGetUserMedia:be,shimConstraints:Pe,shimRTCIceServerUrls:Oe,shimTrackEventTransceiver:Le,shimCreateOfferLegacy:Ne,shimAudioContext:De});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=ee.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,N(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function xe(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=ee.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=ee.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=ee.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 Ue(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},N(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function we(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 $e(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 je(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 Ve=Object.freeze({__proto__:null,shimRTCIceCandidate:Me,shimMaxMessageSize:xe,shimSendThrowTypeError:Ue,shimConnectionState:we,removeExtmapAllowMixed:$e,shimAddIceCandidateNullOrEmpty:je});const He=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=L(r.userAgent,/Firefox\/(\d+)\./,1);else if(r.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection&&!e.RTCIceGatherer)t.browser="chrome",t.version=L(r.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(r.mediaDevices&&r.userAgent.match(/Edge\/(\d+).(\d+)$/))t.browser="edge",t.version=L(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=L(r.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),n={browserDetails:i,commonShim:Ve,extractVersion:L,disableLog:D,disableWarnings:A};switch(i.browser){case"chrome":if(!Q||!q||!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=Q,je(e,i),H(e,i),B(e),q(e,i),K(e),Y(e,i),F(e),G(e),J(e),z(e,i),Me(e),we(e),xe(e,i),Ue(e),$e(e,i);break;case"firefox":if(!Ie||!_e||!t.shimFirefox)return r("Firefox shim is not included in this adapter release."),n;r("adapter.js shimming firefox."),n.browserShim=Ie,je(e,i),he(e,i),_e(e,i),pe(e),ve(e),me(e),fe(e),Re(e),ge(e),Se(e),Ce(e),Te(e),Me(e),we(e),xe(e,i),Ue(e);break;case"edge":if(!le||!de||!t.shimEdge)return r("MS edge shim is not included in this adapter release."),n;r("adapter.js shimming edge."),n.browserShim=le,ae(e),ce(e),de(e,i),ue(e),xe(e,i),Ue(e);break;case"safari":if(!Ae||!t.shimSafari)return r("Safari shim is not included in this adapter release."),n;r("adapter.js shimming safari."),n.browserShim=Ae,je(e,i),Oe(e),Ne(e),ke(e),Ee(e),ye(e),Le(e),be(e),De(e),Me(e),xe(e,i),Ue(e),$e(e,i);break;default:r("Unsupported browser!")}return n}({window:"undefined"==typeof window?void 0:window});var Be,Ke,Fe;!function(e){e.FPS_10="FPS_10",e.FPS_15="FPS_15",e.FPS_24="FPS_24",e.FPS_30="FPS_30"}(Be||(Be={})),function(e){e.W176_H132="W176_H132",e.W176_H144="W176_H144",e.W256_H144="W256_H144",e.W320_H180="W320_H180",e.W240_H240="W240_H240",e.W320_H240="W320_H240",e.W480_H360="W480_H360",e.W640_H360="W640_H360",e.W480_H480="W480_H480",e.W640_H480="W640_H480",e.W720_H480="W720_H480",e.W1280_H720="W1280_H720",e.W1920_H1080="W1920_H1080"}(Ke||(Ke={})),function(e){e[e.AUDIO_ONLY=0]="AUDIO_ONLY",e[e.VIDEO_ONLY=1]="VIDEO_ONLY",e[e.AUDIO_VIDEO=2]="AUDIO_VIDEO"}(Fe||(Fe={}));const Ge={[Ke.W176_H132]:{width:176,height:132,maxBitrate:150,minBitrate:80},[Ke.W176_H144]:{width:176,height:144,maxBitrate:160,minBitrate:80},[Ke.W256_H144]:{width:256,height:144,maxBitrate:240,minBitrate:120},[Ke.W320_H180]:{width:320,height:180,maxBitrate:280,minBitrate:120},[Ke.W240_H240]:{width:240,height:240,maxBitrate:280,minBitrate:120},[Ke.W320_H240]:{width:320,height:240,maxBitrate:400,minBitrate:120},[Ke.W480_H360]:{width:480,height:360,maxBitrate:650,minBitrate:150},[Ke.W640_H360]:{width:640,height:360,maxBitrate:800,minBitrate:180},[Ke.W480_H480]:{width:480,height:480,maxBitrate:800,minBitrate:180},[Ke.W640_H480]:{width:640,height:480,maxBitrate:900,minBitrate:200},[Ke.W720_H480]:{width:720,height:480,maxBitrate:1e3,minBitrate:200},[Ke.W1280_H720]:{width:1280,height:720,maxBitrate:2200,minBitrate:250},[Ke.W1920_H1080]:{width:1920,height:1080,maxBitrate:4e3,minBitrate:400}},Je=(e,t)=>{const r=e*t;let i=Number.MAX_VALUE,n=null;for(const e in Ge){const t=Ge[e],s=Math.abs(t.width*t.height-r);s<i&&(n=t,i=s)}return n},We={10:1,15:1,24:1.5,30:1.5},Ye=e=>{let t=Number.MAX_VALUE,r=1;for(const i in We){const n=Math.abs(e-parseInt(i));n<t&&(t=n,r=We[i])}return r},qe={getCameras:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind))})),getMicrophones:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind))})),getSpeakers:()=>C(void 0,void 0,void 0,(function*(){return(yield navigator.mediaDevices.enumerateDevices()).filter((e=>"audiooutput"===e.kind))}))};class ze extends t{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(){T.info(`set ${this._id} enabled: false`),this._setLocalMuted(!0)}unmute(){T.info(`set ${this._id} enabled: true`),this._setLocalMuted(!1)}isLocalMuted(){return this._localMuted}isMCUTrack(){return Boolean(this._roomId)}isOwnerMuted(){return this._remoteMuted}play(e,t){return C(this,void 0,void 0,(function*(){if(!this._msTrack)return T.warn(`the track is not ready to play -> id: ${this._id}`),{code:I.TRACK_NOT_READY};if("ended"===this._msTrack.readyState&&T.warn(`the track's readyState is 'ended' -> id: ${this._id}`),null==t?void 0:t.volume){if(!r(null==t?void 0:t.volume))return T.error(`${null==t?void 0:t.volume} is not a number, the valid range of options.volume is 0-100`),{code:I.PARAMS_ERROR};(null==t?void 0:t.volume)<0&&(t.volume=0,T.warn("the valid range of options.volume is 0-100, the value of volume has been set 0")),(null==t?void 0:t.volume)>100&&(t.volume=100,T.warn("the valid range of options.volume is 0-100, the value of volume has been set 100"))}if(null==t?void 0:t.audioDeviceId){if(!(yield qe.getSpeakers()).map((e=>e.deviceId)).includes(t.audioDeviceId))return T.error(`the options.audioDeviceId is invalid --\x3e ${t.audioDeviceId}`),{code:I.PARAMS_ERROR}}const i=this.isVideoTrack();if(i&&(!e||!(e instanceof HTMLVideoElement)))return T.error(`the video track need an <video> to play -> id: ${this._id}`),{code:I.VIDEO_TRACK_MISS_MEDIA_ELEMENT};this._element=i?e: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;T.debug(`HTMLMediaElement onloadstart -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.ondurationchange=e=>{var t;T.debug(`HTMLMediaElement ondurationchange -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadedmetadata=e=>{var t;T.debug(`HTMLMediaElement onloadedmetadata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onloadeddata=e=>{var t;T.debug(`HTMLMediaElement onloadeddata -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.onabort=e=>{var t;T.info(`HTMLMediaElement onabort -> id: ${null===(t=e.target)||void 0===t?void 0:t.id}, trackId: ${this._id}`)},this._element.oncanplay=e=>{var t;T.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 r=Math.floor(100*(null===(t=e.target)||void 0===t?void 0:t.volume));T.info(`HTMLMediaElement onvolumechange -> volume: ${r}, trackId: ${this._id}`)},this._element.srcObject=this._msStream,this._element.autoplay=!0,i&&(this._element.playsInline=!0,this._element.x5PlaysInline=!0,this._element.webkitPlaysInline=!0),i||!(null==t?void 0:t.volume)&&0!==(null==t?void 0:t.volume)||(this._element.volume=(null==t?void 0:t.volume)/100);try{(null==t?void 0:t.audioDeviceId)&&!i?yield this._element.setSinkId(t.audioDeviceId):this._element.play()}catch(e){return"No permission to use requested device"===e.message?(T.error(`setSinkId failed -> ${e.message}`),{code:I.NO_PERMISSION_TO_USE_REQUESTED_DEVICE}):(T.error(e),{code:I.TRACK_PLAY_ERROR})}return{code:I.SUCCESS}}))}__innerDestroy(){this.__innerSetMediaStreamTrack(void 0)}__releaseMediaElement(){this._element&&(this._element.remove(),this._element.srcObject=null)}}class Qe extends ze{constructor(e,t,r,i){super(e,t,r,!0),this._isPublished=!1,this.__innerSetMediaStreamTrack(i),i.onended=()=>{i.onended=null,this.emit(Qe.EVENT_LOCAL_TRACK_END,this),this.removeAll(Qe.EVENT_LOCAL_TRACK_END)}}_setLocalMuted(e){const t=this._localMuted!==e;super._setLocalMuted(e),this._remoteMuted=this._localMuted,t&&this.emit(Qe.__INNER_EVENT_MUTED_CHANGE__,this)}__innerSetPublished(e){this._isPublished=e}isPublished(){return this._isPublished}destroy(){var e;T.info(`track is destroyed -> trackId: ${this.getTrackId()}`),null===(e=this._msTrack)||void 0===e||e.stop(),super.__innerDestroy(),this.isAudioTrack()&&super.__releaseMediaElement(),this.emit(Qe.__INNER_EVENT_DESTROY__,this)}setBitrate(e=0,t=0,i=0){!r(e)||!r(t)||!r(i)||e<=0||t<=0||e<t?T.error("setBitrate params error ->"):this._bitrateInfo={max:e,min:t,start:i}}getBitrate(){var e,t;const{min:r,max:i}=this._msTrack?mt(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}}}Qe.EVENT_LOCAL_TRACK_END="local-track-end",Qe.__INNER_EVENT_MUTED_CHANGE__="inner-muted-change",Qe.__INNER_EVENT_DESTROY__="inner-destroy";class Xe extends Qe{constructor(e,t,r){super(e,t,"audio",r)}setBitrate(e,t,r){T.warn("`setBitrate` invalid for audio track")}getBitrate(){return{start:32,max:32,min:32}}}class Ze extends Qe{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 et extends Qe{constructor(e,t,r,i,n){super(e,t,r,i),this._resource=n,et.__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(),et.__innerRemoveMapping(this.getTrackId(),this._resource),super.destroy()}}et._mapping=new Map;class tt extends et{constructor(e,t,r,i){super(e,t,"video",r,i)}}class rt extends et{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:I.SUCCESS})}}class it extends Xe{}class nt extends Ze{}class st extends Ze{}class ot extends ze{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 ot{constructor(e,t,r){super(e,t,"audio",r)}}class ct extends ot{constructor(e,t,r){super(e,t,"video",r)}}const dt=(e,t)=>({name:e,content:JSON.stringify({uris:t,ignore:!0})}),ut=e=>JSON.stringify(e),lt=e=>/^[a-zA-Z\d-=]+$/g.test(e),ht="http:"!==location.protocol||["localhost","127.0.0.1"].includes(location.hostname),pt=e=>{if(void 0===e)return 0;if(r(e))return e;const t=e;return t.exact||t.ideal||t.max||0},_t=e=>{const t=e.getConstraints();return{width:pt(t.width),height:pt(t.height),frameRate:pt(t.frameRate)}},mt=e=>{const{width:t,height:r,frameRate:i}=_t(e),n=Je(t,r),s=Ye(i);return{min:n.minBitrate*s,max:n.maxBitrate*s}},ft=e=>[e.msid,e.mediaType].join("_"),vt=e=>{const t=e.split("_");return{mediaType:parseInt(t.pop()),tag:t.pop(),userId:t.join("_")}},Rt=(e,t)=>[e,t].join("_"),gt=e=>e.map((e=>Object.assign({},e))),St=(e,t,r=!1)=>{e=e.slice();const i=[],n=[],s=[];return t.forEach((t=>{const n=ft(t);let o=e.findIndex((e=>ft(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}},Ct=()=>{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},Tt=e=>{const[t,r]=e.split("_").map((e=>parseInt(e.replace(/[^\d]/g,""))));return{width:t,height:r}},It=e=>!!Ke[e],Et=e=>!!Be[e],yt=e=>parseInt(e.replace("FPS_","")),kt=(()=>{const{browser:e,version:t,supportsUnifiedPlan:r}=He.browserDetails;return{browser:e,version:t,supportsUnifiedPlan:!1!==r}})();function bt(){return"captureStream"in HTMLMediaElement.prototype||"mozCaptureStream"in HTMLMediaElement.prototype}function Pt(){return"mediaDevices"in navigator&&"getDisplayMedia"in navigator.mediaDevices}const Ot=e=>"[object Null]"===Object.prototype.toString.call(e),Lt=e=>1===e.type,Nt=(e,t)=>{const r={},i=Object.keys(e.users);return i.length&&i.forEach((i=>{const n=[],s=e.users[i];if(s.extra){const e=JSON.parse(s.extra).roomId;if(t!==e)return}if(s.uris)try{n.push(...JSON.parse(s.uris))}catch(e){T.warn(`invalid user data -> userId: ${i}, userData: ${s}`)}r[i]=n})),r};var Dt,At;!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",e.PK_INVITE="RCRTC:invite",e.PK_INVITE_TIMEOUT="RCRTC:inviteTimeout",e.PK_CANCEL_INVITE="RCRTC:cancelInvite",e.PK_INVITE_ANSWER="RCRTC:answerInvite",e.PK_END="RCRTC:endInvite",e.OTHER_ROOM_OFFLINE="RCRTC:otherRoomOffline"}(Dt||(Dt={})),function(e){e.SUCCESS="Success",e.FAIL="Fail"}(At||(At={}));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 C(this,void 0,void 0,(function*(){this._timer||(this._timer=setInterval(this._loop.bind(this),this._gap))}))}_loop(){var e,t,r;return C(this,void 0,void 0,(function*(){const n=yield new Promise((e=>{this._context.rtcPing(this._roomId,this._roomMode).then(e).catch((t=>{T.error(`rtcping receive unknown error -> ${t}`),e(i.UNKNOWN)})),setTimeout(e,1e4,i.TIMEOUT)})),s=Date.now();if(n===i.SUCCESS)return this._latestTimestamp=s,void(null===(e=this.onPingResult)||void 0===e||e.call(this,At.SUCCESS));null===(t=this.onPingResult)||void 0===t||t.call(this,At.FAIL),T.warn(`rtcping failed -> code: ${n}`),(40003===n||s-this._latestTimestamp>6e4)&&(this.stop(),null===(r=this.onFailed)||void 0===r||r.call(this,40003===n))}))}stop(){this._timer&&(clearInterval(this._timer),this._timer=null)}}var xt;!function(e){e[e.NORMAL=1]="NORMAL",e[e.TINY=2]="TINY"}(xt||(xt={}));const Ut=(e,t)=>Math.round(8*t/e),wt=(e,t=2)=>{const r=10**t;return Math.round(e*r)/r},$t=(e,t=2)=>{e>1&&(e/=32767);const r=10**t;return Math.ceil(e*r)},jt=(e,t,r,i)=>{if(0===t)return 0;if(!r||!i)return wt(e/t,3);const n=t-i;if(0===n)return 0;const s=e-r;return s<0||n<0?0:wt(s/n,3)},Vt=e=>{const{jitter:t,rtt:r,packetsLostRate:i}=e;return!Ot(t)||!Ot(r)||0!==i};class Ht{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 Ut(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 Ut(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=jt(t,r,n,s),this._latestPacketsSent[e].packetsLost=t,this._latestPacketsSent[e].packetsSent=n===t?s:r}else i=jt(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=jt(t,r+t,n,s+n)}else i=jt(t,r);return this._latestPacketsRecv[e]={packetsLost:t,packetsRecv:r},i}clearLatestpacketsSent(e){e.forEach((e=>{if(parseInt(e.split("_").pop())===Fe.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 h=null==o?void 0:o.split("\r\nm="),p=null==h?void 0:h.filter((e=>e.includes(`a=ssrc:${i}`)))[0],_=null==p?void 0:p.match(a);return l=_?_[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 Bt extends Ht{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:h,bytesSent:p,trackId:_,encoderImplementation:m,pliCount:f,nackCount:v,firCount:R}=o;if(!_)return;let{framesPerSecond:g,frameWidth:S,frameHeight:C}=o;"video"!==c||S||C||g||(S=e[_].frameWidth,C=e[_].frameHeight,g=u?e[u].framesPerSecond:null);const T=e[l];let I=null,E=null,y=0;T&&(I=T.jitter,E=T.roundTripTime,y=T.packetsLost),n+=y;const k=this.getResourceIdByParseSdp(o),b=u?e[u].audioLevel:e[_].audioLevel;let P=null;!this._latestPacketsSent[k]&&(this._latestPacketsSent[k]={}),T?P=this.updateSenderPacketsLost(k,y,h):this._latestPacketsSent[k].crtPacketsSent=h;let O=this.updateBytesSent(k,p,r);O<0&&(O=0),s+=O,t.senders.push({id:a,trackId:k,kind:c,packetsLostRate:P,remoteResource:!1,audioLevel:b||0===b?$t(b):null,frameWidth:S,frameHeight:C,frameRate:g,bitrate:O,jitter:I?Math.round(1e3*I):I,rtt:E,encoderImplementation:m,pliCount:f,nackCount:v,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&&!Vt(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:h,kind:p,codecImplementationName:_,nackCount:m,pliCount:f}=s;if(!a)return;let{frameWidth:v,frameHeight:R,audioLevel:g}=s;"video"===p?v||R||(v=e[a].frameWidth,R=e[a].frameHeight):g||(g=e[a].audioLevel),n+=c;const S=this.getResourceIdByParseSdp(s),C=this.updateReceiverPacketsLost(S,c,d);let T=this.updateBytesRecv(S,l,r);T<0&&(T=0),o+=T,t.receivers.push({trackId:S,kind:p,packetsLostRate:C,remoteResource:!0,audioLevel:g||0===g?$t(g):null,frameWidth:v,frameHeight:R,frameRate:h,bitrate:T,jitter:u?Math.round(1e3*u):0,codecImplementationName:_,nackCount:m,pliCount:f,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,h=e[u],{ip:p,port:_,networkType:m}=h,f=e[l],{ip:v,port:R,protocol:g}=f;t.iceCandidatePair={IP:p,port:_,networkType:m,remoteIP:v,remotePort:R,protocol:g,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?$t(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?$t(s):null})})),t}}class Kt extends Ht{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:h,pliCount:p,remoteId:_}=a,{jitter:m,roundTripTime:f,packetsLost:v}=_?e[_]:{jitter:null,roundTripTime:null,packetsLost:0},R=this.getResourceIdByParseSdp(a);i+=v;let g=null;!this._latestPacketsSent[R]&&(this._latestPacketsSent[R]={}),_?g=this.updateSenderPacketsLost(R,v,d):this._latestPacketsSent[R].crtPacketsSent=d;let S=0;"video"===o?u&&(S=Math.floor(u/1e3)):S=this.updateBytesSent(R,c,t),S<0&&(S=0),n+=S,r.senders.push({trackId:R,kind:o,packetsLostRate:g,remoteResource:!1,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(l),bitrate:S,jitter:m?Math.round(1e3*m):null,rtt:f,encoderImplementation:null,pliCount:p,nackCount:h,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&&Vt(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:h,nackCount:p,pliCount:_}=a,m=this.getResourceIdByParseSdp(a);i+=n;const f=this.updateReceiverPacketsLost(m,n,c);let v=0;"video"===l?h&&(v=Math.floor(h/1e3)):v=this.updateBytesRecv(m,o,t),v<0&&(v=0),s+=v,r.receivers.push({trackId:m,kind:l,packetsLostRate:f,remoteResource:!0,audioLevel:null,frameWidth:null,frameHeight:null,frameRate:Math.floor(u),bitrate:v,jitter:d?Math.round(1e3*d):null,codecImplementationName:null,nackCount:p,pliCount:_,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:h}=d;r.iceCandidatePair={IP:o,port:c,networkType:null,remoteIP:u,remotePort:l,protocol:h,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 Ft extends Ht{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:h,encoderImplementation:p,pliCount:_,nackCount:m,firCount:f}=n;if(!h)return;const{audioLevel:v,frameHeight:R,frameWidth:g}=e[h];let S=this.updateBytesSent(o,l,r);S<0&&(S=0),s+=S,t.senders.push({trackId:o,kind:a,packetsLostRate:null,remoteResource:!1,audioLevel:v||0===v?$t(v):null,frameWidth:g,frameHeight:R,frameRate:null,bitrate:S,jitter:null,rtt:null,encoderImplementation:p,pliCount:_,nackCount:m,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:h,nackCount:p,pliCount:_}=s,m=this.getResourceIdByParseSdp(s);if(!a)return;const{frameHeight:f,frameWidth:v,audioLevel:R}=e[a];n+=c;const g=this.updateReceiverPacketsLost(m,c,d);let S=this.updateBytesRecv(m,l,r);S<0&&(S=0),o+=S,t.receivers.push({trackId:m,kind:h,packetsLostRate:g,remoteResource:!0,audioLevel:R||0===R?$t(R):null,frameWidth:v,frameHeight:f,frameRate:null,bitrate:S,jitter:u,codecImplementationName:null,nackCount:p,pliCount:_,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,h=e[u],{address:p,port:_}=h,m=e[l],{address:f,port:v,protocol:R}=m;t.iceCandidatePair={IP:p||null,port:_,networkType:null,remoteIP:f,remotePort:v,protocol:R,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?$t(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?$t(o):null})})),t}}class Gt{constructor(e){this._peer=e,this._outboundStreams={}}static setSdpSemantics(e){const{browser:t,version:r,supportsUnifiedPlan:i}=kt;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 Gt._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}=_t(r);e.push({trackId:r.id,simulcast:i?xt.TINY:xt.NORMAL,resolution:`${n}x${s}`})}return e}setRemoteAnswer(e){return C(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 T.error(e),I.SET_REMOTE_DESCRIPTION_FAILED}return I.SUCCESS}))}getStatParsr(e,t){return/chrome/i.test(kt.browser)?new Bt(e,t):/Firefox/i.test(kt.browser)?new Kt(e,t):/Safari/i.test(kt.browser)?new Ft(e,t):null}}class Jt extends Gt{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 C(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 Wt extends Gt{constructor(){super(...arguments),this._sendTransceiver={},this._localTracks={},this._recvAudio=[],this._recvVideo=[],this._recvTransceiver={},this._subedTracks=[]}setBitrate(e,t,r){T.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}=vt(e);this._recvTransceiver[e]=t;const i=r===Fe.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 C(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)&&(T.warn(`answer sdp invalid -> ${JSON.stringify(e)}`),e=e.replace(t,"\r\n")),super.setRemoteAnswer(e)}}class Yt extends t{constructor(e,t){super(),this._reTryExchange=e,this._polarisReport=t,this.pubLocalTracks={},this._reTryExchangeTimer=null,this._reportStatsTimer=null,this._reportListener=null;const r=Gt.getSdpSemantics(),i=this._rtcPeerConn=new RTCPeerConnection({sdpSemantics:r});this._sdpStrategy="plan-b"===r?new Jt(i):new Wt(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(){T.info(`onconnectionstatechange -> ${this._rtcPeerConn.connectionState}`)}_onICEConnectionStateChange(){var e,t;T.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||(T.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){T.error("onICEConnectionStateChange error",e)}}_onTrackReady(e){if(!e.streams.length)return;const t=[e.streams[0].id,"audio"===e.receiver.track.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_");this._updateRecvTransceiverMap(t,e.transceiver),this.emit(Yt.__INNER_EVENT_TRACK_READY__,e)}setBitrate(e,t,r){return C(this,void 0,void 0,(function*(){this._sdpStrategy.setBitrate(e,t,r)}))}createOffer(e){return C(this,void 0,void 0,(function*(){const t=yield this._sdpStrategy.createOffer(e);return T.debug(`offer -> ${JSON.stringify(t.sdp)}`),t}))}setRemoteAnswer(e){return C(this,void 0,void 0,(function*(){return T.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(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Qe.__INNER_EVENT_DESTROY__,this._onLocalTrackDestroied,this),e.on(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.on(Qe.__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(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),e.off(Qe.__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(Qe.__INNER_EVENT_MUTED_CHANGE__,e)}_onLocalTrackDestroied(e){this.emit(Qe.__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,t;return C(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);return null===(t=this.reportParser)||void 0===t?void 0:t.formatRCRTCStateReport(i)}))}getAudioLevelReportData(){var e,t;return C(this,void 0,void 0,(function*(){const r=yield this._rtcPeerConn.getStats(),i=null===(e=this.reportParser)||void 0===e?void 0:e.parseRTCStatsReport(r);if(!i)return[];return null===(t=this.reportParser)||void 0===t?void 0:t.getAudioLevelList(i)}))}_reportHandle(){var e,t,r;return C(this,void 0,void 0,(function*(){const i=yield this._getStatsData();if(!i)return;(i.senders.length||i.receivers.length)&&(null===(e=this._polarisReport)||void 0===e||e.sendR3R4Data(i));const n=this._createRCRTCStateReport(i);null===(r=null===(t=this._reportListener)||void 0===t?void 0:t.onStateReport)||void 0===r||r.call(t,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 qt,zt,Qt,Xt,Zt;Yt.__INNER_EVENT_TRACK_READY__="inner-track-ready",function(e){e[e.DISABLE=0]="DISABLE",e[e.ENABLE=1]="ENABLE"}(qt||(qt={})),function(e){e[e.MeetingOrAnchor=1]="MeetingOrAnchor",e[e.Audience=2]="Audience"}(zt||(zt={}));class er{constructor(e,t,r,i,n=zt.MeetingOrAnchor){this._context=e,this._runtime=t,this._roomId=r,this._crtRTCRoom=i,this._userRole=n}_send(e){this._context.getConnectionStatus()===n.CONNECTED&&this._context.setRTCState(this._roomId,e)}_getClientID(){const e="uuid";let t=this._runtime.localStorage.getItem(e);return t||(t=Ct(),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())===Fe.AUDIO_ONLY?"audio":"video",n=r.pop();t=[r.join("_"),n,e,i].join("_")}else{const e=parseInt(r.pop())===Fe.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,h=this._context.getCurrentId();let p=`R3\t${n}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`,_=`R4\t${s}\t-1\t-1\t-1\t${o}\t${a}\t${c}\t${d}\t${u}\t${l}\t${h}\r`;const m=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:h,pliCount:p,rtt:_,googFirsSent:m,encoderImplementation:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||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:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsSent:m,samplingRate:n,googRenderDelayMs:u,encoderImplementation:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getLocalTrack(R))||void 0===t?void 0:t.isLocalMuted())?qt.DISABLE:qt.ENABLE}})),f=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:h,pliCount:p,rtt:_,googFirsReceived:m,codecImplementationName:f}=e,v=this._getPolarisTrackId(r),R=this._getRealResourceId(r);return{trackId:v,googCodecName:f||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:h||0===h?h:-1,pliCount:p||0===p?p:-1,rtt:_||-1,googFirsReceived:m,samplingRate:n,googRenderDelayMs:u,codecImplementationName:f||String(-1),trackState:(null===(t=this._crtRTCRoom.getRemoteTrack(R))||void 0===t?void 0:t.isLocalMuted())?qt.DISABLE:qt.ENABLE}}));p+=m.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(p+`\r${this._userRole}`),_+=f.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(_+`\r${this._userRole}`)}sendR1(){const e=`R1\t5.3.5\t${this._context.getCoreVersion()}\tweb\t${navigator.platform}\t-1\t${kt.browser}\t${kt.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"}(Qt||(Qt={})),function(e){e.BEGIN="begin",e.END="end"}(Xt||(Xt={}));class tr{constructor(e){this._room=e,this._audioLevelChangeHandler=null,this._timer=null,this._pc=this._room.__getPC()}_audioLevelReport(){return C(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?T.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)}}!function(e){e[e.ANCHOR=1]="ANCHOR",e[e.AUDIENCE=2]="AUDIENCE"}(Zt||(Zt={}));const rr=e=>e instanceof ze?e.getTrackId():e.track.getTrackId();class ir{constructor(e,t,r,i,n,s,o,a,c,d){this._context=e,this._runtime=t,this._roomId=r,this._roomMode=n,this._service=s,this._initOptions=o,this._ntfClearRoomItem=a,this._isMainRoom=d,this._remoteTracks={},this._subscribedList=[],this._destroyed=!1,this.msgTaskQueue=new y,this._appListener=null,this._onRecvPKMsg=null,this._token=i.token,this._sessionId=i.sessionId,this._roomResources=c?{}:Nt(i,this._roomId),this._initRemoteTracks();const u=this._context.getCurrentId(),l=this._roomResources[u]=this._roomResources[u]||[];T.debug(`room data -> ${JSON.stringify(this._roomResources)}`),l.length>0&&b((()=>this._unpublishPrev(l))),c&&this._afterChangedRole(i),this._pinger=new Mt(r,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 er(this._context,this._runtime,this._roomId,this),this._polarisReport.sendR1(),this._pc=new Yt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this._pc.on(Qe.__INNER_EVENT_MUTED_CHANGE__,this._onLocalTrackMuted,this),this._pc.on(Qe.__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=ft(e),{tag:r,userId:i,mediaType:n}=vt(t),s=n===Fe.AUDIO_ONLY?new at(r,i):new ct(r,i);s.__innerSetRemoteMuted(0===e.state),this._remoteTracks[t]=s}))}}_handlePingResult(e){this._callAppListener("onPing",e)}setBitrate(e,t,i){T.warn("`RCAbstractRoom.setBitrate` will be deprecated, use `RCLocalTrack.setBitrate` instead."),s("max",e,(e=>r(e)&&e>Math.max(t||1,200)),!0),s("min",t,(t=>r(t)&&t>=1&&(!r(e)||t<e)),!0),s("start",i,(i=>r(i)&&i>t&&i<=e)),this._pc.setBitrate(e,t,i)}_onTrackReady(e){const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):T.warn(`cannot found remote track ${r.id}`)}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_onUserUnpublish(e){return C(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(e){return C(this,void 0,void 0,(function*(){const t=e.slice();e.length=0,T.info(`unpublish uris prev login: ${JSON.stringify(t)}`);const r=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.UNPUBLISH,t),ut([]),Dt.TOTAL_CONTENT_RESOURCE,ut([]));r!==i.SUCCESS?T.error(`unpublish prev uris failed -> code: ${r}`):T.debug("unpublish uris prev login succeed")}))}__parseInnerMessage(e){const{targetId:t,conversationType:r}=e;if(r!==o.RTC_ROOM)return!1;if(t!==this._roomId)return!0;T.info(`recv inner msg -> message: ${JSON.stringify(e)} | roomid: ${this._roomId}`);const i=e.content;switch(e.messageType){case Dt.KICK:this._kickoff(!0,i);break;case Dt.STATE:this.msgTaskQueue.push((()=>this._stateHandle(i)));break;case Dt.MODIFY:case Dt.PUBLISH:case Dt.UNPUBLISH:case Dt.TOTAL_CONTENT_RESOURCE:this.msgTaskQueue.push((()=>this._resourceHandle(i,e.messageType,e.senderUserId)));break;case Dt.ROOM_NOTIFY:this._callAppListener("onRoomAttributeChange",e.messageType,e.content);break;case Dt.USER_NOTIFY:T.warn(`TODO: ${Dt.USER_NOTIFY}`);break;case Dt.PK_INVITE:case Dt.PK_CANCEL_INVITE:case Dt.PK_INVITE_TIMEOUT:case Dt.PK_INVITE_ANSWER:case Dt.PK_END:this._onRecvPKMsg&&this._onRecvPKMsg(e);break;case Dt.OTHER_ROOM_OFFLINE:break;default:this._callAppListener("onMessageReceive",e.messageType,e.content,e.senderUserId,e.messageUId)}return!0}_kickoff(e,t){let r;T.warn(`onKickOff -> byServer: ${e}`),this._ntfClearRoomItem(),this._leaveHandle(!e),e&&((null==t?void 0:t.users)||[]).forEach((e=>{e.userId===this._context.getCurrentId()&&(r=e.type)})),this._callAppListener("onKickOff",e,r)}_rtcpeerClosed(){this._ntfClearRoomItem(),this._leaveHandle(!0),this._callAppListener("onRTCPeerConnectionCloseByException")}_resourceHandle(e,t,r){return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return void T.warn(`room has been destroyed. -> roomId: ${this._roomId}`);const{uris:i,ignore:n}=e;if(n||!i)return;const s=[],o=[],a=[];let c;const d=this._roomResources[r]||(this._roomResources[r]=[]);switch(t){case Dt.MODIFY:a.push(...i);break;case Dt.PUBLISH:s.push(...i);break;case Dt.UNPUBLISH:o.push(...i);break;case Dt.TOTAL_CONTENT_RESOURCE:c=St(d,i),s.push(...c.publishedList),o.push(...c.unpublishedList),a.push(...c.modifiedList)}if(s.length>0){const e=d.map(ft),t=[],r=[];if(s.forEach((i=>{const n=ft(i),s=e.indexOf(n),{userId:o,tag:a,mediaType:c}=vt(n);s>-1?d[s]=i:d.push(i);let u=this._remoteTracks[n];u?u.isSubscribed()&&t.push(u):(u=c===Fe.AUDIO_ONLY?new at(a,o):new ct(a,o),this._remoteTracks[n]=u,r.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));T.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield b((()=>this.__subscribe(t,!0)));r!==I.SUCCESS&&T.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._onTrackPublish(r)}if(o.length>0){const e=o.map(ft);for(let t=d.length-1;t>=0;t-=1){const r=d[t];e.includes(ft(r))&&d.splice(t,1)}const t=o.map((e=>{const t=ft(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t)}if(a.length>0){const e=d.map(ft);for(let t=0;t<a.length;t+=1){const r=a[t],i=ft(r),n=e.indexOf(i);d[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 t;return C(this,void 0,void 0,(function*(){const{users:r}=e;if(0===r.length)return;for(let e=0;e<r.length;e++){const t=r[e];if(t.extra&&t.extra.roomId!==this._roomId)return;if(1==+t.state&&!this.getRemoteUserIds().includes(t.userId))return}const i=[],n=[],s=[],o=[];r.forEach((e=>{0==+e.state?(T.debug(`user joined -> ${e.userId}`),this._roomResources[e.userId]||(e.switchRoleType?s.push(e.userId):i.push(e.userId)),this._roomResources[e.userId]=this._roomResources[e.userId]||[]):(T.debug(`user left -> ${e.userId}`),e.switchRoleType?o.push(e.userId):n.push(e.userId))}));const a=[...i,...s],c=[...n,...o];if(c.length){const e=[],t=[];c.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===(t=this._appListener)||void 0===t?void 0:t.onSwitchRole)return s.length&&s.forEach((e=>this._callAppListener("onSwitchRole",e,Zt.ANCHOR))),o.length&&o.forEach((e=>this._callAppListener("onSwitchRole",e,Zt.AUDIENCE))),i.length&&this._callAppListener("onUserJoin",i),void(n.length&&this._callAppListener("onUserLeave",n));a.length&&this._callAppListener("onUserJoin",a),c.length&&this._callAppListener("onUserLeave",c)}))}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(e,t){return C(this,void 0,void 0,(function*(){const{code:r}=yield this._context.sendMessage(o.RTC_ROOM,this._roomId,{messageType:e,content:t,isStatusMessage:!0});return r!==i.SUCCESS?(T.error(`send message failed -> code: ${r}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}setRoomAttribute(e,t,r,n=!1){return C(this,void 0,void 0,(function*(){const s=yield this._context.setRTCData(this._roomId,e,t,n,a.ROOM,r);return s!==i.SUCCESS?(T.error(`SetRoomAttributeValue Failed: ${s}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}deleteRoomAttributes(e,t,r=!1){return C(this,void 0,void 0,(function*(){const n=yield this._context.removeRTCData(this._roomId,e,r,a.ROOM,t);return n!==i.SUCCESS?(T.error(`DeleteRoomAttribute Failed: ${n}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS}}))}getRoomAttributes(e=[],t=!1){return C(this,void 0,void 0,(function*(){const{code:r,data:n}=yield this._context.getRTCData(this._roomId,e,t,a.ROOM);return r!==i.SUCCESS?(T.error(`GetRoomAttributes Failed: ${r}`),{code:I.SIGNAL_ERROR}):{code:I.SUCCESS,data:n}}))}_setUserAttributeValue(e,t,r){return this._context.setRTCData(this._roomId,e,t,!1,a.PERSON,r)}_deleteUserAttributes(e,t){return this._context.removeRTCData(this._roomId,e,!1,a.PERSON,t)}_getUserAttributes(e){return this._context.getRTCData(this._roomId,e,!1,a.PERSON)}isDestroyed(){return this._destroyed}__destroy(e){return this._leaveHandle(e)}_leaveHandle(e){var t;return C(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.clearAudioLevelReportTimer(),e&&(yield this._context.quitRTCRoom(this._roomId)),this._isMainRoom&&this._quitAllPKRoom(),this._pc.removeAllLocalTrack(),this._pinger.stop(),yield this._service.exit(this._getRTCReqestHeaders()),this._pc.destroy(),this._polarisReport=null,this._removeRemoteTracks())}))}_onLocalTrackDestroied(e){e instanceof Ze&&e.__isTiny()||this.unpublish([e])}_onLocalTrackMuted(e){return C(this,void 0,void 0,(function*(){const t=e.getTrackId(),r=this._context.getCurrentId(),n=[{resourceId:t,enabled:!e.isLocalMuted()}],s=this._roomResources[r]||[],o=[];for(let e=0;e<s.length;e+=1){const t=s[e],r=ft(t),i=n.findIndex((e=>e.resourceId===r));if(i>=0){const{enabled:e}=n[i];t.state=e?1:0,o.push(t);break}}const a=yield b((()=>this._context.setRTCTotalRes(this._roomId,dt(Dt.MODIFY,o),ut(s),Dt.TOTAL_CONTENT_RESOURCE)));a!==i.SUCCESS&&T.error("notice `track.enabled` change failed -> code: "+a)}))}_removePubFailedTracks(e){e.forEach((e=>{const t=e instanceof Qe?e:e.track;T.debug(`remove pub failed track from peerconnection -> trackId: ${t.getTrackId()}`),this._pc.removeLocalTrackById(t.getTrackId())}))}publish(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__publish(e)))}))}__publish(e){return C(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof mr)return T.error("the `publish` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return T.error(`publish failed, room has been destroyed. -> roomId: ${this._roomId}`),{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof Qe||e.track instanceof Qe))),!0))return T.error(`publish failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};const t=this._context.getCurrentId();if(this._pc.getLocalTracks().length+(e=>{let t=0;return e.forEach((e=>{e instanceof Qe?t++:e.pubTiny&&e.track.isVideoTrack()?t+=2:t++})),t})(e)>10)return T.error(`publish failed, tracks limit exceeded -> roomId: ${this._roomId}`),{code:I.PUBLISH_TRACK_LIMIT_EXCEEDED};T.debug(`publish tracks -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`),e.forEach((e=>{const{track:t,pubTiny:r}=e instanceof Qe?{pubTiny:!1,track:e}:e;if(this._pc.addLocalTrack(t),t.isVideoTrack()&&r){let e;try{e=t.__innerGetMediaStreamTrack().clone();const i=r.frameRate||Be.FPS_15,n=r.resolution||Ke.W176_H144,{width:s,height:o}=Tt(n),a=yt(i);e.applyConstraints({width:s,height:o,frameRate:a})}catch(r){return null==e||e.stop(),void T.warn(`pubTiny failed -> id: ${t.getTrackId()}, msg: ${r.message}`)}this._pc.addLocalTrack(new Ze(t.getTag(),t.getUserId(),e,!0))}})),this._pc.clearReTryExchangeTimer();const r=yield this._createExchangeParams(this._subscribedList,!1),n=this._getPushOtherRoomsParams();n&&(r.pushOtherRooms=n);const s=yield this._exchangeHandle(r);if(s.code!==I.SUCCESS)return T.error(`publish failed -> roomId: ${this._roomId}, code: ${s.code}`),this._removePubFailedTracks(e),{code:s.code};const{publishList:o,sdp:a,resultCode:l,message:h,urls:p,mcuPublishList:_}=s.data;if(l!==I.SUCCESS)return T.error(`publish failed -> roomId: ${this._roomId}, code: ${l}, msg: ${h}`),this._removePubFailedTracks(e),{code:l};const m=yield this._pc.setRemoteAnswer(a.sdp);if(m!==I.SUCCESS)return{code:m};const f=this._roomResources[t],v=o.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ft(e))},e))),{publishedList:R}=St(f,v),g=(null==_?void 0:_.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))))||[],S=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.PUBLISH,R),ut(v),Dt.TOTAL_CONTENT_RESOURCE,ut(g));if(S!==i.SUCCESS)return T.error(`send publish streams notification failed: ${S}`),{code:I.SIGNAL_ERROR};this._roomResources[t]=v;const C=R.map((e=>ft(e)));return this._polarisReport&&this._polarisReport.sendR2(Qt.PUBLISH,Xt.BEGIN,C),e.forEach((e=>{const{track:t}=e instanceof Qe?{track:e}:e;t.__innerSetPublished(!0)})),T.debug(`publish success: ${C.join(",")}`),this._roomMode===u.LIVE?{code:I.SUCCESS,liveUrl:null==p?void 0:p.liveUrl}:{code:I.SUCCESS}}))}_getPushOtherRoomsParams(){return[]}_reTryExchange(){return C(this,void 0,void 0,(function*(){b((()=>C(this,void 0,void 0,(function*(){const e=yield this._createExchangeParams(this._subscribedList,!0),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`reTryExchange failed: ${n}`),{code:n};this._pc.clearReTryExchangeTimer();const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==I.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,t){return C(this,void 0,void 0,(function*(){return{sdp:yield this._pc.createOffer(t),extend:JSON.stringify({resolutionInfo:this._pc.getOutboundVideoInfo()}),subscribeList:e.filter((e=>{const t=e.track.getTrackId(),{userId:r}=vt(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?xt.TINY:xt.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 C(this,void 0,void 0,(function*(){return b((()=>this.__unpublish(e)))}))}__unpublish(e){var t;return C(this,void 0,void 0,(function*(){if(!this._isMainRoom&&this instanceof mr)return T.error("the `unpublish` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(this._assertRoomDestroyed())return T.warn(`room has been destroyed, no need to unpublish tracks -> roomId: ${this._roomId}`),{code:I.SUCCESS};const r=this._context.getCurrentId();if(!c("tracks",e,(()=>e.every((e=>e.getUserId()===r&&e instanceof Qe))),!0))return T.warn(`unpublish failed, tracks is invalid -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`),{code:I.PARAMS_ERROR};const n=e.map((e=>e.getTrackId())),s=n.map(this._getResourceById.bind(this)).filter((e=>!!e));if(0===s.length)return{code:I.SUCCESS};const o=this._roomResources[r].filter((e=>!s.includes(e)));n.forEach((e=>this._pc.removeLocalTrackById(e))),null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.PUBLISH,Xt.END,n),this._pc.clearReTryExchangeTimer();const a=yield this._createExchangeParams(this._subscribedList,!1),d=this._getPushOtherRoomsParams();d&&(a.pushOtherRooms=d);const u=yield this._exchangeHandle(a);if(u.code!==I.SUCCESS)return T.error(`exchange failed -> code: ${u.code}`),{code:u.code};const{publishList:l,sdp:h,resultCode:p,message:_,mcuPublishList:m}=u.data;p!==I.SUCCESS&&T.error(`unpublish streams failed -> code: ${p}, msg: ${_}`);const f=m?m.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:1},e))):[],v=yield this._context.setRTCTotalRes(this._roomId,dt(Dt.UNPUBLISH,s),ut(o),Dt.TOTAL_CONTENT_RESOURCE,ut(f));if(v!==i.SUCCESS)return T.error("send unpublish notification failed:",v),{code:I.SIGNAL_ERROR};T.debug(`unpublish success -> tracks: ${n.join(",")}`);const R=yield this._pc.setRemoteAnswer(h.sdp);if(R!==I.SUCCESS)return{code:R};const g=l.map((e=>Object.assign({tag:e.msid.split("_").pop(),state:this._getResourceState(ft(e))},e)));return this._roomResources[r]=g,{code:I.SUCCESS}}))}_getResourceById(e){const{userId:t}=vt(e);return this._roomResources[t].find((t=>ft(t)===e))}_isValidResourceId(e){var t;const{userId:r}=vt(e);return!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>ft(t)===e)))}subscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__subscribe(e,!1)))}))}__subscribe(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return T.error(`subscribe failed, room has been destroyed -> roomId: ${this._roomId}`),{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return T.error(`subscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`subscribe -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`);const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof ot?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(Qt.SUBSCRIBE,Xt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:I.SUCCESS}}))}unsubscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe(e)))}))}__unsubscribe(e){var t;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return T.warn(`room has beed destroyed, no need to unsubscribe tracks -> roomId: ${this._roomId}`),{code:I.SUCCESS};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot))),!0))return T.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`unsubscribe -> roomId: ${this._roomId}, tracks: ${e.map(rr)}`);const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.SUBSCRIBE,Xt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}_assertRoomDestroyed(){if(this._destroyed){const e="This room has been destroyed. Please use `RCRTCClient.joinRTCRoom` or `RCRTCClient.joinLivingRoom` to catch another instance.";return T.warn(e),I.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 C(this,void 0,void 0,(function*(){return b((()=>this._updateSubListHandle(e,!1)))}))}_updateSubListHandle(e,t=!1){return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return T.error(`update sublist failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};T.info(`update subscribe list -> roomId: ${this._roomId}, forceReq: ${t}, tracks: ${e.map(rr)}`);let r=e.map((e=>e instanceof ot?{track:e}:Object.assign({},e)));const i={};r=r.filter((e=>{const t=e.track.getTrackId();return this._remoteTracks[t]?!i[t]&&(i[t]=!0):(T.warn(`track cannot found in room -> trackId: ${t}`),!1)})).map((e=>Object.assign({},e)));const n=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(r.forEach((t=>{const r=n.findIndex((e=>e.track===t.track));if(-1===r)return void(e=!0);n.splice(r,1)[0].subTiny!==t.subTiny&&(e=!0)})),n.length&&(e=!0),!e)return{code:I.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(r.map((e=>e.track)));const s=yield this._createExchangeParams(r,!1),o=this._getPushOtherRoomsParams();o&&(s.pushOtherRooms=o);const a=yield this._exchangeHandle(s),u=r.map((e=>e.track.getTrackId()));if(a.code!==I.SUCCESS)return{code:a.code};const{sdp:l,resultCode:h,message:p,subscribedList:_}=a.data;if(h!==I.SUCCESS)return T.error(`change subscribe list failed: ${h}`),{code:h};T.debug(`subscribe success: ${u.join(",")}`);const m=yield this._pc.setRemoteAnswer(l.sdp);if(m!==I.SUCCESS)return{code:m};const f=null==_?void 0:_.map((e=>`${e.msid}_${e.mediaType}`)),v=r.filter((e=>null==f?void 0:f.includes(e.track.getTrackId()))),R=r.filter((e=>!(null==f?void 0:f.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=v.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...v),R.length?{code:I.SUCCESS,failedList:R}:{code:I.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 tr(this),this._audioLevelReport.onAudioLevelChange(e,t||1e3)}__onReconnected(e){return C(this,void 0,void 0,(function*(){if("closed"===this._pc.getRTCPeerConn().connectionState)return T.warn("RTCPeerConnection closed. Please rejoin room to restore services."),void this._rtcpeerClosed();const{code:t,data:r}=yield this._context.joinRTCRoom(this._roomId,this._roomMode,e);if(t!==i.SUCCESS)return void T.error(`RTC __onReconnected getRTCRoomInfo failed: ${t}`);T.debug(`RTC __onReconnected getRTCRoomInfo success: ${JSON.stringify(r)}`);const n=[],s={},o={},a={},c=Nt(r,this._roomId),d=Object.keys(c),u=Object.keys(this._roomResources);for(let e=d.length-1;e>=0;e-=1){const t=d[e],r=u.indexOf(t);if(-1===r){n.push(t),s[t]=gt(c[t]);continue}const i=this._roomResources[t],l=c[t],{publishedList:h,modifiedList:p,unpublishedList:_}=St(i,l,!0);s[t]=gt(h),o[t]=gt(_),a[t]=gt(p),u.splice(r,1)}u.length&&u.forEach((e=>{delete this._roomResources[e]})),Object.assign(this._roomResources,c),u.length&&this._callAppListener("onUserLeave",u),n.length&&this._callAppListener("onUserJoin",n);for(const e in o){const t=o[e];if(t.length){const e=t.map((e=>this._remoteTracks[ft(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=ft(e),{userId:r,tag:i,mediaType:n}=vt(t),s=this._remoteTracks[t]=n===Fe.AUDIO_ONLY?new at(i,r):new ct(i,r);return s.__innerSetRemoteMuted(0===e.state),s}));this._onTrackPublish(r)})),Object.keys(a).forEach((e=>{a[e].forEach((e=>{const t=ft(e),r=this._remoteTracks[t];r.__innerSetRemoteMuted(0===e.state),r.isAudioTrack()?this._onAudioMuteChange(r):this._onVideoMuteChange(r)}))})),{data:r}}))}_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={})}_registerPKMsgListener(e){this._onRecvPKMsg=e}_quitAllPKRoom(){}}var nr,sr,or;!function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(nr||(nr={})),function(e){e[e.CUSTOMIZE=1]="CUSTOMIZE",e[e.SUSPENSION=2]="SUSPENSION",e[e.ADAPTATION=3]="ADAPTATION"}(sr||(sr={})),function(e){e[e.CROP=1]="CROP",e[e.WHOLE=2]="WHOLE"}(or||(or={}));const ar=()=>({version:1,mode:sr.SUSPENSION});class cr{constructor(e,t,r){this._onFlush=e,this._isValidTrackId=t,this._sendCDNInfoSignal=r,this._values=ar()}setHostVideoTrack(e){if(!this._isValidTrackId(e))return T.error(`setHostVideoTrack failed: videoTrackId is invalid -> ${e}`),this;const{mediaType:t,tag:r,userId:i}=vt(e);return t!==Fe.VIDEO_ONLY?(T.error(`setHostVideoTrack failed: kind of resource is not 'video' -> ${e}`),this):(this._values.host_stream_id=Rt(i,r),this)}setMixLayoutMode(e){return[sr.CUSTOMIZE,sr.SUSPENSION,sr.ADAPTATION].includes(e)?(this._values.mode=e,this):(T.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:nr.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 T.warn("setOutputVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Tt(e);return this._addOutputValue("video",{width:t,height:r},"normal"),this}setOutputVideoFPS(e){if(!Et(e))return T.warn("setOutputVideoFPS failed: `fps` is invalid"),this;const t=yt(e);return this._addOutputValue("video",{fps:t},"normal"),this}setOutputVideoBitrate(e){return!r(e)||e<=0?T.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"normal"),this}setOutputTinyVideoResolution(e){if(!It(e))return T.warn("setOutputTinyVideoResolution failed: `resolution` is invalid"),this;const{width:t,height:r}=Tt(e);return this._addOutputValue("video",{width:t,height:r},"tiny"),this}setOutputTinyVideoFPS(e){if(!Et(e))return T.warn("setOutputTinyVideoFPS failed: `fps` is invalid"),this;const t=yt(e);return this._addOutputValue("video",{fps:t},"tiny"),this}setOutputTinyVideoBitrate(e){return!r(e)||e<=0?T.error(`bitrate is invalid: ${e}`):this._addOutputValue("video",{bitrate:e},"tiny"),this}setOutputVideoRenderMode(e){return[or.CROP,or.WHOLE].includes(e)?this._addOutputValue("video",e,"exparams"):T.error(`renderMode is invalid: ${e}`),this}setOutputAudioBitrate(e){return r(e)&&e>0?this._addOutputValue("audio",e):T.error(`bitrate is invalid: ${e}`),this}setOutputBackgroundColor(e){return/^0x[a-fA-F0-9]{6}$/.test(e)?this._addOutputValue("video",e,"backgroundColor"):T.error(`color is invalid: ${e}`),this}addOutputBackgroundPicture(e,t,i,n,s){var o,a,c;if(!l(e))return T.error(`uri is invalid: ${e}`),this;if([t,i,n,s].some((e=>!r(e)||e<0||e>1)))return T.error(`some attrs of (x, y, w, h) is invalid: ${t}, ${i}, ${n}, ${s}`),this;const d=(null===(c=null===(a=null===(o=this._values.output)||void 0===o?void 0:o.video)||void 0===a?void 0:a.backgroundPicture)||void 0===c?void 0:c.picture)||[];return d.push({uri:e,w:n,h:s,x:t,y:i}),this._addOutputValue("video",{picture:d},"backgroundPicture"),this}removeOutputBackgroundPicture(e){var t,r,i;if(!l(e))return T.error(`uri is invalid: ${e}`),this;let n=null===(i=null===(r=null===(t=this._values.output)||void 0===t?void 0:t.video)||void 0===r?void 0:r.backgroundPicture)||void 0===i?void 0:i.picture;return n&&(n=n.filter((t=>t.uri!==e)),this._addOutputValue("video",{pictures:n},"backgroundPicture")),this}clearOutputBackgroundPicture(){return this._addOutputValue("video",{pictures:[]},"backgroundPicture"),this}setOutputBackgroundPictureFillMode(e){return[nr.CROP,nr.WHOLE].includes(e)?this._addOutputValue("video",{fillMode:e},"backgroundPicture"):T.error(`fillMode is invalid: ${e}`),this}addPublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return T.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];let s=!1;return e.forEach((e=>{n.some((t=>t.pushurl===e))||(s=!0,n.push({pushurl:e}))})),n.length>5?(T.error("publish stream url no more than 5"),this):(s&&this._addOutputValue("cdn",n),this)}removePublishStreamUrls(e){var t,r;const i=/^rtmp:\/\/.+/;if(!d(e)||0===e.length||e.some((e=>!i.test(e))))return T.error(`urls is invalid: ${e}`),this;const n=(null===(r=null===(t=this._values.output)||void 0===t?void 0:t.cdn)||void 0===r?void 0:r.concat())||[];for(let t=n.length-1;t>=0;t-=1){const{pushurl:r}=n[t],i=e.indexOf(r);i>=0&&(e.splice(i,1),n.splice(t,1))}return this._addOutputValue("cdn",n),this}clearPublishStreamUrls(){return this._addOutputValue("cdn",[]),this}addCustomizeLayoutVideo(e,t,i,n,s){if(!this._isValidTrackId(e))return T.error(`trackId is invalid: ${e}`),this;if(!r(t)||!r(i))return T.error(`some attrs of (x, y) is invalid: ${t}, ${i}`),this;if([n,s].some((e=>!r(e)||e<0)))return T.error(`some attrs of (width, height) is invalid: ${n}, ${s}`),this;const{userId:o,tag:a,mediaType:c}=vt(e);if(c!==Fe.VIDEO_ONLY)return T.error(`kind of resource is not 'video': ${e}`),this;const d=Rt(o,a);return(this._values.input||(this._values.input={video:[]})).video.push({user_id:o,stream_id:d,x:t,y:i,width:n,height:s}),this}removeCustomizeLayoutVideo(e){if(!this._isValidTrackId(e))return T.error(`trackId is invalid: ${e}`),this;const{userId:t,tag:r,mediaType:i}=vt(e);if(i!==Fe.VIDEO_ONLY)return T.error(`kind of resource is not 'video': ${e}`),this;const n=Rt(t,r),s=this._values.input||(this._values.input={video:[]});return s.video=s.video.filter((e=>e.stream_id===n)),this}clearCustomizeLayoutVideo(){return(this._values.input||(this._values.input={video:[]})).video=[],this}flush(){var e,t,r,i;return C(this,void 0,void 0,(function*(){const n=JSON.parse(JSON.stringify(this._values)),{code:s}=yield this._onFlush(n);return s===I.SUCCESS&&((null===(t=null===(e=this._values.output)||void 0===e?void 0:e.video.normal)||void 0===t?void 0:t.width)||(null===(i=null===(r=this._values.output)||void 0===r?void 0:r.video.normal)||void 0===i?void 0:i.fps))&&this._sendCDNInfoSignal(),this._values=ar(),{code:s}}))}}var dr,ur,lr,hr;!function(e){e[e.OPEN=1]="OPEN",e[e.STOP=2]="STOP"}(dr||(dr={})),function(e){e[e.SPREAD=0]="SPREAD",e[e.NO_SPREAD=-1]="NO_SPREAD"}(ur||(ur={})),function(e){e[e.AUTOMATIC=0]="AUTOMATIC",e[e.MANUAL=1]="MANUAL"}(lr||(lr={})),function(e){e[e.VIDEO=0]="VIDEO",e[e.AUDIO=1]="AUDIO"}(hr||(hr={}));const pr=()=>"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)}));class _r{constructor(e,t,r,i,n,s,o,a,c){this._PKInfo=e,this._context=t,this._runtime=r,this._service=i,this._initOptions=n,this._mainLivingRoom=s,this._registerPKMsgListener=o,this._onJoinedPKRoom=a,this._onLeavePKRoom=c,this._inviteTimeout=30,this._appListener=null,this._joinedPKRooms={},this._registerPKMsgListener(this._onRecvPKMsg.bind(this)),this._mainRoomId=this._mainLivingRoom.getRoomId()}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_onInvite(e){const t=e.inviteInfo||{},{inviterRoomId:r,inviterUserId:i,extra:n}=t,s={inviterRoomId:r,inviterUserId:i,extra:n};this._PKInfo[r]=t,this._callAppListener("onRequestJoinOtherRoom",s)}_onCancelInvite(e){const{inviterRoomId:t,inviterUserId:r,extra:i}=e.inviteInfo||{},n={inviterRoomId:t,inviterUserId:r,extra:i};delete this._PKInfo[t],this._callAppListener("onCancelRequestOtherRoom",n)}_onInviteTimeout(e){}_onInviteAnswer(e){const{answerCode:t,inviteContent:r}=e,{inviteSessionId:i,inviterUserId:n,inviterRoomId:s,inviteeUserId:o,inviterUserAutoMix:a,inviteeUserAutoMix:c,inviteeRoomId:d,extra:u}=r,l={agree:1===t,inviterRoomId:s,inviterUserId:n,inviteeRoomId:d,inviteeUserId:o,extra:u};this._PKInfo[d]=this._PKInfo[d]||{inviteSessionId:i,inviterRoomId:s,inviterUserId:n,inviterUserAutoMix:a,inviteeRoomId:d},this._PKInfo[d].inviteeUserAutoMix=c,this._callAppListener("onResponseJoinOtherRoom",l)}_onPKEnd(e){return C(this,void 0,void 0,(function*(){const{inviteeRoomId:t,inviterRoomId:r,userId:i}=e.inviteInfo,n=r===this._mainRoomId?t:r,s={endRoomId:n,endUserId:i};this._joinedPKRooms[n]&&(yield this.leaveOtherRoom(this._joinedPKRooms[n])),delete this._PKInfo[n],this._callAppListener("onFinishOtherRoom",s)}))}_onRecvPKMsg(e){const{targetId:t,content:r,messageType:i}=e;switch(i){case Dt.PK_INVITE:this._onInvite(r);break;case Dt.PK_CANCEL_INVITE:this._onCancelInvite(r);break;case Dt.PK_INVITE_TIMEOUT:this._onInviteTimeout(r);break;case Dt.PK_INVITE_ANSWER:this._onInviteAnswer(r);break;case Dt.PK_END:this._onPKEnd(r)}}registerRoomPKEventListener(e){this._appListener=e}requestJoinOtherRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:I.PARAMS_ERROR};T.info(`requestRoomPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; options: ${JSON.stringify(r||{})}`);const n=pr(),s=!p(null==r?void 0:r.autoMix)||(null==r?void 0:r.autoMix),o={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e,inviteeUserId:t,inviteeTimeoutTime:this._inviteTimeout,extra:(null==r?void 0:r.extra)||""},a={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteTimeout:this._inviteTimeout,inviteInfo:JSON.stringify(o),inviteSessionId:n};T.info(`requestRoomPK -> params: ${JSON.stringify(a)}`);const d=yield this._context.requestRoomPK(a);return d!==i.SUCCESS?(T.error(`requestRoomPK failed: ${d}`),{code:d}):(T.info("requestRoomPK success"),this._PKInfo[e]={inviteSessionId:n,inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviterUserAutoMix:s,inviteeRoomId:e},{code:I.SUCCESS})}))}cancelRequestJoinOtherRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(!c("inviteeRoomId",e,h,!0)||!c("inviteeUserId",t,h,!0))return{code:I.PARAMS_ERROR};if(!this._PKInfo[e])return T.error(`未发起过与 ${e} 房间内 ${t} 连麦的请求`),{code:I.PARAMS_ERROR};T.info(`canceRequestJoinPK -> inviteeRoomId: ${e}; inviteeUserId: ${t}; extra: ${r}`);const n={inviterRoomId:this._mainRoomId,inviterUserId:this._context.getCurrentId(),inviteeRoomId:e,inviteeUserId:t,extra:r||""},s={roomId:this._mainRoomId,invitedRoomId:e,invitedUserId:t,inviteSessionId:this._PKInfo[e].inviteSessionId,inviteInfo:JSON.stringify(n)};T.info(`canceRequestJoinPK -> params: ${JSON.stringify(s)}`);const o=yield this._context.cancelRoomPK(s);return o!==i.SUCCESS?(T.error(`canceRequestJoinPK failed: ${o}`),{code:o}):(T.info("canceRequestJoinPK success"),delete this._PKInfo[e],{code:I.SUCCESS})}))}responseJoinOtherRoom(e,t,r,n){return C(this,void 0,void 0,(function*(){if(!c("inviterRoomId",e,h,!0)||!c("inviterUserId",t,h,!0))return{code:I.PARAMS_ERROR};if(!this._PKInfo[e])return T.error(`${e} 房间内的 ${t} 未发起过连麦请求`),{code:I.PARAMS_ERROR};T.info(`responseRoomPK -> inviterRoomId: ${e}; inviterUserId: ${t}; agree: ${r}; options: ${JSON.stringify(n||{})}`);const{inviteSessionId:s,inviterUserAutoMix:o}=this._PKInfo[e],a=!p(null==n?void 0:n.autoMix)||(null==n?void 0:n.autoMix),d={inviteSessionId:s,inviterRoomId:e,inviterUserId:t,inviterUserAutoMix:o,inviteeRoomId:this._mainRoomId,inviteeUserId:this._context.getCurrentId(),inviteeUserAutoMix:a},u=Object.assign(d,{inviterUserAutoMix:o}),l=r?Object.assign(d,{MultiRoomKey:`${e}|${this._mainRoomId}`,MultiRoomValue:JSON.stringify(u)}):d;!_(null==n?void 0:n.extra)&&Object.assign(l,{extra:n.extra});const m={agree:r,roomId:this._mainRoomId,inviteSessionId:s,inviteRoomId:e,inviteUserId:t,content:JSON.stringify(l),key:`${e}|${this._mainRoomId}`,value:JSON.stringify(d)};T.info(`responseRoomPK -> params: ${JSON.stringify(m)}`);const f=yield this._context.responseRoomPK(m);return f!==i.SUCCESS?(T.error(`responseRoomPK failed: ${f}`),{code:f}):(T.info("responseRoomPK success"),this._PKInfo[e].inviteeUserAutoMix=a,{code:I.SUCCESS})}))}_quitRoomPK(e){return C(this,void 0,void 0,(function*(){const{inviterRoomId:t,inviteeRoomId:r,inviterUserId:n}=this._PKInfo[e],s={inviteeRoomId:r,inviterRoomId:t,userId:this._context.getCurrentId()},o={roomId:this._mainRoomId,endRoomId:e,sessionId:this._PKInfo[e].inviteSessionId,content:JSON.stringify(s),keys:[`${t}|${n}`]};T.info(`quitRoomPK -> params: ${JSON.stringify(o)}`);const a=yield this._context.endRoomPK(o);return a!==i.SUCCESS?(T.error(`quitRoomPK failed: ${a}`),{code:I.SIGNAL_ERROR}):(T.info("quitRoomPK success"),delete this._PKInfo[e],{code:I.SUCCESS})}))}_relaseCrtRoom(){}joinOtherRoom(e){return C(this,void 0,void 0,(function*(){if(!c("roomId",e,h,!0))return{code:I.PARAMS_ERROR};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(T.info(`JoinPKRoom, roomId: ${e}`),this._joinedPKRooms[e])return{code:I.REPERT_JOIN_ROOM};const t=hr.VIDEO,r={extra:`{"roomId": "${this._mainRoomId}"}`},{code:s,data:o}=yield this._context.joinRTCRoom(e,u.LIVE,t,void 0,r);if(s!==i.SUCCESS)return T.error(`JoinPKRoom failed -> code: ${s}`),{code:s};T.info(`JoinPKRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(o)}`);const a=new mr(this._context,this._runtime,e,o,this._service,this._initOptions,this._relaseCrtRoom.bind(this),t,!1,!1);return this._joinedPKRooms[e]=a,this._onJoinedPKRoom(e,a),{room:a,code:I.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}leaveOtherRoom(e,t){return C(this,void 0,void 0,(function*(){return b((()=>C(this,void 0,void 0,(function*(){const r=e.getRoomId();return T.info(`leavePKRoom -> userId: ${this._context.getCurrentId()} , roomId: ${r}`),yield e.__destroy(!0),delete this._joinedPKRooms[r],this._onLeavePKRoom(r),this._PKInfo[r]?(t&&this._quitRoomPK(r),{code:I.SUCCESS}):{code:I.SUCCESS}}))))}))}getPKInfo(e){return this._PKInfo[e]}getAllPKInfo(){return this._PKInfo}getJoinedPKRooms(){return this._joinedPKRooms}}class mr extends ir{constructor(e,t,r,i,n,s,o,a,c=!1,d){var l;if(super(e,t,r,i,u.LIVE,n,s,o,c,d),this._livingType=a,this._isMainRoom=d,this._CDNUris=null,this._CDNEnable=!1,this._mcuConfigBuilder=new cr(this._onMCUConfigFlush.bind(this),this._isValidResourceId.bind(this),this._sendCDNInfoSignal.bind(this)),this._isMainRoom){const r=((e,t)=>{const r={};return t.forEach((t=>{const i=JSON.parse(t.value),{inviterRoomId:n,inviteeRoomId:s}=i;r[e===n?s:n]=JSON.parse(t.value)})),r})(this._roomId,i.roomInfo);this._roomPKHandler=new _r(r,e,t,n,s,this,super._registerPKMsgListener.bind(this),this._onJoinedPKRoom.bind(this),this._onLeavePKRoom.bind(this))}const h=null===(l=i.roomInfo.filter((e=>"cdn_uris"===e.key))[0])||void 0===l?void 0:l.value;h&&(this._CDNUris=JSON.parse(h)[0])}_isValidResourceId(e){var t;const{userId:r}=vt(e),i=!!(null===(t=this._roomResources[r])||void 0===t?void 0:t.find((t=>ft(t)===e)));let n=!1;const{code:s,roomPKHandler:o}=this.getRoomPKHandler();if(s!==I.SUCCESS||!o)return i;const a=o.getJoinedPKRooms(),c=[];return Object.values(a).map((e=>{c.push(...e.getRemoteTracks())})),n=c.some((t=>e===t.getTrackId())),i||n}getLivingType(){return this._livingType}getMCUConfigBuilder(){return this._isMainRoom?this._mcuConfigBuilder:(T.error("the `getMCUConfigBuilder` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_onMCUConfigFlush(e){return C(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:r,res:i}=yield this._service.setMcuConfig(t,e);return r!==I.SUCCESS?(T.error(`set MCU config failed: ${r}`),{code:r}):(T.info("set MCU config success"),i.pull_url&&(this._CDNUris=JSON.parse(i.pull_url)),{code:r,res:i})}))}__onReconnected(){const e=Object.create(null,{__onReconnected:{get:()=>super.__onReconnected}});var t,r;return C(this,void 0,void 0,(function*(){const i=yield e.__onReconnected.call(this,this._livingType);if(!i||!i.data)return;const n=i.data.roomInfo,s=null===(t=n.filter((e=>"cdn_uris"===e.key))[0])||void 0===t?void 0:t.value;if(!s)return;const o=JSON.parse(s);(null===(r=this._CDNUris)||void 0===r?void 0:r.enableInnerCDN)!==o.enableInnerCDN&&this._callAppListener("onCDNEnableChange",o.enableInnerCDN),this._CDNUris=o}))}enableInnerCDN(e){return C(this,void 0,void 0,(function*(){if(!this._isMainRoom)return T.error("the `enableInnerCDN` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!p(e))return T.error("`enable` is invalid"),{code:I.PARAMS_ERROR};this._CDNEnable=e;const t={version:2,output:{inCDNModel:e?dr.OPEN:dr.STOP}},{code:r}=yield this._onMCUConfigFlush(t);if(r!==I.SUCCESS)return T.error(`enableInnerCDN failed -> code: ${r}`),{code:I.SIGNAL_ERROR};if(this._CDNUris&&this._CDNUris.broadcast!==ur.SPREAD)return T.info("enableInnerCDN succeed"),{code:I.SUCCESS};const{code:i}=yield b((()=>C(this,void 0,void 0,(function*(){return this._sendCDNInfoSignal()}))));return i===I.SUCCESS?(T.info("enableInnerCDN succeed"),{code:I.SUCCESS}):(T.error(`enableInnerCDN failed -> code: ${i}`),{code:i})}))}_sendCDNInfoSignal(){return C(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===I.SUCCESS))?{code:I.SUCCESS}:{code:I.SIGNAL_ERROR}}))}_spreadCDNInfo(e){return C(this,void 0,void 0,(function*(){const t=yield this._context.setRTCCDNUris(this._roomId,Dt.TOTAL_CONTENT_RESOURCE,JSON.stringify([e]));return t!==i.SUCCESS?(T.error(`spreadCDNInfo failed -> code: ${t}`),{code:I.SIGNAL_ERROR}):(T.info("spreadCDNInfo succeed"),{code:I.SUCCESS})}))}_setRoomCDNInfo(e){return C(this,void 0,void 0,(function*(){const t=yield this._context.setRTCData(this._roomId,"cdn_uris",JSON.stringify([e]),!0,a.ROOM);return t!==i.SUCCESS?(T.error(`setRoomCDNInfo failed -> code: ${t}`),{code:I.SIGNAL_ERROR}):(T.info("setRoomCDNInfo succeed"),{code:I.SUCCESS})}))}_resourceHandle(e,t,r){const i=Object.create(null,{_resourceHandle:{get:()=>super._resourceHandle}});var n;return C(this,void 0,void 0,(function*(){i._resourceHandle.call(this,e,t,r),e.cdn_uris&&((null===(n=this._CDNUris)||void 0===n?void 0:n.enableInnerCDN)!==e.cdn_uris[0].enableInnerCDN&&this._callAppListener("onCDNEnableChange",!this.__getCDNEnable()),this._CDNUris=e.cdn_uris[0])}))}_exchangeHandle(e){var t,r,i;return C(this,void 0,void 0,(function*(){const n=yield this._service.exchange(this._getRTCReqestHeaders(),e),s=null===(r=null===(t=n.data)||void 0===t?void 0:t.urls)||void 0===r?void 0:r.pull_url;return n.code===I.SUCCESS&&s?(this._CDNUris=JSON.parse(s),(null===(i=this._CDNUris)||void 0===i?void 0:i.broadcast)===ur.SPREAD&&(this._CDNEnable=!0,this._sendCDNInfoSignal()),n):n}))}_afterChangedRole(e){const t=Nt(e,this._roomId),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]},Dt.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)===lr.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}_onJoinedPKRoom(e,t){b((()=>C(this,void 0,void 0,(function*(){const{code:t,roomPKHandler:r}=this.getRoomPKHandler();if(t===I.SUCCESS&&r){if(!r.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}))))}_onLeavePKRoom(e){b((()=>C(this,void 0,void 0,(function*(){const{code:t,roomPKHandler:r}=this.getRoomPKHandler();if(t===I.SUCCESS&&r){if(!r.getPKInfo(e))return;this._exchangeWithPushOtherRoom()}}))))}_getPushOtherRoomsParams(){const e=[];if(!this.isMainRoom()||!this._roomPKHandler)return e;const t=this._roomPKHandler.getJoinedPKRooms();for(const r in t){const i=t[r].getSessionId(),n=this._roomPKHandler.getPKInfo(r);if(!n)continue;const{inviterUserAutoMix:s,inviteeUserAutoMix:o,inviterUserId:a}=n,c=this._context.getCurrentId()===a;e.push({roomId:r,sessionId:i,autoMix:c?!!s:!!o})}return e}_exchangeWithPushOtherRoom(){return C(this,void 0,void 0,(function*(){if(!this.getLocalTracks().length)return;const e=yield this._createExchangeParams(this._subscribedList,!1),t=this._getPushOtherRoomsParams();t&&(e.pushOtherRooms=t);const r=yield this._exchangeHandle(e);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`exchange with pushOtherRoom failed: ${n}`),{code:n};const s=yield this._pc.setRemoteAnswer(i.sdp);return s!==I.SUCCESS?{code:s}:void 0}))}getRoomPKHandler(){return this._isMainRoom?{code:I.SUCCESS,roomPKHandler:this._roomPKHandler}:(T.error("the `getRoomPKHandler` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM})}_quitAllPKRoom(){const e=this._roomPKHandler.getJoinedPKRooms();for(const t in e){const r=e[t];this._roomPKHandler.leaveOtherRoom(r)}}isMainRoom(){return this._isMainRoom}}class fr extends ir{constructor(e,t,r,i,n,s,o){super(e,t,r,i,u.RTC,n,s,o,!1)}}const vr=()=>({"Content-Type":"application/json;charset=UTF-8","Cache-Control":"no-cache",ClientType:`web|${kt.browser}|${kt.version}`,ClientVersion:"5.3.5","Client-Session-Id":pr(),"Request-Id":Date.now().toString()});class Rr{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 r;try{r=JSON.parse(e.voipCallInfo||'{ "strategy": 0 }')}catch(t){return T.warn("parse `voipCallInfo` of navi failed: "+e.voipCallInfo),[]}if(0===r.strategy)return[];const i=null===(t=r.callEngine)||void 0===t?void 0:t.filter((e=>4===e.engineType));if(!i||0===i.length)return[];const n=i[0],s=[];return n.mediaServer&&s.push(n.mediaServer.replace(/^(https?:\/\/)?/,"https://")),n.backupMediaServer&&n.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(e,t,r){return C(this,void 0,void 0,(function*(){const i=this.getNaviMS();if(0===i.length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};this._rtcFinger&&(r.rtcFinger=this._rtcFinger);for(let n=0;n<i.length;n+=1){const s=`${i[n]}${e}`,o=vr();T.debug(`request -> Request-Id: ${o["Request-Id"]}, url: ${s}`);const{status:a,data:c}=yield this._runtime.httpReq({url:s,body:JSON.stringify(r),headers:Object.assign(Object.assign({},o),t),method:m.POST,timeout:this._timeout});if(200===a){const e=JSON.parse(c);return e.rtcFinger&&(this._rtcFinger=e.rtcFinger),e.clusterId&&(this._clusterId=e.clusterId),T.debug(`request success -> Request-Id: ${o["Request-Id"]}`),{code:I.SUCCESS,data:e}}T.warn(`request failed -> Request-Id: ${o["Request-Id"]}, status: ${a}, url: ${s}`),this._failedMs.push(...this._msInNavi.splice(n,1))}return{code:I.REQUEST_FAILED}}))}exchange(e,t){var r;return C(this,void 0,void 0,(function*(){const i=yield this._request("/exchange",e,t);if(i.code===I.SUCCESS&&(null===(r=i.data)||void 0===r?void 0:r.resultCode)===I.SUCCESS){const e=i.data.urls;e&&(this._configUrl=e.configUrl)}return i}))}exit(e){return C(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 C(this,void 0,void 0,(function*(){const{code:t}=yield this._request("/broadcast/exit",e,{});return{code:t}}))}setMcuConfig(e,t){return C(this,void 0,void 0,(function*(){if(!this._configUrl)return{code:I.MCU_SERVER_NOT_FOUND};const r=`${this._configUrl.replace(/^(https?:\/\/)?/,"https://")}/server/mcu/config`,i=vr();T.debug(`request -> Request-Id: ${i["Request-Id"]}, url: ${r}`);const{status:n,data:s}=yield this._runtime.httpReq({url:r,headers:Object.assign(Object.assign({},i),e),body:JSON.stringify(t),method:m.POST});if(200===n){T.debug(`request success -> Request-Id: ${i["Request-Id"]}`);const e=JSON.parse(s);return{code:e.resultCode,res:e}}return{code:I.REQUEST_FAILED}}))}getCDNResourceInfo(e,t){return C(this,void 0,void 0,(function*(){const r=vr(),{status:i,data:n}=yield this._runtime.httpReq({url:t,headers:Object.assign(Object.assign({},r),e),method:m.GET});if(200===i){const e=JSON.parse(n);return{code:e.resultCode,res:e}}return T.warn(`request failed -> Request-Id: ${r["Request-Id"]}, status: ${i}, url: ${t}`),{code:I.REQUEST_FAILED}}))}}class gr{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 Rr(t,e,r.mediaServer)}_getReqHeaders(e){return C(this,void 0,void 0,(function*(){const t=this._context.getCurrentId(),r=t;if(!this._rtcToken){const{code:t,data:n}=yield this._context.getRTCToken(r,u.LIVE,e);if(t!==i.SUCCESS)return T.error(`getRTCToken failed: ${t}`),{code:I.SIGNAL_ERROR};this._rtcToken=n.rtcToken}return{code:I.SUCCESS,headers:{"App-Key":this._context.getAppkey(),UserId:t,RoomId:r,RoomType:u.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 C(this,void 0,void 0,(function*(){this._fromRetry=!0;const{code:t}=yield this.subscribe(this._liveUrl,this._livingType,this._mediaType,this._subTiny);t===I.SUCCESS&&(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer())}))}subscribe(e,t,r,i=!1){return C(this,void 0,void 0,(function*(){return b((()=>this.__subscribe(e,t,r,i)))}))}__subscribe(e,t,r,i=!1){var n;return C(this,void 0,void 0,(function*(){const s=[];if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR,tracks:s};if(!this._fromRetry&&(null===(n=this._pc)||void 0===n||n.clearReTryExchangeTimer()),this._fromRetry=!1,!f(e))return T.error(`liveUrl is invalid: ${e}`),{code:I.PARAMS_ERROR,tracks:s};if(![hr.AUDIO,hr.VIDEO].includes(t))return T.error(`livingType is invalid: ${t}`),{code:I.PARAMS_ERROR,tracks:s};if(![Fe.AUDIO_ONLY,Fe.VIDEO_ONLY,Fe.AUDIO_VIDEO].includes(r))return T.error(`mediaType is invalid: ${r}`),{code:I.PARAMS_ERROR,tracks:s};if(this._liveUrl&&this._liveUrl!==e)return{code:I.BROADCAST_SUB_LIST_NOT_EMPTY,tracks:s};this._pc||(this._pc=new Yt(this._reTryExchange.bind(this)),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,this._onTrackReady,this),this.registerReportListener(this._reportListener)),this._liveUrl=e;const{code:o,headers:a}=yield this._getReqHeaders(t);if(o!==I.SUCCESS)return{code:o,tracks:s};const c=`rc_mcu_${Date.now()}`,d="RongCloudRTC";0===this._subTracks.length&&(this._subTracks.push(new at(d,c),new ct(d,c)),this._pc.updateSubRemoteTracks(this._subTracks.slice()));const u={sdp:yield this._pc.createOffer(!0),liveUrl:e,mediaType:r,simulcast:i?xt.TINY:xt.NORMAL,switchstream:!1},l=yield this._service.broadcastSubscribe(a,u);if(l.code!==I.SUCCESS)return T.error(`andience subscribe failed: ${l.code}`),{code:l.code,tracks:s};const h=l.data;if(h.resultCode!==I.SUCCESS)return T.error(`andience subscribe failed! code: ${h.resultCode}; message: ${h.message}`),{code:h.resultCode,tracks:s};T.debug(`andience subscribe success: ${e}`),this._livingType=t,this._mediaType=r,this._subTiny=i;const{sdp:p,subscribedList:_}=h,m=[];return _.forEach((e=>{const{mediaType:t}=e,r=this._subTracks[t];m.push(r),r.__innerSetRemoteMuted(!0)})),this._pc.setRemoteAnswer(p.sdp),{code:I.SUCCESS,tracks:m}}))}unsubscribe(){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe()))}))}__unsubscribe(){var e;return C(this,void 0,void 0,(function*(){if(null===(e=this._pc)||void 0===e||e.clearReTryExchangeTimer(),!this._rtcToken||!this._liveUrl)return{code:I.SUCCESS};const{headers:t}=yield this._getReqHeaders(),{code:r}=yield this._service.broadcastExit(t);return r!==I.SUCCESS?T.error(`broadcast unsubscribe failed: ${r}`):T.debug("broadcast unsubscribe success"),this._clearSubscribeInfo(),{code:r}}))}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,r;const i=e.receiver.track,n="audio"===i.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY,s=this._subTracks[n];s.__innerSetMediaStreamTrack(i);try{null===(r=null===(t=this._appListener)||void 0===t?void 0:t.onTrackReady)||void 0===r||r.call(t,s)}catch(e){T.error(e)}}}var Sr,Cr;!function(e){e.RTMP="rtmp",e.FLV="flv",e.HLS="hls"}(Sr||(Sr={})),function(e){e[e.NOT_HTTPS=0]="NOT_HTTPS",e[e.HTTPS=1]="HTTPS"}(Cr||(Cr={}));const Tr=Object.assign(Object.assign({},Tt(Ke.W176_H144)),{frameRate:yt(Be.FPS_15)});class Ir{constructor(e,t,r,i,n,s){this._context=e,this._runtime=t,this._initOptions=r,this._roomId=i,this._joinResData=n,this._livingType=s,this._roomAnchorList=[],this._roomRes={},this._roomAnchorRes={},this._remoteTracks={},this._appListener=null,this._subscribedList=[],this._sessionId="",this._destroyed=!1,this._setInitData(),this._service=new Rr(this._runtime,this._context,this._initOptions.mediaServer,this._initOptions.timeout),this._polarisReport=new er(this._context,this._runtime,this._roomId,this,zt.Audience),this._polarisReport.sendR1(),this._pc=new Yt(this._reTryExchange.bind(this),this._polarisReport),this._pc.on(Yt.__INNER_EVENT_TRACK_READY__,(e=>{const t=e.streams[0].id,r=e.receiver.track,i=[t,"audio"===r.kind?Fe.AUDIO_ONLY:Fe.VIDEO_ONLY].join("_"),n=this._remoteTracks[i];n?(n.__innerSetMediaStreamTrack(r),this._callAppListener("onTrackReady",n)):T.warn("cannot found RCRemoteTrack:",r.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],i=r?r.value:"",n=t.filter((e=>"RC_ANCHOR_LIST"===e.key)).map((e=>JSON.parse(e.value||"[]")))[0],s=t.filter((e=>e.key.includes("RC_RES_"))).map((e=>JSON.parse(e.value||"{}"))),o=s.length?JSON.parse(s[0].mcu_uris||"[]"):[],a=[];o.forEach((t=>{const{mediaType:r,tag:i}=t,n=r===Fe.AUDIO_ONLY?new at(i,"",e):new ct(i,"",e);a.push(n)}));const c=[],d=[];s.forEach((e=>{const t=JSON.parse(e.uris||"[]");c.push(...t),t.forEach((e=>{const{mediaType:t,tag:r,msid:i}=e,n=i.split("_")[0],s=t===Fe.AUDIO_ONLY?new at(r,n):new ct(r,n);d.push(s)}))}));const u=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:i,remoteUserIds:n||[],remoteRTCUris:c,remoteMUCUris:o,remoteRTCTracks:d,remoteMCUTracks:a,remoteTracks:[...d,...a],CDNUris:u||{}}})(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=ft(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 T.warn(e),I.ROOM_HAS_BEEN_DESTROYED}}singalDataChange(e,t){var r;if(t!==this._roomId)return void T.warn(`singalDataChange -> not the current room data: data roomId: ${t}, current roomId: ${this._roomId}`);T.debug("singalDataChange -> singalData:",JSON.stringify(e||{}));const i=[],n=null===(r=e.filter((e=>"RC_CDN"===e.key))[0])||void 0===r?void 0:r.value;n&&this._diffCDNUris(JSON.parse(JSON.parse(n).cdn_uris)[0]),e.forEach((e=>{const{key:t,value:r,timestamp:n,uid:s}=e;if(-1!==t.indexOf("RC_RES_")){const e=JSON.parse(r||"{}"),t=JSON.parse(e.mcu_uris||"[]"),n=JSON.parse(e.uris||"[]");return i.push(...t),void this._diffAnchorResource(n,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(i)}_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 C(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 C(this,void 0,void 0,(function*(){const t=[],r=[],i=[];e.forEach((e=>{const r=ft(e),{userId:n,tag:s,mediaType:o}=vt(r),a=[this._roomId,s,o].join("_");if(!this._remoteTracks[a]){const r=o===Fe.AUDIO_ONLY?new at(s,"",this._roomId):new ct(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,t){return C(this,void 0,void 0,(function*(){const r=this._roomAnchorRes[t]||(this._roomAnchorRes[t]=[]),{publishedList:i,unpublishedList:n,modifiedList:s}=St(r,e);if(i.length){const e=r.map(ft),t=[],n=[];if(i.forEach((i=>{const s=ft(i),o=e.indexOf(s),{userId:a,tag:c,mediaType:d}=vt(s);o>-1?r[o]=i:r.push(i);let u=this._remoteTracks[s];this._roomRes[s]=i,u?u.isSubscribed()&&t.push(u):(u=d===Fe.AUDIO_ONLY?new at(c,a):new ct(c,a),this._remoteTracks[s]=u,n.push(u)),u.__innerSetRemoteMuted(0===i.state)})),t.length){const e=t.map((e=>e.getTrackId()));T.debug(`resub tracks -> ${JSON.stringify(e)}`);const{code:r}=yield b((()=>this._subscribeHandle(t,!0)));r!==I.SUCCESS&&T.error(`resub tracks failed -> code: ${r}, ids: ${JSON.stringify(e)}`)}this._callAppListener("onAnchorTrackPublish",n)}if(n.length){const e=n.map(ft);for(let t=r.length-1;t>=0;t-=1){const i=r[t];e.includes(ft(i))&&r.splice(t,1)}const t=n.map((e=>{const t=ft(e);return this._remoteTracks[t]}));yield this._onUserUnpublish(t,"onAnchorTrackUnpublish")}if(s.length){const e=r.map(ft);for(let t=0;t<s.length;t++){const i=s[t],n=ft(i),o=e.indexOf(n);r[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,t){return C(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(t,e)}))}_callAppListener(e,...t){var r;const i=null===(r=this._appListener)||void 0===r?void 0:r[e];if(i)try{i(...t)}catch(e){T.error(e)}}_reTryExchange(){return C(this,void 0,void 0,(function*(){b((()=>C(this,void 0,void 0,(function*(){var e;const{reqBody:t}=yield this._createSubscribeParams(this._subscribedList,{},!0),r=yield this._exchangeHandle(t);if(r.code!==I.SUCCESS)return T.error(`reTryExchange failed: ${r.code}`),{code:r.code};const{sdp:i,resultCode:n}=r.data;if(n!==I.SUCCESS)return T.error(`reTryExchange failed: ${n}`),{code:n};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,n=[this._roomId,"RongCloudRTC"].join("_");i.sdp=i.sdp.replace(new RegExp(r,"g"),n)}const o=yield this._pc.setRemoteAnswer(i.sdp);return o!==I.SUCCESS?{code:o}:void 0}))))}))}_createSubscribeParams(e,t,r){return C(this,void 0,void 0,(function*(){const i=yield this._pc.createOffer(r),n={resolutionInfo:[]},s={min:0,max:0};Object.keys(t).forEach((e=>{const{mediaStream:r,tinyStream:o}=t[e];[r,o].forEach(((t,r)=>{var o;const a=1===r?[e,"tiny"].join("_"):e;i.sdp=null===(o=i.sdp)||void 0===o?void 0:o.replace(new RegExp(t.id,"g"),a);const c=t.getVideoTracks()[0];if(!c)return;const d=0===r,{width:u,height:l,frameRate:h}=d?_t(c):Tr;n.resolutionInfo.push({trackId:c.id,simulcast:d?xt.NORMAL:xt.TINY,resolution:`${u}x${l}`});const p=Je(u,l),_=Ye(h);s.min+=p.minBitrate*_,s.max+=p.maxBitrate*_}))}));return{reqBody:{sdp:i,switchstream:!1,newVersionFlag:!0,subscribeList:e.map((e=>({simulcast:e.subTiny?xt.TINY:xt.NORMAL,resolution:"",uri:this._roomRes[e.track.getTrackId()].uri})))},dynamicBitrate:s,offer:i}}))}_subscribeHandle(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return{code:I.PARAMS_ERROR};const i=this._subscribedList.map((e=>Object.assign({},e))),n=e.map((e=>e instanceof ot?{track:e}:e));let s=!1;const o=[];return n.forEach((e=>{const t=e.track.getTrackId();o.push(t);const r=i.find((e=>e.track.getTrackId()===t));r&&r.subTiny===e.subTiny||(r?r.subTiny=e.subTiny:i.push(e),s=!0)})),s||t?(null===(r=this._polarisReport)||void 0===r||r.sendR2(Qt.SUBSCRIBE,Xt.BEGIN,o),this._updateSubListHandle(i,!0)):{code:I.SUCCESS}}))}_getReqHeaders(){const e=this._context.getCurrentId();return{"App-Key":this._context.getAppkey(),RoomId:e,Token:this._joinResData.token,RoomType:u.LIVE,UserId:e,"Session-Id":this._sessionId}}_exchangeHandle(e){return this._service.broadcastSubscribe(this._getReqHeaders(),e)}_updateSubListHandle(e,t=!1){var r;return C(this,void 0,void 0,(function*(){if(this._assertRoomDestroyed())return{code:I.ROOM_HAS_BEEN_DESTROYED};if(!c("resources",e,(()=>d(e)&&e.every((e=>e instanceof ot||e.track instanceof ot))),!0))return{code:I.PARAMS_ERROR};let i=e.map((e=>e instanceof ot?{track:e}:Object.assign({},e)));const n={};i=i.filter((e=>{const t=e.track.getTrackId();return!n[t]&&(n[t]=!0)})).map((e=>Object.assign({},e)));const s=this._subscribedList.map((e=>Object.assign({},e)));if(!t){let e=!1;if(i.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:I.SUCCESS}}this._pc.clearReTryExchangeTimer(),this._pc.updateSubRemoteTracks(i.map((e=>e.track)));const{reqBody:o}=yield this._createSubscribeParams(i,{},!1),a=yield this._exchangeHandle(o);if(s.length){const e=[];s.forEach((t=>{e.push(t.track.getTrackId())})),null===(r=this._pc.reportParser)||void 0===r||r.clearLatestPacketsRecv(e)}if(a.code!==I.SUCCESS)return{code:a.code};const{sdp:u,resultCode:l,message:h,subscribedList:p}=a.data;if(l!==I.SUCCESS)return T.error("change subscribe list failed:",h,l),{code:l};i.forEach((e=>{const{track:t}=e;if(t.isMCUTrack()){const e=this._roomRes[t.getTrackId()].msid,{tag:r,userId:i}=vt(t.getTrackId()),n=[i,r].join("_");u.sdp=u.sdp.replace(new RegExp(e,"g"),n)}}));const _=yield this._pc.setRemoteAnswer(u.sdp);if(_!==I.SUCCESS)return{code:_};const m=null==p?void 0:p.map((e=>`${e.msid}_${e.mediaType}`)),f=i.filter((e=>{if(e.track.isMCUTrack()){const t=this._roomRes[e.track.getTrackId()],r=`${t.msid}_${t.mediaType}`;return m.includes(r)}return null==m?void 0:m.includes(e.track.getTrackId())})),v=null==f?void 0:f.map((e=>`${e.track.getTrackId()}`)),R=i.filter((e=>!(null==v?void 0:v.includes(e.track.getTrackId()))));for(const e in this._remoteTracks){const t=f.some((t=>t.track.getTrackId()===e));this._remoteTracks[e].__innerSetSubscribed(t)}return this._subscribedList.splice(0,this._subscribedList.length,...f),R.length?{code:I.SUCCESS,failedList:R}:{code:I.SUCCESS}}))}_diffCDNUris(e){return C(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 C(this,void 0,void 0,(function*(){const{w:t,h:r,fps:i}=e,n=this._initOptions.pullInnerCDNProtocol||Sr.FLV,s=this._initOptions.pullInnerCDNUseHttps===Cr.NOT_HTTPS?Cr.NOT_HTTPS:Cr.HTTPS;if(!this._CDNUris.url)return T.error(`cdn_uris url is empty, the anchor need to open or push CDN, code: ${I.CDN_RESOURCE_IS_EMPTY}`),{code:I.CDN_RESOURCE_IS_EMPTY};const o={"App-Key":this._context.getAppkey(),Token:this._joinResData.token,RoomId:this.getRoomId(),UserId:this._context.getCurrentId(),SessionId:this.getSessionId()},a=[];t&&a.push(`w=${t}`),r&&a.push(`h=${r}`),i&&a.push(`fps=${i}`),a.push(`kind=${n}`),a.push(`is_https=${s}`);const c=a.join("&");let d=`${this._CDNUris.url}?`;c&&(d+=c);const{code:u,res:l}=yield this._service.getCDNResourceInfo(o,d);return u!==I.SUCCESS?(T.error(`getCDNPlayUrl failed: ${u}`),{code:u}):(T.info(`getCDNPlayUrl success: ${null==l?void 0:l.data.pull_url}`),{code:u,CDNPlayUrl:null==l?void 0:l.data.pull_url})}))}getCDNPlayUrl(e,t){return C(this,void 0,void 0,(function*(){if(e&&!It(e))return T.error("`resolution` is invalid"),{code:I.PARAMS_ERROR};if(t&&!Et(t))return T.error("`fps` is invalid"),{code:I.PARAMS_ERROR};const{width:r,height:i}=e?Tt(e):{width:null,height:null},n=t?yt(t):null,s={};return r&&(s.w=r),i&&(s.h=i),n&&(s.fps=n),this._getCDNPlayUrl(s)}))}subscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this._subscribeHandle(e,!1)))}))}__unsubscribe(e){var t;return C(this,void 0,void 0,(function*(){if(!c("tracks",e,(()=>d(e)&&e.length>0&&e.every((e=>e instanceof ot))),!0))return T.error(`unsubscribe failed, tracks is invalid -> roomId: ${this._roomId}`),{code:I.PARAMS_ERROR};const r=this._subscribedList.map((e=>Object.assign({},e))).filter((t=>!e.includes(t.track)));return null===(t=this._polarisReport)||void 0===t||t.sendR2(Qt.SUBSCRIBE,Xt.END,e.map((e=>e.getTrackId()))),this._updateSubListHandle(r,!1)}))}unsubscribe(e){return C(this,void 0,void 0,(function*(){return b((()=>this.__unsubscribe(e)))}))}__destroy(e){var t;return C(this,void 0,void 0,(function*(){this._destroyed||(this._destroyed=!0,null===(t=this._audioLevelReport)||void 0===t||t.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 C(this,void 0,void 0,(function*(){const{code:e}=yield this._context.joinLivingRoomAsAudience(this._roomId,u.LIVE);e!==i.SUCCESS&&T.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 tr(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 Er=(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 yr{constructor(e,t,r){this._context=e,this._runtime=t,this._options=r,this._crtRoom=null,this._audience=null,this._crtAudienceLivingRoom=null,Gt.setSdpSemantics(r.sdpSemantics||"plan-b"),this._service=new Rr(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(e){var t;if(e.conversationType!==o.RTC_ROOM)return!1;if(this._crtRoom instanceof mr){this._getJoinedPKRoomList().forEach((t=>{t.__parseInnerMessage(e)}))}return null===(t=this._crtRoom)||void 0===t||t.__parseInnerMessage(e),!0}_getJoinedPKRoomList(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===I.SUCCESS&&t){const e=t.getJoinedPKRooms()||{};return Object.values(e)}return[]}_getPKRoomIds(){const{code:e,roomPKHandler:t}=this._crtRoom.getRoomPKHandler();if(e===I.SUCCESS&&t){const e=t.getAllPKInfo();return Object.keys(e)}return[]}getCurrentId(){return this._context.getCurrentId()}joinRTCRoom(e,t,r){return b((()=>this._joinRTCRoom(e,t,r)))}_joinRTCRoom(e,t,r){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0))return{code:I.PARAMS_ERROR};if(!c("outerUserDatas",r,v,!1))return{code:I.PARAMS_ERROR};if(r){if(!Object.keys(r).every((e=>c(`outerUserDatas.${e}`,r[e],f,!0))))return{code:I.PARAMS_ERROR}}if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};T.debug(`joinRoom -> roomId: ${e}; joinType: ${t||R.KICK}`);const{code:s,data:o}=yield this._context.joinRTCRoom(e,u.RTC,void 0,t,void 0,r);if(s!==i.SUCCESS){T.error(`joinRoom failed -> code: ${s}`);return{code:s===E.JOIN_REFUSED?I.SIGNAL_JOIN_RTC_ROOM_REFUSED:s}}T.debug(`joinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(o)}`);const a=new fr(this._context,this._runtime,e,o,this._service,this._options,this._releaseCrtRoomObj.bind(this));return this._crtRoom=a,{room:a,code:I.SUCCESS,userIds:a.getRemoteUserIds(),tracks:a.getRemoteTracks()}}))}joinLivingRoom(e,t,r,i){return b((()=>this._joinLivingRoom(e,t,r,i)))}_joinLivingRoom(e,t,r,s){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===hr.AUDIO||e===hr.VIDEO)))return{code:I.PARAMS_ERROR};if(!c("outerUserDatas",s,v,!1))return{code:I.PARAMS_ERROR};if(s){if(!Object.keys(s).every((e=>c(`outerUserDatas.${e}`,s[e],f,!0))))return{code:I.PARAMS_ERROR}}if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};if(this._context.getConnectionStatus()!==n.CONNECTED)return{code:I.SIGNAL_DISCONNECTED};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};T.debug(`joinRoom, roomId: ${e}`);const{code:o,data:a}=yield this._context.joinRTCRoom(e,u.LIVE,t,r,void 0,s);if(o!==i.SUCCESS)return T.error(`joinRoom failed -> code: ${o}`),{code:o};T.debug(`JoinRoom success -> userId: ${this._context.getCurrentId()}, roomId: ${e}, data: ${JSON.stringify(a)}`);const d=new mr(this._context,this._runtime,e,a,this._service,this._options,this._releaseCrtRoomObj.bind(this),t,!1,!0);this._crtRoom=d;const l={room:d,code:I.SUCCESS,userIds:d.getRemoteUserIds(),tracks:d.getRemoteTracks(),PKRoomIds:this._getPKRoomIds()};return d.__getCDNPushMode()===lr.MANUAL&&Object.assign(l,{CDNEnable:d.__getCDNEnable()}),l}))}getAudienceClient(){return this._audience||(this._audience=new gr(this._context,this._runtime,this._options)),this._audience}_onIMStatusChange(e){if(T.debug(`signal server connection state change: ${e}`),e===n.CONNECTED){if(this._crtRoom instanceof mr){this._getJoinedPKRoomList().forEach((e=>{e.__onReconnected()}))}this._crtRoom&&this._crtRoom.__onReconnected()}}_onIMDisconnect(){T.debug("TODO -> on IM disconnect")}_onIMUninit(){T.debug("TODO -> on IM client ondestroy")}leaveRoom(e){return b((()=>this._leaveRoom(e)))}_leaveRoom(e){return C(this,void 0,void 0,(function*(){return this._crtRoom?(yield this._crtRoom.__destroy(!0),T.debug(`quitRTCRoom -> userId: ${this._context.getCurrentId()} , roomId: ${this._crtRoom.getRoomId()}`),this._crtRoom=null,{code:I.SUCCESS}):{code:I.SUCCESS}}))}_releaseCrtRoomObj(){this._crtRoom=null}_getMediaStream(e,t="getUserMedia"){return C(this,void 0,void 0,(function*(){try{const r=yield navigator.mediaDevices[t](e);return{code:I.SUCCESS,stream:r}}catch(e){if("Permission denied"===e.message)return{code:I.PERMISSION_DENIED};T.error(`get user media failed -> ${e.message}`)}return{code:"getUserMedia"===t?I.GET_USER_MEDIA_FAILED:I.GET_DISPLAY_MEDIA_FAILED}}))}createMicrophoneAudioTrack(e="RongCloudRTC",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};const{stream:i,code:n}=yield this._getMediaStream({audio:{deviceId:null==t?void 0:t.micphoneId,sampleRate:null==t?void 0:t.sampleRate}});if(n!==I.SUCCESS)return{code:n};const s=i.getAudioTracks()[0];return{code:n,track:new it(e,r,s)}}))}createCameraVideoTrack(e="RongCloudRTC",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};const i=It(null==t?void 0:t.resolution)?t.resolution:Ke.W640_H480,{width:n,height:s}=Tt(i),{stream:o,code:a}=yield this._getMediaStream({video:{deviceId:null==t?void 0:t.cameraId,frameRate:yt((null==t?void 0:t.frameRate)||Be.FPS_15),width:n,height:s,facingMode:null==t?void 0:t.faceMode}});if(a!==I.SUCCESS)return{code:a};const c=o.getVideoTracks()[0];return{code:a,track:new nt(e,r,c)}}))}createMicrophoneAndCameraTracks(e="RongCloudRTC",t){var r,i,n,s,o,a;return C(this,void 0,void 0,(function*(){const c=[];if(!lt(e))return{code:I.INVALID_TAGS,tracks:c};const d=this._context.getCurrentId();if(!d)return{code:I.INVALID_USER_ID,tracks:c};const u=It(null===(r=null==t?void 0:t.video)||void 0===r?void 0:r.resolution)?t.video.resolution:Ke.W640_H480,{width:l,height:h}=Tt(u),{stream:p,code:_}=yield this._getMediaStream({video:{deviceId:null===(i=null==t?void 0:t.video)||void 0===i?void 0:i.cameraId,frameRate:yt((null===(n=null==t?void 0:t.video)||void 0===n?void 0:n.frameRate)||Be.FPS_15),width:l,height:h,facingMode:null===(s=null==t?void 0:t.video)||void 0===s?void 0:s.faceMode},audio:{deviceId:null===(o=null==t?void 0:t.audio)||void 0===o?void 0:o.micphoneId,sampleRate:null===(a=null==t?void 0:t.audio)||void 0===a?void 0:a.sampleRate}});return _!==I.SUCCESS||p.getTracks().forEach((t=>{"video"===t.kind?c.push(new nt(e,d,t)):c.unshift(new it(e,d,t))})),{code:_,tracks:c}}))}createScreenVideoTrack(e="screenshare",t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};const r=this._context.getCurrentId();if(!r)return{code:I.INVALID_USER_ID};if(!Pt())return{code:I.BROWSER_NOT_SUPPORT};const i=/Electron/.test(navigator.userAgent);if(i&&!(null==t?void 0:t.chromeMediaSourceId))return{code:I.PARAMS_ERROR};const n=It(null==t?void 0:t.resolution)?t.resolution:Ke.W1280_H720,{width:s,height:o}=Tt(n),a=i?{mandatory:{chromeMediaSourceId:t.chromeMediaSourceId,chromeMediaSource:"desktop",minWidth:s,maxWidth:s,minHeight:o,maxHeight:o}}:{frameRate:yt((null==t?void 0:t.frameRate)||Be.FPS_15),width:s,height:o},{stream:c,code:d}=yield this._getMediaStream({video:a,audio:!1},i?"getUserMedia":"getDisplayMedia");if(d!==I.SUCCESS)return{code:d};const u=c.getVideoTracks()[0];return{code:d,track:new st(e,r,u)}}))}createLocalAudioTrack(e,t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"audio"!==t.kind)return{code:I.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:I.SUCCESS,track:new Xe(e,r,t)}:{code:I.INVALID_USER_ID}}))}createLocalVideoTrack(e,t){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS};if(!t||"[object MediaStreamTrack]"!==t.toString()||"video"!==t.kind)return{code:I.CREATE_CUSTOM_TRACK_FAILED};const r=this._context.getCurrentId();return r?{code:I.SUCCESS,track:new Ze(e,r,t)}:{code:I.INVALID_USER_ID}}))}createLocalFileTracks(e,t,r){return C(this,void 0,void 0,(function*(){if(!lt(e))return{code:I.INVALID_TAGS,tracks:[]};if(!bt())return{code:I.BROWSER_NOT_SUPPORT,tracks:[]};const i=t instanceof File?URL.createObjectURL(t):t;if(!l(i)&&!/^blob:/.test(i))return T.warn(`createLocalFileTracks failed: params error -> url: ${i}`),{code:I.PARAMS_ERROR,tracks:[]};const n=this._context.getCurrentId();return n?new Promise((t=>{const s=document.createElement("video");(null==r?void 0:r.withoutAudio)&&(s.muted=!0),s.onloadedmetadata=()=>{const o=[];let a;try{const e=s.mozCaptureStream?"mozCaptureStream":"captureStream";a=s[e]()}catch(e){T.error(`create RCLocalFileTrack failed, captureSteam error. -> url: ${i}`),T.error(e),t({code:I.CREATE_FILE_TRACK_FAILED,tracks:o})}const[c,d]=Er(a,r);c&&o.push(new rt(e,n,c,s)),d&&o.push(new tt(e,n,d,s)),0===o.length&&(s.pause(),s.src=""),s.onerror=null,t({code:I.SUCCESS,tracks:o})},s.onerror=()=>{T.error(`create RCLocalFileTrack failed -> url: ${i}`),t({code:I.CREATE_FILE_TRACK_FAILED,tracks:[]})},s.src=i,s.loop=!0,s.play()})):{code:I.INVALID_USER_ID,tracks:[]}}))}createLocalTracks(e,t,r){return C(this,void 0,void 0,(function*(){const i=[];if(!lt(e))return{code:I.INVALID_TAGS,tracks:i};if(!(t instanceof MediaStream))return{code:I.PARAMS_ERROR,tracks:i};const n=this._context.getCurrentId();if(!n)return{code:I.INVALID_USER_ID,tracks:i};const[s,o]=Er(t,r);return s&&i.push(new Xe(e,n,s)),o&&i.push(new Ze(e,n,o)),{code:I.SUCCESS,tracks:i}}))}joinLivingRoomAsAudience(e,t){return C(this,void 0,void 0,(function*(){if(Lt(this._context.getNaviInfo()))return{code:I.PACKAGE_ENVIRONMENT_ERROR};if(!c("roomId",e,h,!0)||!c("livingType",t,(e=>e===hr.AUDIO||e===hr.VIDEO)))return{code:I.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:I.REPERT_JOIN_ROOM};if(!this._service.getNaviMS().length)return{code:I.NOT_OPEN_VIDEO_AUDIO_SERVER};const{code:r,data:n}=yield this._context.joinLivingRoomAsAudience(e,u.LIVE,t);if(r!==i.SUCCESS)return T.error("audienceJoinLivingRoomError:",r),{code:I.SIGNAL_AUDIENCE_JOIN_ROOM_FAILED};T.info(`joinLivingRoomAsAudience success, room data: ${JSON.stringify(n)}`);const s=new Ir(this._context,this._runtime,this._options,e,n,t);return this._crtAudienceLivingRoom=s,{room:s,code:I.SUCCESS,userIds:s.getRemoteUserIds(),RTCTracks:s.getRemoteRTCTracks(),MCUTracks:s.getRemoteMCUTracks(),CDNUris:s.getCDNInfo()}}))}leaveLivingRoomAsAudience(e){return C(this,void 0,void 0,(function*(){return this._crtAudienceLivingRoom?this._crtAudienceLivingRoom!==e?{code:I.PARAMS_ERROR}:(yield this._crtAudienceLivingRoom.__destroy(!0),this._crtAudienceLivingRoom=null,{code:I.SUCCESS}):{code:I.SUCCESS}}))}upgradeToAnchorRoom(e){return C(this,void 0,void 0,(function*(){if(!c("room._roomId",e._roomId,h,!0))return{code:I.PARAMS_ERROR};if(this._crtRoom)return{code:I.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,g.ViewerToAnchor,e._livingType);if(t!==i.SUCCESS)return T.error("change room identity error",t),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};yield this._crtAudienceLivingRoom.__destroy(!1);const n=new mr(this._context,this._runtime,e._roomId,r,this._service,this._options,this._releaseCrtRoomObj.bind(this),e._livingType,!0,!0);return this._crtRoom=n,this._crtAudienceLivingRoom=null,{room:n,code:I.SUCCESS,userIds:e.getRemoteUserIds(),tracks:n.getRemoteTracks()}}))}downgradeToAudienceRoom(e){return C(this,void 0,void 0,(function*(){if(!e.isMainRoom())return T.error("the `downgradeToAudienceRoom` is disabled in PK room"),{code:I.THE_FUNCTION_IS_DISABLED_IN_PKROOM};if(!c("room._roomId",e._roomId,h,!0))return{code:I.PARAMS_ERROR};if(this._crtAudienceLivingRoom)return{code:I.REPERT_JOIN_ROOM};const{code:t,data:r}=yield this._context.rtcIdentityChange(e._roomId,g.AnchorToViewer,e.getLivingType());if(t!==i.SUCCESS)return T.error("change room identity error",t),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED};T.info(`downgradeToAudienceRoom success, room data: ${JSON.stringify(r)}`);const n=new Ir(this._context,this._runtime,this._options,e._roomId,r,e.getLivingType());return this._crtAudienceLivingRoom=n,this._crtRoom.__destroy(!1),this._crtRoom=null,{room:n,code:I.SUCCESS,userIds:n.getRemoteUserIds(),RTCTracks:n.getRemoteRTCTracks(),MCUTracks:n.getRemoteMCUTracks(),CDNUris:n.getCDNInfo()}}))}getJoinedRoomInfo(){return C(this,void 0,void 0,(function*(){const{code:e,data:t}=yield this._context.getRTCJoinedUserInfo(this._context.getCurrentId());return e!==i.SUCCESS?(T.error("getJoinedUserInfo error",e),{code:I.SIGNAL_ROOM_CHANGE_IDENTITY_FAILED}):{code:I.SUCCESS,data:t}}))}}var kr;!function(e){e[e.SERVER_KICK=1]="SERVER_KICK",e[e.OTHER_KICK=2]="OTHER_KICK"}(kr||(kr={}));const br={tag:"RCRTC",verify:e=>"browser"!==e.tag?(T.error(`RCRTC Plugin is not support the runtime '${e.tag}'`),!1):ht?(S.add("plugin-rtc","5.3.5"),!!S.validEngine(">=5.1.2")||(T.error(`The current engine version '${S.getInfo().engine}' error, plugin-rtc required engine version at least '>=5.1.2'.`),!1)):(T.error("Please use the https protocol or use `http://localhost` to open the page!"),!1),setup:(e,t,i={})=>(T.setLogLevel(i.logLevel),T.setLogStdout(i.logStdout),T.warn("RCRTC Version: 5.3.5, Commit: 812bb452e2979607773fd0096a3730f9fe5b9198"),T.warn(`browserInfo.browser -> ${kt.browser}`),T.warn(`browserInfo.supportsUnifiedPlan -> ${kt.supportsUnifiedPlan}`),T.warn(`browserInfo.version -> ${kt.version}`),s("options.mediaServer",i.mediaServer,(e=>!(!l(e)||"https:"===location.protocol&&!/^https/.test(e)))),s("options.timeout",i.timeout,(e=>r(e)&&e>=5e3&&e<=3e4)),s("options.pingGap",i.pingGap,(e=>r(e)&&e>=3e3&&e<=1e4)),new yr(e,t,i))},Pr={DEFAULT:"RongCloudRTC"},Or={transResolution:Tt,transFrameRate:yt,parseTrackId:vt,ifSupportLocalFileTrack:bt,ifSupportScreenShare:Pt};export{nr as BackgroundPictureFillMode,sr as MixLayoutMode,or as MixVideoRenderMode,ir as RCAbstractRoom,gr as RCAudienceClient,Ir as RCAudienceLivingRoom,nt as RCCameraVideoTrack,Be as RCFrameRate,Cr as RCInnerCDNPullIsHttps,Sr as RCInnerCDNPullKind,kr as RCKickReason,mr as RCLivingRoom,hr as RCLivingType,Xe as RCLocalAudioTrack,rt as RCLocalFileAudioTrack,et as RCLocalFileTrack,tt as RCLocalFileVideoTrack,Qe as RCLocalTrack,Ze as RCLocalVideoTrack,cr as RCMCUConfigBuilder,Fe as RCMediaType,it as RCMicphoneAudioTrack,yr as RCRTCClient,I as RCRTCCode,Zt as RCRTCLiveRole,At as RCRTCPingResult,fr as RCRTCRoom,at as RCRemoteAudioTrack,ot as RCRemoteTrack,ct as RCRemoteVideoTrack,Ke as RCResolution,st as RCScreenVideoTrack,Pr as RCTag,ze as RCTrack,qe as device,Or as helper,br as installer};
|